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
|
philippboehmsturm/antx-master
|
spm_cfg_fmri_spec.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_fmri_spec.m
| 42,012 |
utf_8
|
7692832cbcb1b1b77dff681c2a7319f9
|
function fmri_spec = spm_cfg_fmri_spec
% SPM Configuration file for fMRI model specification
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% $Id: spm_cfg_fmri_spec.m 637 2011-05-11 09:53:31Z vglauche $
rev = '$Rev: 637 $';
% ---------------------------------------------------------------------
% dir Directory
% ---------------------------------------------------------------------
dir = cfg_files;
dir.tag = 'dir';
dir.name = 'Directory';
dir.help = {'Select a directory where the SPM.mat file containing the specified design matrix will be written.'};
dir.filter = 'dir';
dir.ufilter = '.*';
dir.num = [1 1];
% ---------------------------------------------------------------------
% units Units for design
% ---------------------------------------------------------------------
units = cfg_menu;
units.tag = 'units';
units.name = 'Units for design';
units.help = {'The onsets of events or blocks can be specified in either scans or seconds.'};
units.labels = {
'Scans'
'Seconds'
}';
units.values = {
'scans'
'secs'
}';
% ---------------------------------------------------------------------
% RT Interscan interval
% ---------------------------------------------------------------------
RT = cfg_entry;
RT.tag = 'RT';
RT.name = 'Interscan interval';
RT.help = {'Interscan interval, TR, (specified in seconds). This is the time between acquiring a plane of one volume and the same plane in the next volume. It is assumed to be constant throughout.'};
RT.strtype = 'e';
RT.num = [1 1];
% ---------------------------------------------------------------------
% fmri_t Microtime resolution
% ---------------------------------------------------------------------
fmri_t = cfg_entry;
fmri_t.tag = 'fmri_t';
fmri_t.name = 'Microtime resolution';
fmri_t.help = {
'The microtime resolution, t, is the number of time-bins per scan used when building regressors. '
''
'Do not change this parameter unless you have a long TR and wish to shift regressors so that they are aligned to a particular slice. '
}';
fmri_t.strtype = 'e';
fmri_t.num = [1 1];
fmri_t.def = @(val)spm_get_defaults('stats.fmri.fmri_t', val{:});
% ---------------------------------------------------------------------
% fmri_t0 Microtime onset
% ---------------------------------------------------------------------
fmri_t0 = cfg_entry;
fmri_t0.tag = 'fmri_t0';
fmri_t0.name = 'Microtime onset';
fmri_t0.help = {
'The microtime onset, t0, is the first time-bin at which the regressors are resampled to coincide with data acquisition. If t0 = 1 then the regressors will be appropriate for the first slice. If you want to temporally realign the regressors so that they match responses in the middle slice then make t0 = t/2 (assuming there is a negligible gap between volume acquisitions). '
''
'Do not change the default setting unless you have a long TR. '
}';
fmri_t0.strtype = 'e';
fmri_t0.num = [1 1];
fmri_t0.def = @(val)spm_get_defaults('stats.fmri.fmri_t0', val{:});
% ---------------------------------------------------------------------
% timing Timing parameters
% ---------------------------------------------------------------------
timing = cfg_branch;
timing.tag = 'timing';
timing.name = 'Timing parameters';
timing.val = {units RT fmri_t fmri_t0 };
timing.help = {
'Specify various timing parameters needed to construct the design matrix. This includes the units of the design specification and the interscan interval.'
''
'Also, with longs TRs you may want to shift the regressors so that they are aligned to a particular slice. This is effected by changing the microtime resolution and onset. '
}';
% ---------------------------------------------------------------------
% scans Scans
% ---------------------------------------------------------------------
scans = cfg_files;
scans.tag = 'scans';
scans.name = 'Scans';
scans.help = {'Select the fMRI scans for this session. They must all have the same image dimensions, orientation, voxel size etc.'};
scans.filter = 'image';
scans.ufilter = '.*';
scans.num = [1 Inf];
% ---------------------------------------------------------------------
% name Name
% ---------------------------------------------------------------------
name = cfg_entry;
name.tag = 'name';
name.name = 'Name';
name.help = {'Condition Name'};
name.strtype = 's';
name.num = [1 Inf];
% ---------------------------------------------------------------------
% onset Onsets
% ---------------------------------------------------------------------
onset = cfg_entry;
onset.tag = 'onset';
onset.name = 'Onsets';
onset.help = {'Specify a vector of onset times for this condition type. '};
onset.strtype = 'e';
onset.num = [Inf 1];
% ---------------------------------------------------------------------
% duration Durations
% ---------------------------------------------------------------------
duration = cfg_entry;
duration.tag = 'duration';
duration.name = 'Durations';
duration.help = {'Specify the event durations. Epoch and event-related responses are modeled in exactly the same way but by specifying their different durations. Events are specified with a duration of 0. If you enter a single number for the durations it will be assumed that all trials conform to this duration. If you have multiple different durations, then the number must match the number of onset times.'};
duration.strtype = 'e';
duration.num = [Inf 1];
% ---------------------------------------------------------------------
% tmod Time Modulation
% ---------------------------------------------------------------------
tmod = cfg_menu;
tmod.tag = 'tmod';
tmod.name = 'Time Modulation';
tmod.help = {
'This option allows for the characterisation of linear or nonlinear time effects. For example, 1st order modulation would model the stick functions and a linear change of the stick function heights over time. Higher order modulation will introduce further columns that contain the stick functions scaled by time squared, time cubed etc.'
''
'Interactions or response modulations can enter at two levels. Firstly the stick function itself can be modulated by some parametric variate (this can be time or some trial-specific variate like reaction time) modeling the interaction between the trial and the variate or, secondly interactions among the trials themselves can be modeled using a Volterra series formulation that accommodates interactions over time (and therefore within and between trial types).'
}';
tmod.labels = {
'No Time Modulation'
'1st order Time Modulation'
'2nd order Time Modulation'
'3rd order Time Modulation'
'4th order Time Modulation'
'5th order Time Modulation'
'6th order Time Modulation'
}';
tmod.values = {0 1 2 3 4 5 6};
tmod.val = {0};
% ---------------------------------------------------------------------
% name Name
% ---------------------------------------------------------------------
name1 = cfg_entry;
name1.tag = 'name';
name1.name = 'Name';
name1.help = {'Enter a name for this parameter.'};
name1.strtype = 's';
name1.num = [1 Inf];
% ---------------------------------------------------------------------
% param Values
% ---------------------------------------------------------------------
param = cfg_entry;
param.tag = 'param';
param.name = 'Values';
param.help = {'Enter a vector of values, one for each occurence of the event.'};
param.strtype = 'e';
param.num = [Inf 1];
% ---------------------------------------------------------------------
% poly Polynomial Expansion
% ---------------------------------------------------------------------
poly = cfg_menu;
poly.tag = 'poly';
poly.name = 'Polynomial Expansion';
poly.help = {'For example, 1st order modulation would model the stick functions and a linear change of the stick function heights over different values of the parameter. Higher order modulation will introduce further columns that contain the stick functions scaled by parameter squared, cubed etc.'};
poly.labels = {
'1st order'
'2nd order'
'3rd order'
'4th order'
'5th order'
'6th order'
}';
poly.values = {1 2 3 4 5 6};
% ---------------------------------------------------------------------
% pmod Parameter
% ---------------------------------------------------------------------
pmod = cfg_branch;
pmod.tag = 'pmod';
pmod.name = 'Parameter';
pmod.val = {name1 param poly };
pmod.help = {
'Model interractions with user specified parameters. This allows nonlinear effects relating to some other measure to be modelled in the design matrix.'
''
'Interactions or response modulations can enter at two levels. Firstly the stick function itself can be modulated by some parametric variate (this can be time or some trial-specific variate like reaction time) modeling the interaction between the trial and the variate or, secondly interactions among the trials themselves can be modeled using a Volterra series formulation that accommodates interactions over time (and therefore within and between trial types).'
}';
% ---------------------------------------------------------------------
% generic Parametric Modulations
% ---------------------------------------------------------------------
generic2 = cfg_repeat;
generic2.tag = 'generic';
generic2.name = 'Parametric Modulations';
generic2.help = {'The stick function itself can be modulated by some parametric variate (this can be time or some trial-specific variate like reaction time) modeling the interaction between the trial and the variate. The events can be modulated by zero or more parameters.'};
generic2.values = {pmod };
generic2.num = [0 Inf];
% ---------------------------------------------------------------------
% cond Condition
% ---------------------------------------------------------------------
cond = cfg_branch;
cond.tag = 'cond';
cond.name = 'Condition';
cond.val = {name onset duration tmod generic2 };
cond.check = @cond_check;
cond.help = {'An array of input functions is contructed, specifying occurrence events or epochs (or both). These are convolved with a basis set at a later stage to give regressors that enter into the design matrix. Interactions of evoked responses with some parameter (time or a specified variate) enter at this stage as additional columns in the design matrix with each trial multiplied by the [expansion of the] trial-specific parameter. The 0th order expansion is simply the main effect in the first column.'};
% ---------------------------------------------------------------------
% generic Conditions
% ---------------------------------------------------------------------
generic1 = cfg_repeat;
generic1.tag = 'generic';
generic1.name = 'Conditions';
generic1.help = {'You are allowed to combine both event- and epoch-related responses in the same model and/or regressor. Any number of condition (event or epoch) types can be specified. Epoch and event-related responses are modeled in exactly the same way by specifying their onsets [in terms of onset times] and their durations. Events are specified with a duration of 0. If you enter a single number for the durations it will be assumed that all trials conform to this duration.For factorial designs, one can later associate these experimental conditions with the appropriate levels of experimental factors. '};
generic1.values = {cond };
generic1.num = [0 Inf];
% ---------------------------------------------------------------------
% multi Multiple conditions
% ---------------------------------------------------------------------
multi = cfg_files;
multi.tag = 'multi';
multi.name = 'Multiple conditions';
multi.val{1} = {''};
multi.help = {
'Select the *.mat file containing details of your multiple experimental conditions. '
''
'If you have multiple conditions then entering the details a condition at a time is very inefficient. This option can be used to load all the required information in one go. You will first need to create a *.mat file containing the relevant information. '
''
'This *.mat file must include the following cell arrays (each 1 x n): names, onsets and durations. eg. names=cell(1,5), onsets=cell(1,5), durations=cell(1,5), then names{2}=''SSent-DSpeak'', onsets{2}=[3 5 19 222], durations{2}=[0 0 0 0], contain the required details of the second condition. These cell arrays may be made available by your stimulus delivery program, eg. COGENT. The duration vectors can contain a single entry if the durations are identical for all events.'
''
'Time and Parametric effects can also be included. For time modulation include a cell array (1 x n) called tmod. It should have a have a single number in each cell. Unused cells may contain either a 0 or be left empty. The number specifies the order of time modulation from 0 = No Time Modulation to 6 = 6th Order Time Modulation. eg. tmod{3} = 1, modulates the 3rd condition by a linear time effect.'
''
'For parametric modulation include a structure array, which is up to 1 x n in size, called pmod. n must be less than or equal to the number of cells in the names/onsets/durations cell arrays. The structure array pmod must have the fields: name, param and poly. Each of these fields is in turn a cell array to allow the inclusion of one or more parametric effects per column of the design. The field name must be a cell array containing strings. The field param is a cell array containing a vector of parameters. Remember each parameter must be the same length as its corresponding onsets vector. The field poly is a cell array (for consistency) with each cell containing a single number specifying the order of the polynomial expansion from 1 to 6.'
''
'Note that each condition is assigned its corresponding entry in the structure array (condition 1 parametric modulators are in pmod(1), condition 2 parametric modulators are in pmod(2), etc. Within a condition multiple parametric modulators are accessed via each fields cell arrays. So for condition 1, parametric modulator 1 would be defined in pmod(1).name{1}, pmod(1).param{1}, and pmod(1).poly{1}. A second parametric modulator for condition 1 would be defined as pmod(1).name{2}, pmod(1).param{2} and pmod(1).poly{2}. If there was also a parametric modulator for condition 2, then remember the first modulator for that condition is in cell array 1: pmod(2).name{1}, pmod(2).param{1}, and pmod(2).poly{1}. If some, but not all conditions are parametrically modulated, then the non-modulated indices in the pmod structure can be left blank. For example, if conditions 1 and 3 but not condition 2 are modulated, then specify pmod(1) and pmod(3). Similarly, if conditions 1 and 2 are modulated but there are 3 conditions overall, it is only necessary for pmod to be a 1 x 2 structure array.'
''
'EXAMPLE:'
'Make an empty pmod structure: '
' pmod = struct(''name'',{''''},''param'',{},''poly'',{});'
'Specify one parametric regressor for the first condition: '
' pmod(1).name{1} = ''regressor1'';'
' pmod(1).param{1} = [1 2 4 5 6];'
' pmod(1).poly{1} = 1;'
'Specify 2 parametric regressors for the second condition: '
' pmod(2).name{1} = ''regressor2-1'';'
' pmod(2).param{1} = [1 3 5 7]; '
' pmod(2).poly{1} = 1;'
' pmod(2).name{2} = ''regressor2-2'';'
' pmod(2).param{2} = [2 4 6 8 10];'
' pmod(2).poly{2} = 1;'
''
'The parametric modulator should be mean corrected if appropriate. Unused structure entries should have all fields left empty.'
}';
multi.filter = 'mat';
multi.ufilter = '.*';
multi.num = [0 1];
% ---------------------------------------------------------------------
% name Name
% ---------------------------------------------------------------------
name = cfg_entry;
name.tag = 'name';
name.name = 'Name';
name.help = {'Enter name of regressor eg. First movement parameter'};
name.strtype = 's';
name.num = [1 Inf];
% ---------------------------------------------------------------------
% val Value
% ---------------------------------------------------------------------
val = cfg_entry;
val.tag = 'val';
val.name = 'Value';
val.help = {'Enter the vector of regressor values'};
val.strtype = 'e';
val.num = [Inf 1];
% ---------------------------------------------------------------------
% regress Regressor
% ---------------------------------------------------------------------
regress = cfg_branch;
regress.tag = 'regress';
regress.name = 'Regressor';
regress.val = {name val };
regress.help = {'regressor'};
% ---------------------------------------------------------------------
% generic Regressors
% ---------------------------------------------------------------------
generic2 = cfg_repeat;
generic2.tag = 'generic';
generic2.name = 'Regressors';
generic2.help = {'Regressors are additional columns included in the design matrix, which may model effects that would not be convolved with the haemodynamic response. One such example would be the estimated movement parameters, which may confound the data.'};
generic2.values = {regress };
generic2.num = [0 Inf];
% ---------------------------------------------------------------------
% multi_reg Multiple regressors
% ---------------------------------------------------------------------
multi_reg = cfg_files;
multi_reg.tag = 'multi_reg';
multi_reg.name = 'Multiple regressors';
multi_reg.val{1} = {''};
multi_reg.help = {
'Select the *.mat/*.txt file containing details of your multiple regressors. '
''
'If you have multiple regressors eg. realignment parameters, then entering the details a regressor at a time is very inefficient. This option can be used to load all the required information in one go. '
''
'You will first need to create a *.mat file containing a matrix R or a *.txt file containing the regressors. Each column of R will contain a different regressor. When SPM creates the design matrix the regressors will be named R1, R2, R3, ..etc.'
}';
multi_reg.filter = 'mat';
multi_reg.ufilter = '.*';
multi_reg.num = [0 1];
% ---------------------------------------------------------------------
% hpf High-pass filter
% ---------------------------------------------------------------------
hpf = cfg_entry;
hpf.tag = 'hpf';
hpf.name = 'High-pass filter';
hpf.help = {'The default high-pass filter cutoff is 128 seconds.Slow signal drifts with a period longer than this will be removed. Use ''explore design'' to ensure this cut-off is not removing too much experimental variance. High-pass filtering is implemented using a residual forming matrix (i.e. it is not a convolution) and is simply to a way to remove confounds without estimating their parameters explicitly. The constant term is also incorporated into this filter matrix.'};
hpf.strtype = 'e';
hpf.num = [1 1];
hpf.def = @(val)spm_get_defaults('stats.fmri.hpf', val{:});
% ---------------------------------------------------------------------
% sess Subject/Session
% ---------------------------------------------------------------------
sess = cfg_branch;
sess.tag = 'sess';
sess.name = 'Subject/Session';
sess.val = {scans generic1 multi generic2 multi_reg hpf };
sess.check = @sess_check;
sess.help = {'The design matrix for fMRI data consists of one or more separable, session-specific partitions. These partitions are usually either one per subject, or one per fMRI scanning session for that subject.'};
% ---------------------------------------------------------------------
% generic Data & Design
% ---------------------------------------------------------------------
generic = cfg_repeat;
generic.tag = 'generic';
generic.name = 'Data & Design';
generic.help = {
'The design matrix defines the experimental design and the nature of hypothesis testing to be implemented. The design matrix has one row for each scan and one column for each effect or explanatory variable. (e.g. regressor or stimulus function). '
''
'This allows you to build design matrices with separable session-specific partitions. Each partition may be the same (in which case it is only necessary to specify it once) or different. Responses can be either event- or epoch related, where the latter model involves prolonged and possibly time-varying responses to state-related changes in experimental conditions. Event-related response are modelled in terms of responses to instantaneous events. Mathematically they are both modelled by convolving a series of delta (stick) or box-car functions, encoding the input or stimulus function. with a set of hemodynamic basis functions.'
}';
generic.values = {sess };
generic.num = [1 Inf];
% ---------------------------------------------------------------------
% name Name
% ---------------------------------------------------------------------
name = cfg_entry;
name.tag = 'name';
name.name = 'Name';
name.help = {'Name of factor, eg. ''Repetition'' '};
name.strtype = 's';
name.num = [1 Inf];
% ---------------------------------------------------------------------
% levels Levels
% ---------------------------------------------------------------------
levels = cfg_entry;
levels.tag = 'levels';
levels.name = 'Levels';
levels.help = {'Enter number of levels for this factor, eg. 2'};
levels.strtype = 'e';
levels.num = [Inf 1];
% ---------------------------------------------------------------------
% fact Factor
% ---------------------------------------------------------------------
fact = cfg_branch;
fact.tag = 'fact';
fact.name = 'Factor';
fact.val = {name levels };
fact.help = {'Add a new factor to your experimental design'};
% ---------------------------------------------------------------------
% generic Factorial design
% ---------------------------------------------------------------------
generic1 = cfg_repeat;
generic1.tag = 'generic';
generic1.name = 'Factorial design';
generic1.help = {
'If you have a factorial design then SPM can automatically generate the contrasts necessary to test for the main effects and interactions. '
''
'This includes the F-contrasts necessary to test for these effects at the within-subject level (first level) and the simple contrasts necessary to generate the contrast images for a between-subject (second-level) analysis.'
''
'To use this option, create as many factors as you need and provide a name and number of levels for each. SPM assumes that the condition numbers of the first factor change slowest, the second factor next slowest etc. It is best to write down the contingency table for your design to ensure this condition is met. This table relates the levels of each factor to the conditions. '
''
'For example, if you have 2-by-3 design your contingency table has two rows and three columns where the the first factor spans the rows, and the second factor the columns. The numbers of the conditions are 1,2,3 for the first row and 4,5,6 for the second. '
}';
generic1.values = {fact };
generic1.num = [0 Inf];
% ---------------------------------------------------------------------
% derivs Model derivatives
% ---------------------------------------------------------------------
derivs = cfg_menu;
derivs.tag = 'derivs';
derivs.name = 'Model derivatives';
derivs.help = {'Model HRF Derivatives. The canonical HRF combined with time and dispersion derivatives comprise an ''informed'' basis set, as the shape of the canonical response conforms to the hemodynamic response that is commonly observed. The incorporation of the derivate terms allow for variations in subject-to-subject and voxel-to-voxel responses. The time derivative allows the peak response to vary by plus or minus a second and the dispersion derivative allows the width of the response to vary. The informed basis set requires an SPM{F} for inference. T-contrasts over just the canonical are perfectly valid but assume constant delay/dispersion. The informed basis set compares favourably with eg. FIR bases on many data sets. '};
derivs.labels = {
'No derivatives'
'Time derivatives'
'Time and Dispersion derivatives'
}';
derivs.values = {[0 0] [1 0] [1 1]};
derivs.val = {[0 0]};
% ---------------------------------------------------------------------
% hrf Canonical HRF
% ---------------------------------------------------------------------
hrf = cfg_branch;
hrf.tag = 'hrf';
hrf.name = 'Canonical HRF';
hrf.val = {derivs };
hrf.help = {'Canonical Hemodynamic Response Function. This is the default option. Contrasts of these effects have a physical interpretation and represent a parsimonious way of characterising event-related responses. This option is also useful if you wish to look separately at activations and deactivations (this is implemented using a t-contrast with a +1 or -1 entry over the canonical regressor). '};
% ---------------------------------------------------------------------
% length Window length
% ---------------------------------------------------------------------
length = cfg_entry;
length.tag = 'length';
length.name = 'Window length';
length.help = {'Post-stimulus window length (in seconds)'};
length.strtype = 'e';
length.num = [1 1];
% ---------------------------------------------------------------------
% order Order
% ---------------------------------------------------------------------
order = cfg_entry;
order.tag = 'order';
order.name = 'Order';
order.help = {'Number of basis functions'};
order.strtype = 'e';
order.num = [1 1];
% ---------------------------------------------------------------------
% fourier Fourier Set
% ---------------------------------------------------------------------
fourier = cfg_branch;
fourier.tag = 'fourier';
fourier.name = 'Fourier Set';
fourier.val = {length order };
fourier.help = {'Fourier basis functions. This option requires an SPM{F} for inference.'};
% ---------------------------------------------------------------------
% length Window length
% ---------------------------------------------------------------------
length = cfg_entry;
length.tag = 'length';
length.name = 'Window length';
length.help = {'Post-stimulus window length (in seconds)'};
length.strtype = 'e';
length.num = [1 1];
% ---------------------------------------------------------------------
% order Order
% ---------------------------------------------------------------------
order = cfg_entry;
order.tag = 'order';
order.name = 'Order';
order.help = {'Number of basis functions'};
order.strtype = 'e';
order.num = [1 1];
% ---------------------------------------------------------------------
% fourier_han Fourier Set (Hanning)
% ---------------------------------------------------------------------
fourier_han = cfg_branch;
fourier_han.tag = 'fourier_han';
fourier_han.name = 'Fourier Set (Hanning)';
fourier_han.val = {length order };
fourier_han.help = {'Fourier basis functions with Hanning Window - requires SPM{F} for inference.'};
% ---------------------------------------------------------------------
% length Window length
% ---------------------------------------------------------------------
length = cfg_entry;
length.tag = 'length';
length.name = 'Window length';
length.help = {'Post-stimulus window length (in seconds)'};
length.strtype = 'e';
length.num = [1 1];
% ---------------------------------------------------------------------
% order Order
% ---------------------------------------------------------------------
order = cfg_entry;
order.tag = 'order';
order.name = 'Order';
order.help = {'Number of basis functions'};
order.strtype = 'e';
order.num = [1 1];
% ---------------------------------------------------------------------
% gamma Gamma Functions
% ---------------------------------------------------------------------
gamma = cfg_branch;
gamma.tag = 'gamma';
gamma.name = 'Gamma Functions';
gamma.val = {length order };
gamma.help = {'Gamma basis functions - requires SPM{F} for inference.'};
% ---------------------------------------------------------------------
% length Window length
% ---------------------------------------------------------------------
length = cfg_entry;
length.tag = 'length';
length.name = 'Window length';
length.help = {'Post-stimulus window length (in seconds)'};
length.strtype = 'e';
length.num = [1 1];
% ---------------------------------------------------------------------
% order Order
% ---------------------------------------------------------------------
order = cfg_entry;
order.tag = 'order';
order.name = 'Order';
order.help = {'Number of basis functions'};
order.strtype = 'e';
order.num = [1 1];
% ---------------------------------------------------------------------
% fir Finite Impulse Response
% ---------------------------------------------------------------------
fir = cfg_branch;
fir.tag = 'fir';
fir.name = 'Finite Impulse Response';
fir.val = {length order };
fir.help = {'Finite impulse response - requires SPM{F} for inference.'};
% ---------------------------------------------------------------------
% bases Basis Functions
% ---------------------------------------------------------------------
bases = cfg_choice;
bases.tag = 'bases';
bases.name = 'Basis Functions';
bases.val = {hrf };
bases.help = {'The most common choice of basis function is the Canonical HRF with or without time and dispersion derivatives. '};
bases.values = {hrf fourier fourier_han gamma fir };
% ---------------------------------------------------------------------
% volt Model Interactions (Volterra)
% ---------------------------------------------------------------------
volt = cfg_menu;
volt.tag = 'volt';
volt.name = 'Model Interactions (Volterra)';
volt.help = {
'Generalized convolution of inputs (U) with basis set (bf).'
''
'For first order expansions the causes are simply convolved (e.g. stick functions) in U.u by the basis functions in bf to create a design matrix X. For second order expansions new entries appear in ind, bf and name that correspond to the interaction among the orginal causes. The basis functions for these efects are two dimensional and are used to assemble the second order kernel. Second order effects are computed for only the first column of U.u.'
'Interactions or response modulations can enter at two levels. Firstly the stick function itself can be modulated by some parametric variate (this can be time or some trial-specific variate like reaction time) modeling the interaction between the trial and the variate or, secondly interactions among the trials themselves can be modeled using a Volterra series formulation that accommodates interactions over time (and therefore within and between trial types).'
}';
volt.labels = {
'Do not model Interactions'
'Model Interactions'
}';
volt.values = {1 2};
volt.val = {1};
% ---------------------------------------------------------------------
% global Global normalisation
% ---------------------------------------------------------------------
xGlobal = cfg_menu;
xGlobal.tag = 'global';
xGlobal.name = 'Global normalisation';
xGlobal.help = {'Global intensity normalisation'};
xGlobal.labels = {
'Scaling'
'None'
}';
xGlobal.values = {
'Scaling'
'None'
}';
xGlobal.val = {'None'};
% ---------------------------------------------------------------------
% mask Explicit mask
% ---------------------------------------------------------------------
mask = cfg_files;
mask.tag = 'mask';
mask.name = 'Explicit mask';
mask.val{1} = {''};
mask.help = {'Specify an image for explicitly masking the analysis. A sensible option here is to use a segmention of structural images to specify a within-brain mask. If you select that image as an explicit mask then only those voxels in the brain will be analysed. This both speeds the estimation and restricts SPMs/PPMs to within-brain voxels. Alternatively, if such structural images are unavailble or no masking is required, then leave this field empty.'};
mask.filter = 'image';
mask.ufilter = '.*';
mask.num = [0 1];
% ---------------------------------------------------------------------
% cvi Serial correlations
% ---------------------------------------------------------------------
cvi = cfg_menu;
cvi.tag = 'cvi';
cvi.name = 'Serial correlations';
cvi.help = {
'Serial correlations in fMRI time series due to aliased biorhythms and unmodelled neuronal activity can be accounted for using an autoregressive AR(1) model during Classical (ReML) parameter estimation. '
''
'This estimate assumes the same correlation structure for each voxel, within each session. ReML estimates are then used to correct for non-sphericity during inference by adjusting the statistics and degrees of freedom appropriately. The discrepancy between estimated and actual intrinsic (i.e. prior to filtering) correlations are greatest at low frequencies. Therefore specification of the high-pass filter is particularly important. '
''
'Serial correlation can be ignored if you choose the ''none'' option. Note that the above options only apply if you later specify that your model will be estimated using the Classical (ReML) approach. If you choose Bayesian estimation these options will be ignored. For Bayesian estimation, the choice of noisemodel (AR model order) is made under the estimation options. '
}';
cvi.labels = {
'none'
'AR(1)'
}';
cvi.values = {
'none'
'AR(1)'
}';
for k = 1:20
label = sprintf('AR(%d) [arfit fixed order]',k);
cvi.labels{end+1} = label;
cvi.values{end+1} = {label k};
end
for k = 1:20
label = sprintf('AR(%d) [arfit estimate order]',k);
cvi.labels{end+1} = label;
cvi.values{end+1} = {label -k};
end
cvi.def = @(val)spm_get_defaults('stats.fmri.cvi', val{:});
% ---------------------------------------------------------------------
% fmri_spec fMRI model specification
% ---------------------------------------------------------------------
fmri_spec = cfg_exbranch;
fmri_spec.tag = 'fmri_spec';
fmri_spec.name = 'fMRI model specification';
fmri_spec.val = {dir timing generic generic1 bases volt xGlobal mask cvi };
fmri_spec.help = {
'Statistical analysis of fMRI data uses a mass-univariate approach based on General Linear Models (GLMs). It comprises the following steps (1) specification of the GLM design matrix, fMRI data files and filtering (2) estimation of GLM paramaters using classical or Bayesian approaches and (3) interrogation of results using contrast vectors to produce Statistical Parametric Maps (SPMs) or Posterior Probability Maps (PPMs).'
''
'The design matrix defines the experimental design and the nature of hypothesis testing to be implemented. The design matrix has one row for each scan and one column for each effect or explanatory variable. (eg. regressor or stimulus function). You can build design matrices with separable session-specific partitions. Each partition may be the same (in which case it is only necessary to specify it once) or different. '
''
'Responses can be either event- or epoch related, the only distinction is the duration of the underlying input or stimulus function. Mathematically they are both modeled by convolving a series of delta (stick) or box functions (u), indicating the onset of an event or epoch with a set of basis functions. These basis functions model the hemodynamic convolution, applied by the brain, to the inputs. This convolution can be first-order or a generalized convolution modeled to second order (if you specify the Volterra option). The same inputs are used by the Hemodynamic model or Dynamic Causal Models which model the convolution explicitly in terms of hidden state variables. '
''
'Basis functions can be used to plot estimated responses to single events once the parameters (i.e. basis function coefficients) have been estimated. The importance of basis functions is that they provide a graceful transition between simple fixed response models (like the box-car) and finite impulse response (FIR) models, where there is one basis function for each scan following an event or epoch onset. The nice thing about basis functions, compared to FIR models, is that data sampling and stimulus presentation does not have to be synchronized thereby allowing a uniform and unbiased sampling of peri-stimulus time.'
''
'Event-related designs may be stochastic or deterministic. Stochastic designs involve one of a number of trial-types occurring with a specified probability at successive intervals in time. These probabilities can be fixed (stationary designs) or time-dependent (modulated or non-stationary designs). The most efficient designs obtain when the probabilities of every trial type are equal. A critical issue in stochastic designs is whether to include null events If you wish to estimate the evoked response to a specific event type (as opposed to differential responses) then a null event must be included (even if it is not modeled explicitly).'
''
'In SPM, analysis of data from multiple subjects typically proceeds in two stages using models at two ''levels''. The ''first level'' models are used to implement a within-subject analysis. Typically there will be as many first level models as there are subjects. Analysis proceeds as described using the ''Specify first level'' and ''Estimate'' options. The results of these analyses can then be presented as ''case studies''. More often, however, one wishes to make inferences about the population from which the subjects were drawn. This is an example of a ''Random-Effects (RFX) analysis'' (or, more properly, a mixed-effects analysis). In SPM, RFX analysis is implemented using the ''summary-statistic'' approach where contrast images from each subject are used as summary measures of subject responses. These are then entered as data into a ''second level'' model. '
}';
fmri_spec.prog = @spm_run_fmri_spec;
fmri_spec.vout = @vout_stats;
fmri_spec.modality = {'FMRI'};
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function t = cond_check(job)
t = {};
if (numel(job.onset) ~= numel(job.duration)) && (numel(job.duration)~=1),
t = {sprintf('"%s": Number of event onsets (%d) does not match the number of durations (%d).',...
job.name, numel(job.onset),numel(job.duration))};
end;
for i=1:numel(job.pmod),
if numel(job.onset) ~= numel(job.pmod(i).param),
t = {t{:}, sprintf('"%s" & "%s":Number of event onsets (%d) does not equal the number of parameters (%d).',...
job.name, job.pmod(i).name, numel(job.onset),numel(job.pmod(i).param))};
end;
end;
return;
%-------------------------------------------------------------------------
%-------------------------------------------------------------------------
function t = sess_check(sess)
t = {};
for i=1:numel(sess.regress),
if numel(sess.scans) ~= numel(sess.regress(i).val),
t = {t{:}, sprintf('Num scans (%d) ~= Num regress[%d] (%d).',numel(sess.scans),i,numel(sess.regress(i).val))};
end;
end;
return;
%-------------------------------------------------------------------------
%-------------------------------------------------------------------------
function dep = vout_stats(job)
dep(1) = cfg_dep;
dep(1).sname = 'SPM.mat File';
dep(1).src_output = substruct('.','spmmat');
dep(1).tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}});
%dep(2) = cfg_dep;
%dep(2).sname = 'SPM Variable';
%dep(2).src_output = substruct('.','spmvar');
%dep(2).tgt_spec = cfg_findspec({{'strtype','e'}});
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_bms.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_bms.m
| 26,212 |
utf_8
|
e9c005333a71f641ae7d9147b7144d8d
|
function bms = spm_cfg_bms
% Configuration file for BMS interface.
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Maria Joao Rosa
% $Id: spm_cfg_bms.m 3955 2010-06-29 17:26:29Z maria $
% ---------------------------------------------------------------------
% dir Directory
% ---------------------------------------------------------------------
dir = cfg_files;
dir.tag = 'dir';
dir.name = 'Directory';
dir.help = {['Select the directory where the files containing the '...
'results from BMS (BMS.mat) will be written.']};
dir.filter = 'dir';
dir.ufilter = '.*';
dir.num = [1 1];
% ---------------------------------------------------------------------
% mod_dcm Models (.mat)
% ---------------------------------------------------------------------
mod_dcm = cfg_files;
mod_dcm.tag = 'mod_dcm';
mod_dcm.name = 'Models';
mod_dcm.help = {['Select the DCM file (.mat) for each model. '...
'DCM.mat files (models) should be specified '...
'in the same order for each subject and session.']};
mod_dcm.filter = 'mat';
mod_dcm.ufilter = '.*';
mod_dcm.num = [0 Inf];
% ---------------------------------------------------------------------
% sess_dcm Sessions
% ---------------------------------------------------------------------
sess_dcm = cfg_branch;
sess_dcm.tag = 'sess_dcm';
sess_dcm.name = 'Session';
sess_dcm.val = {mod_dcm };
% ---------------------------------------------------------------------
% subj_dcm Subject
% ---------------------------------------------------------------------
subj_dcm = cfg_repeat;
subj_dcm.tag = 'subj_dcm';
subj_dcm.name = 'Subject';
subj_dcm.values = {sess_dcm };
% ---------------------------------------------------------------------
% dcm Data
% ---------------------------------------------------------------------
dcm = cfg_repeat;
dcm.tag = 'dcm';
dcm.name = 'Data';
dcm.help = {['Select DCM file (.mat) for each model, session and '...
'subject.']}';
dcm.values = {subj_dcm };
dcm.num = [0 Inf];
% ---------------------------------------------------------------------
% mod_map Models (.img)
% ---------------------------------------------------------------------
mod_map = cfg_files;
mod_map.tag = 'mod_map';
mod_map.name = 'Models';
mod_map.help = {['Specify the log. evidence map (.img) for each model. '...
'Log-evidence maps should be specified '...
'in the same order for each subject and session.']};
mod_map.filter = 'image';
mod_map.ufilter = '.*';
mod_map.num = [1 Inf];
% ---------------------------------------------------------------------
% sess_map Sessions (Maps)
% ---------------------------------------------------------------------
sess_map = cfg_branch;
sess_map.tag = 'sess_map';
sess_map.name = 'Session';
sess_map.val = {mod_map };
% ---------------------------------------------------------------------
% subj_dcm Subject (Maps)
% ---------------------------------------------------------------------
subj_map = cfg_repeat;
subj_map.tag = 'subj_map';
subj_map.name = 'Subject';
subj_map.values = {sess_map };
% ---------------------------------------------------------------------
% map Data
% ---------------------------------------------------------------------
map = cfg_repeat;
map.tag = 'map';
map.name = 'Data';
map.help = {['Select the log. evidence maps (.img) for each '...
'model, session and subject.']}';
map.values = {subj_map };
map.num = [1 Inf];
% ---------------------------------------------------------------------
% mod_name Name
% ---------------------------------------------------------------------
mod_name = cfg_entry;
mod_name.tag = 'mod_name';
mod_name.name = 'Name';
mod_name.help = {'Specify name for each model (optional).'};
mod_name.strtype = 's';
mod_name.num = [0 Inf];
mod_name.val = {''};
% ---------------------------------------------------------------------
% name_mod Name models
% ---------------------------------------------------------------------
name_mod = cfg_repeat;
name_mod.tag = 'name_mod';
name_mod.name = 'Name models';
name_mod.help = {'Specify name for each model (optional).'}';
name_mod.values = {mod_name };
name_mod.num = [0 Inf];
% ---------------------------------------------------------------------
% model_sp Load model space
% ---------------------------------------------------------------------
model_sp = cfg_files;
model_sp.tag = 'model_sp';
model_sp.name = 'Load model space';
model_sp.help = {['Optional: load .mat file with all subjects, sessions '...
'and models. This option is a faster alternative to selecting '...
'the DCM.mat files for each subject/model (above in '...
'''Data'').']
['This file is created if the ''Data'' option has been used. '...
'It is saved in the same directory as BMS.mat and can then be loaded '...
'for future BMS/BMA analyses with the same data.']
['The model space file should contain the structure ''subj''. ' ...
'This structure should have the field ''sess'' for sessions, '...
'then the subfield ''model'' and in ''model'' there should be '...
'five subfields: ''fname'' contains the path to the DCM.mat file, '...
'''.F'' the Free Energy of that model, '...
'''.Ep'' and ''Cp'' the mean and covariance of the parameters estimates. '...
'Finally the subfield ''.nonLin'' should be 1 if the model is non-linear and '...
'0 otherwise.']
['Example: subj(3).sess(1).model(4).fname contains the path to the DCM.mat '...
'file for subject 3, session 1 and model 4. subj(3).sess(1).model(4).F '...
'contains the value of the Free Energy for the same model/session/subject.']};
model_sp.filter = 'mat';
model_sp.ufilter = '.*';
model_sp.val = {{''}};
model_sp.num = [0 1];
% ---------------------------------------------------------------------
% load_f Log-evidence matrix
% ---------------------------------------------------------------------
load_f = cfg_files;
load_f.tag = 'load_f';
load_f.name = 'Log-evidence matrix';
load_f.help = {['Optional: load .mat file with log-evidence values for '...
'comparison. This option is a faster alternative to selecting '...
'the DCM.mat files for each subject/model (above in '...
'''Data'') but it does not allow for Bayesian Model Averaging. '...
'To compute BMA the user needs to specify the DCM.mat files '...
'or the model space. ']
['This file should contain an F matrix consisting ' ...
'of [s x m] log-evidence values, where s is the number '...
'of subjects and m the number of models.']};
load_f.filter = 'mat';
load_f.ufilter = '.*';
load_f.val = {{''}};
load_f.num = [0 1];
% ---------------------------------------------------------------------
% method Inference Method
% ---------------------------------------------------------------------
method = cfg_menu;
method.tag = 'method';
method.name = 'Inference method';
method.help = {['Specify inference method: random effects '...
'(2nd-level, RFX) or fixed effects (1st-level, FFX) analysis. '...
'RFX uses Gibbs sampling.']};
method.labels = {
'Fixed effects (FFX)'
'Random effects (RFX)'
}';
method.values = {
'FFX'
'RFX'
}';
% ---------------------------------------------------------------------
% method_maps Inference Method (maps)
% ---------------------------------------------------------------------
method_maps = cfg_menu;
method_maps.tag = 'method_maps';
method_maps.name = 'Inference method';
method_maps.help = {['Specify inference method: random effects '...
'(2nd-level, RFX) or fixed effects (1st-level, FFX) analysis. '...
'RFX uses a Variational Bayes approach.']};
method_maps.labels = {
'Fixed effects (FFX)'
'Random effects (RFX)'
}';
method_maps.values = {
'FFX'
'RFX'
}';
% % ---------------------------------------------------------------------
% % priors Priors
% % ---------------------------------------------------------------------
% priors = cfg_menu;
% priors.tag = 'priors';
% priors.name = 'Priors';
% priors.help = {['Specify priors for family-level inference (RFX only).
% '...
% 'Options: ''Family'' sets alpha0=1 for each family '...
% 'while ''Model'' sets alpha0=1 for each model (not '...
% 'advised).']};
% priors.labels = {
% 'Model'
% 'Family'
% }';
% priors.values = {
% 'M-unity'
% 'F-unity'
% }';
% priors.val = {'F-unity'};
% ---------------------------------------------------------------------
% family_file Family file
% ---------------------------------------------------------------------
family_file = cfg_files;
family_file.tag = 'family_file';
family_file.name = 'Load family';
family_file.help = {['Load family.mat file. This file should contain the '...
'structure ''family'' with fields ''names'' and '...
'''partition''. Example: family.names = {''F1'', '...
'''F2''} and family.partition = [1 2 2 1 1]. '...
' This structure specifies two families with names '...
'''F1'' and ''F2'' and assigns model 1, 4 and 5 to '...
'the first family and models 2 and 3 to the second '...
'family.']};
family_file.val{1} = {''};
family_file.filter = 'mat';
family_file.ufilter = '.*';
family_file.num = [0 1];
% ---------------------------------------------------------------------
% family_name Family name
% ---------------------------------------------------------------------
family_name = cfg_entry;
family_name.tag = 'family_name';
family_name.name = 'Name';
family_name.help = {'Specify name for family.'};
family_name.strtype = 's';
family_name.num = [0 Inf];
% ---------------------------------------------------------------------
% family_models family_models
% ---------------------------------------------------------------------
family_models = cfg_entry;
family_models.tag = 'family_models';
family_models.name = 'Models';
family_models.help = {['Specify models belonging to this family. '...
'Example: write ''2 6'' if the second and sixth model '...
'belong to this family.']};
family_models.strtype = 'e';
family_models.num = [Inf 1];
% ---------------------------------------------------------------------
% family Family
% ---------------------------------------------------------------------
family = cfg_branch;
family.tag = 'family';
family.name = 'Family';
family.val = {family_name family_models };
family.help = {'Specify family name and models.'};
% ---------------------------------------------------------------------
% select_family Specify family
% ---------------------------------------------------------------------
select_family = cfg_repeat;
select_family.tag = 'select_family';
select_family.name = 'Construct family';
select_family.values = {family };
select_family.help = {'Create family. Specify family name and models.'};
% ---------------------------------------------------------------------
% family_level Specify families
% ---------------------------------------------------------------------
family_level = cfg_choice;
family_level.tag = 'family_level';
family_level.name = 'Family inference';
family_level.help = {['Optional field to perform family level inference.'...
'Options: load family.mat '...
'or specify family names and models using '...
'the interface.']};
family_level.val = {family_file };
family_level.values = {family_file select_family };
% ---------------------------------------------------------------------
% bma_part Choose family
% ---------------------------------------------------------------------
bma_part = cfg_entry;
bma_part.tag = 'bma_part';
bma_part.name = 'Enter family';
bma_part.help = {['Specify family (integer). E.g. ''2'' for the second '...
'family to use in BMA. ']};
bma_part.strtype = 'e';
bma_part.num = [0 Inf];
% ---------------------------------------------------------------------
% bma_no no
% ---------------------------------------------------------------------
bma_all = cfg_const;
bma_all.tag = 'bma_all';
bma_all.name = 'All families';
bma_all.val = {'famwin'};
bma_all.help = {'Use all families for Bayesian Model Averaging (BMA).'}';
% ---------------------------------------------------------------------
% bma_no no
% ---------------------------------------------------------------------
bma_famwin = cfg_const;
bma_famwin.tag = 'bma_famwin';
bma_famwin.name = 'Winning family';
bma_famwin.val = {'fanwin'};
bma_famwin.help = {'Use winning family for Bayesian Model Averaging (BMA).'}';
% ---------------------------------------------------------------------
% bma_no no
% ---------------------------------------------------------------------
bma_no = cfg_const;
bma_no.tag = 'bma_no';
bma_no.name = 'Do not compute';
bma_no.val = {0};
bma_no.help = {'Do not compute Bayesian Model Averaging (BMA).'}';
% ---------------------------------------------------------------------
% bma_yes BMA set
% ---------------------------------------------------------------------
bma_yes = cfg_choice;
bma_yes.tag = 'bma_yes';
bma_yes.name = 'Choose family';
bma_yes.help = {['Specify family for Bayesian Model Averaging (BMA). '...
'Options: ''winning family'', ''enter family'' or '...
'''all families''.']};
bma_yes.val = {bma_famwin };
bma_yes.values = {bma_famwin bma_all bma_part };
% ---------------------------------------------------------------------
% bma BMA
% ---------------------------------------------------------------------
bma = cfg_choice;
bma.tag = 'bma';
bma.name = 'BMA';
bma.help = {'Optional field to compute Bayesian Model Averaging (BMA).'};
bma.val = {bma_no };
bma.values = {bma_no bma_yes };
% ---------------------------------------------------------------------
% verify_id Verify data ID
% ---------------------------------------------------------------------
verify_id = cfg_menu;
verify_id.tag = 'verify_id';
verify_id.name = 'Verify data identity';
verify_id.help = {['Verify whether the model comparison is valid '...
'i.e. whether the models have been fitted to the same data.']};
verify_id.labels = {
'Yes'
'No'
}';
verify_id.values = {
1
0
}';
verify_id.val = {0};
% ---------------------------------------------------------------------
% out_file Output files
% ---------------------------------------------------------------------
out_file = cfg_menu;
out_file.tag = 'out_file';
out_file.name = 'Output files (RFX)';
out_file.help = {['Specify which output files to save (only valid for'...
'RFX analyses). ']...
''...
['Default option (and faster option): '...
'PPM = xppm.img (Posterior Probability Maps) '...
'for each model. ']...
''...
['Second option: PPM + EPM = xppm.img + '...
'epm.img (Exceedance Probability '...
'Maps + Exceedance Probability Maps) for each model.']...
''...
['Third option: PPM + EPM + Alpha = xppm.img + '...
'epm.img + alpha.img (PPM, EPM and Map of Dirichlet '...
'Parameters) for each model.']};
out_file.labels = {
'PPM'
'PPM + EPM'
'PPM + EPM + Alpha'
}';
out_file.values = {
0
1
2
}';
out_file.val = {0};
% ---------------------------------------------------------------------
% mask Mask Image
% ---------------------------------------------------------------------
mask = cfg_files;
mask.tag = 'mask';
mask.name = 'Mask Image';
mask.help = {['Specify an image for explicitly masking the analysis. '...
'(optional). '...
'A sensible option here is to use a segmention of '...
'structural images to specify a within-brain mask. '...
'If you select that image as an explicit mask then only '...
'those voxels in the brain will be analysed. This both '...
'speeds the inference process and restricts BMS to '...
'within-brain voxels. Alternatively, if such structural '...
'images are unavailble or no masking is required, then '...
'leave this field empty.']};
mask.filter = 'image';
mask.ufilter = '.*';
mask.val = {{''}};
mask.num = [0 1];
% ---------------------------------------------------------------------
% nsamp Number of samples
% ---------------------------------------------------------------------
nsamp = cfg_entry;
nsamp.tag = 'nsamp';
nsamp.name = 'Number of samples';
nsamp.help = {['Number of samples used to compute exceedance '...
'probabilities (default: 1e6). '...
'To make computations faster reduce the number of '...
'samples when number of models is bigger than 3.']};
nsamp.strtype = 's';
nsamp.num = [1 Inf];
nsamp.val = {'1e6'};
% ---------------------------------------------------------------------
% file BMS.mat
% ---------------------------------------------------------------------
file = cfg_files;
file.tag = 'file';
file.name = 'BMS.mat';
file.help = {['Specify the BMS (.mat) file obtained from previous BMS '...
'analysis (optional). Leave field empty to work on '...
'serial mode.']};
file.filter = 'mat';
file.ufilter = '.*';
file.val = {{''}};
file.num = [0 1];
% ---------------------------------------------------------------------
% img Map to display
% ---------------------------------------------------------------------
img = cfg_files;
img.tag = 'img';
img.name = 'Map to display';
img.help = {['Specify map (.img) obtained from BMS Maps '...
'(optional). Leave field empty to work on serial mode.']};
img.filter = 'image';
img.ufilter = '.*';
img.val = {{''}};
img.num = [0 1];
% ---------------------------------------------------------------------
% thres Probability Threshold
% ---------------------------------------------------------------------
thres = cfg_entry;
thres.tag = 'thres';
thres.name = 'Probability threshold';
thres.help = {['Specify the probability threshold to apply to the '...
'image (optional). Leave field empty to work on '...
'serial mode.']};
thres.strtype = 'e';
thres.num = [0 Inf];
thres.val = {[]};
% ---------------------------------------------------------------------
% k Extent threshold
% ---------------------------------------------------------------------
k = cfg_entry;
k.tag = 'k';
k.name = 'Extent threshold';
k.help = {['Specify extent threshold (minimum number of voxels '...
'per cluster).']};
k.strtype = 'e';
k.num = [0 Inf];
k.val = {[]};
% ---------------------------------------------------------------------
% scale Map Scale
% ---------------------------------------------------------------------
scale = cfg_menu;
scale.tag = 'scale';
scale.name = 'Map scale';
scale.help = {['Specify scale to display maps (optional). Default: '...
'empty field to work on serial mode. Other options: '...
'''None'' will display image with original scale and '...
'''Log-odds'' will display image in a log-odds '...
' scale (in this case .img should be a '...
'probability map).']};
scale.labels = {
'Empty'
'None'
'Log-odds'
}';
scale.values = {
[]
0
1
}';
scale.val = {[]};
% ---------------------------------------------------------------------
% bms_dcm BMS: DCM, output is bar plot
% ---------------------------------------------------------------------
bms_dcm = cfg_exbranch;
bms_dcm.tag = 'bms_dcm';
bms_dcm.name = 'BMS: DCM';
bms_dcm.val = {dir dcm model_sp load_f method family_level bma verify_id};
bms_dcm.help = {['Bayesian Model Selection for Dynamic Causal Modelling '...
'(DCM) for fMRI or MEEG.']...
''...
['Input: DCM files (.mat) for each model, session and subject. '...
'Note that there must be identical numbers of models for all each '...
'sessions, and identical numbers of sessions for all subjects. ']...
''...
['Output: For the fixed effects analysis, the log-evidence for each '...
'model (relative to the worst model) is plotted in the graphics '...
'window, as well as the posterior probability for each model. In '...
'addition, the corresponding values are saved in the directory '...
'specified (BMS.mat). For the random effects analysis, the '...
'expected posterior probability and exceedance probability of each '...
'model (i.e. the probability that this model is more likely than '...
'any other model) are plotted in the graphics window, and the '...
'corresponding values are saved in the directory specified. If '...
'there are multiple sessions per subject, the random effects '...
'analysis operates on the subject-specific sums of log evidences '...
'across sessions.']};
bms_dcm.prog = @spm_run_bms_dcm;
bms_dcm.vout = @vout;
% ---------------------------------------------------------------------
% bms_dcm_vis: DCM (visualise results)
% ---------------------------------------------------------------------
bms_dcm_vis = cfg_exbranch;
bms_dcm_vis.tag = 'bms_dcm_vis';
bms_dcm_vis.name = 'BMS: DCM (Results)';
bms_dcm_vis.val = {file };
bms_dcm_vis.help = {['Bayesian Model Selection for DCM (Results). '...
'Show results from BMS for DCM.']};
bms_dcm_vis.prog = @spm_run_bms_dcm_vis;
% ---------------------------------------------------------------------
% bms_map_inf BMS: Maps (Inference), output is BMS map
% ---------------------------------------------------------------------
bms_map_inf = cfg_exbranch;
bms_map_inf.tag = 'bms_map_inf';
bms_map_inf.name = 'BMS: Maps';
bms_map_inf.val = {dir map name_mod method_maps out_file mask nsamp };
bms_map_inf.help = {'Bayesian Model Selection for Log-Evidence Maps. '...
''...
['Input: log-evidence maps (.img) for each model, session and '...
'subject. Note that there must be identical numbers of models for '...
'all sessions, and identical numbers of sessions for all '...
'subjects.']...
''...
['Output: For the fixed effects analysis, posterior probability maps '...
'(.img) are created for each model. '...
'For the random effects analysis, expected posterior probability '...
'and exceedance probability (i.e. the probability that this model '...
'is more likely than any other model) maps are created for each '...
'model. If there are multiple sessions per subject, the random '...
'effects analysis operates on the subject-specific sums of log '...
'evidences across sessions. In addition, a BMS.mat file will be save '...
'in the specified directory for both methods']};
bms_map_inf.prog = @spm_run_bms_map;
bms_map_inf.vout = @vout;
% ---------------------------------------------------------------------
% bms_map_vis BMS: Maps (Results), visualisation of BMS Maps results
% ---------------------------------------------------------------------
bms_map_vis = cfg_exbranch;
bms_map_vis.tag = 'bms_map_vis';
bms_map_vis.name = 'BMS: Maps (Results)';
bms_map_vis.val = {file img thres k scale};
bms_map_vis.help = {['Bayesian Model Selection Maps (Results). '...
'Show results from BMS Maps (Inference).']};
bms_map_vis.prog = @spm_run_bms_vis;
% ---------------------------------------------------------------------
% bms Bayesian Model Selection
% ---------------------------------------------------------------------
bms = cfg_choice;
bms.tag = 'bms';
bms.name = 'Bayesian Model Selection';
bms.help = {['Bayesian Model Selection for group studies (fixed '...
'effects and random effects analysis).']};
bms.values = {bms_dcm bms_dcm_vis bms_map_inf bms_map_vis };
%------------------------------------------------------------------------
function dep = vout(varargin)
% Output file names will be saved in a struct with field .files
dep(1) = cfg_dep;
dep(1).sname = 'BMS Maps';
dep(1).src_output = substruct('.','files');
dep(1).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_eeg_convert2images.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_eeg_convert2images.m
| 1,533 |
utf_8
|
278f08c7b6bc00ad2186e3d343a12b7c
|
function S = spm_cfg_eeg_convert2images
% configuration file for writing voxel-based images from SPM M/EEG format,
% as a time-series of 2Dimages
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Stefan Kiebel
% $Id: spm_cfg_eeg_convert2images.m 3818 2010-04-13 14:36:31Z vladimir $
Fname = cfg_files;
Fname.tag = 'Fname';
Fname.name = 'File Names';
Fname.filter = 'mat';
Fname.num = [1 inf];
Fname.help = {'Select the M/EEG mat file.'};
n = cfg_entry;
n.tag = 'n';
n.name = 'Output dimension';
n.strtype = 'r';
n.num = [1 1];
n.val = {64};
n.help = {'Enter the Output image dimension'};
yes = cfg_const;
yes.tag = 'yes';
yes.name = 'Interpolate bad channels';
yes.val = {1};
no = cfg_const;
no.tag = 'no';
no.name = 'Mask out bad channels';
no.val = {1};
Interpolate = cfg_choice;
Interpolate.tag = 'interpolate_bad';
Interpolate.name = 'Interpolate';
Interpolate.values = {yes,no};
Interpolate.val = {yes};
Interpolate.help = {'Interpolate bad channels'};
S = cfg_exbranch;
S.tag = 'convert2images';
S.name = 'M/EEG Convert2Images';
S.val = {Fname n Interpolate};
S.help = {'Convert SPM M/EEG data to voxel-based images, as a time-series of 2D images'};
S.prog = @eeg_convert2images;
S.modality = {'EEG'};
function out = eeg_convert2images(job)
% construct the S struct
S = job;
S.Fname = strvcat(job.Fname);
if isfield(S.interpolate_bad, 'yes')
S.interpolate_bad = 1;
else
S.interpolate_bad = 0;
end
spm_eeg_convert2scalp(S);
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_eeg_inv_results.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_eeg_inv_results.m
| 3,226 |
utf_8
|
4785178456ae76c108a54bc2b56a776c
|
function results = spm_cfg_eeg_inv_results
% configuration file for creating images from results of source
% reconstruction
%_______________________________________________________________________
% Copyright (C) 2010 Wellcome Trust Centre for Neuroimaging
% Vladimir Litvak
% $Id: spm_cfg_eeg_inv_results.m 3976 2010-07-08 14:12:31Z karl $
D = cfg_files;
D.tag = 'D';
D.name = 'M/EEG datasets';
D.filter = 'mat';
D.num = [1 Inf];
D.help = {'Select the M/EEG mat files.'};
val = cfg_entry;
val.tag = 'val';
val.name = 'Inversion index';
val.strtype = 'n';
val.help = {'Index of the cell in D.inv where the inversion results are be stored.'};
val.val = {1};
woi = cfg_entry;
woi.tag = 'woi';
woi.name = 'Time window of interest';
woi.strtype = 'r';
woi.num = [Inf 2];
woi.val = {[-Inf Inf]};
woi.help = {'Time window to average over (ms)'};
foi = cfg_entry;
foi.tag = 'foi';
foi.name = 'Frequency window of interest';
foi.strtype = 'r';
foi.num = [1 2];
foi.val = {[0 0]};
foi.help = {'Frequency window (Hz)'};
ctype = cfg_menu;
ctype.tag = 'ctype';
ctype.name = 'Contrast type';
ctype.help = {'Contrast type: evoked activity, induced activity or single trials.'};
ctype.labels = {'Evoked', 'Induced', 'Single trials'};
ctype.values = {'evoked', 'induced', 'trials'};
ctype.val = {'evoked'};
space = cfg_menu;
space.tag = 'space';
space.name = 'Image space';
space.help = {'Image space to wrote the results in.'};
space.labels = {'MNI', 'Native'};
space.values = {1, 0};
space.val = {1};
smoothing = cfg_entry;
smoothing.tag = 'smoothing';
smoothing.name = 'Smoothing kernel width (mm)';
smoothing.strtype = 'r';
smoothing.num = [1 1];
smoothing.val = {8};
results = cfg_exbranch;
results.tag = 'results';
results.name = 'M/EEG inversion results';
results.val = {D, val, woi, foi, ctype, space, smoothing};
results.help = {'Generate images from the results of imaging source reconstruction'};
results.prog = @run_results;
results.vout = @vout_results;
results.modality = {'EEG'};
function out = run_results(job)
contrast = [];
contrast.fboi = job.foi;
contrast.type = job.ctype;
contrast.space = job.space;
contrast.smoothing = job.smoothing;
files = {};
for i = 1:numel(job.D)
D = spm_eeg_load(job.D{i});
D.val = job.val;
if ~isfield(D.inv{D.val}, 'inverse') || ~isfield(D.inv{D.val}.inverse, 'J')
error(sprintf('Imaging source reconstruction is missing for subject %d', i));
end
contrast.woi = fix(sort(job.woi,2));
D.inv{D.val}.contrast = contrast;
D = spm_eeg_inv_results(D);
D = spm_eeg_inv_Mesh2Voxels(D);
save(D);
fname = D.inv{D.val}.contrast.fname;
for j = 1:numel(fname)
if iscell(fname{j})
for k = 1:numel(fname{j})
files = [files; fname{j}(k)];
end
else
files = [files; fname(j)];
end
end
end
out.files = files;
function dep = vout_results(job)
% Output is always in field "D", no matter how job is structured
dep = cfg_dep;
dep(1) = cfg_dep;
dep(1).sname = 'Exported smoothed images';
dep(1).src_output = substruct('.','files');
dep(1).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_eeg_contrast.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_eeg_contrast.m
| 2,514 |
utf_8
|
5ef4acc26bd25c57a355ebd077aecc82
|
function S = spm_cfg_eeg_contrast
% configuration file for computing contrast over epochs
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Stefan Kiebel
% $Id: spm_cfg_eeg_contrast.m 3881 2010-05-07 21:02:57Z vladimir $
D = cfg_files;
D.tag = 'D';
D.name = 'File Name';
D.filter = 'mat';
D.num = [1 1];
D.help = {'Select the EEG mat file.'};
c = cfg_entry;
c.tag = 'c';
c.name = 'Contrast coefficients';
c.strtype = 'r';
c.num = [1 inf];
c.help = {'Enter the contrast vector.'};
label = cfg_entry;
label.tag = 'label';
label.name = 'New condition label';
label.strtype = 's';
label.help = {'Enter the label for the condition derived by applying the contrast.'};
contrast = cfg_branch;
contrast.tag = 'contrast';
contrast.name = 'Contrast';
contrast.val = {c label};
contrasts = cfg_repeat;
contrasts.tag = 'contrasts';
contrasts.name = 'Contrasts';
contrasts.help = {'Each contrast defines a new condition in the output file.'};
contrasts.values = {contrast};
contrasts.num = [1 Inf];
weight = cfg_menu;
weight.tag = 'weight';
weight.name = 'Weight average by repetition numbers';
weight.labels = {'yes', 'no'};
weight.values = {1 , 0};
weight.val = {1};
weight.help = {'This option will weight averages by the number of their occurences in the data set. This is only important when there are multiple occurences of a trial type, e.g. in single trial data.'};
S = cfg_exbranch;
S.tag = 'contrast';
S.name = 'M/EEG Contrast over epochs';
S.val = {D contrasts weight};
S.help = {'Computes contrasts over EEG/MEG epochs.'};
S.prog = @eeg_contrast;
S.vout = @vout_eeg_contrast;
S.modality = {'EEG'};
function out = eeg_contrast(job)
% construct the S struct
S.D = job.D{1};
S.c = cat(1, job.contrast(:).c);
S.label = {job.contrast.label};
S.WeightAve = job.weight;
out.D = spm_eeg_weight_epochs(S);
out.Dfname = {fullfile(out.D.path, out.D.fname)};
function dep = vout_eeg_contrast(job)
% Output is always in field "D", no matter how job is structured
dep = cfg_dep;
dep.sname = 'Contrast of M/EEG epochs';
% reference field "D" from output
dep.src_output = substruct('.','D');
% this can be entered into any evaluated input
dep.tgt_spec = cfg_findspec({{'strtype','e'}});
dep(2) = cfg_dep;
dep(2).sname = 'Contrast Datafile';
% reference field "Dfname" from output
dep(2).src_output = substruct('.','Dfname');
% this can be entered into any file selector
dep(2).tgt_spec = cfg_findspec({{'filter','mat'}});
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_checkreg.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_checkreg.m
| 2,265 |
utf_8
|
c81f7c3223052066b263026099947cec
|
function checkreg = spm_cfg_checkreg
% SPM Configuration file for Check Reg
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% $Id: spm_cfg_checkreg.m 4205 2011-02-21 15:39:08Z guillaume $
%--------------------------------------------------------------------------
% data Images to Display
%--------------------------------------------------------------------------
data = cfg_files;
data.tag = 'data';
data.name = 'Images to Display';
data.help = {'Images to display.'};
data.filter = 'image';
data.ufilter = '.*';
data.num = [1 15];
%--------------------------------------------------------------------------
% checkreg Check Registration
%--------------------------------------------------------------------------
checkreg = cfg_exbranch;
checkreg.tag = 'checkreg';
checkreg.name = 'Check Registration';
checkreg.val = {data };
checkreg.help = {
'Orthogonal views of one or more images are displayed. Clicking in any image moves the centre of the orthogonal views. Images are shown in orientations relative to that of the first selected image. The first specified image is shown at the top-left, and the last at the bottom right. The fastest increment is in the left-to-right direction (the same as you are reading this).'
''
'If you have put your images in the correct file format, then (possibly after specifying some rigid-body rotations):'
' The top-left image is coronal with the top (superior) of the head displayed at the top and the left shown on the left. This is as if the subject is viewed from behind.'
' The bottom-left image is axial with the front (anterior) of the head at the top and the left shown on the left. This is as if the subject is viewed from above.'
' The top-right image is sagittal with the front (anterior) of the head at the left and the top of the head shown at the top. This is as if the subject is viewed from the left.'
}';
checkreg.prog = @check_reg;
%==========================================================================
function check_reg(job)
spm_check_registration(char(job.data));
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_deletefiles.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_deletefiles.m
| 2,302 |
utf_8
|
8fd0b19822b9648162bb473b9dbe360f
|
function deletefiles = spm_cfg_deletefiles
% SPM Configuration file
% automatically generated by the MATLABBATCH utility function GENCODE
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% $Id: spm_cfg_deletefiles.m 2222 2008-09-29 11:08:47Z volkmar $
rev = '$Rev: 2222 $';
% ---------------------------------------------------------------------
% deletefiles Files to delete
% ---------------------------------------------------------------------
deletefiles1 = cfg_files;
deletefiles1.tag = 'deletefiles';
deletefiles1.name = 'Files to delete';
deletefiles1.help = {'Select files to delete.'};
deletefiles1.filter = 'any';
deletefiles1.ufilter = '.*';
deletefiles1.num = [0 Inf];
% ---------------------------------------------------------------------
% deletefiles Delete Files (Deprecated)
% ---------------------------------------------------------------------
deletefiles = cfg_exbranch;
deletefiles.tag = 'deletefiles';
deletefiles.name = 'Delete Files (Deprecated)';
deletefiles.val = {deletefiles1 };
deletefiles.help = {
'This module is deprecated and has been moved to BasicIO.'
'Jobs which are ready to run may continue using it, but the module inputs can not be changed via GUI. Please switch to the BasicIO module instead.'
'This facilty allows to delete files in a batch. Note that deleting files will not make them disappear from file selection lists. Therefore one has to be careful not to select the original files after they have been programmed to be deleted.'
''
'If image files (.img or .nii) are selected, corresponding .hdr or .mat files will be deleted as well, if they exist.'
};
deletefiles.prog = @my_deletefiles;
deletefiles.hidden = true;
%------------------------------------------------------------------------
function my_deletefiles(varargin)
job = varargin{1};
for k = 1:numel(job.deletefiles)
[p n e] = spm_fileparts(job.deletefiles{k});
if strcmp(e,'.img') || strcmp(e,'.nii')
spm_unlink(fullfile(p,[n '.hdr']));
spm_unlink(fullfile(p,[n '.mat']));
end
spm_unlink(fullfile(p,[n e]));
end
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_md.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_md.m
| 1,974 |
utf_8
|
7596c832b50c0ecadcf8ef562069a262
|
function md = spm_cfg_md
% SPM Configuration file for making directory function
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% $Id: spm_cfg_md.m 1827 2008-06-16 13:54:37Z guillaume $
% ----------------------------------------------------------------------
% basedir Select a base directory
% ----------------------------------------------------------------------
basedir = cfg_files;
basedir.tag = 'basedir';
basedir.name = 'Select a base directory';
basedir.help = {'Select a base directory.'};
basedir.filter = 'dir';
basedir.ufilter = '.*';
basedir.num = [1 1];
% ----------------------------------------------------------------------
% name Enter a directory name
% ----------------------------------------------------------------------
name = cfg_entry;
name.tag = 'name';
name.name = 'Enter a directory name';
name.help = {'Enter a directory name'};
name.strtype = 's';
name.num = [1 Inf];
% ----------------------------------------------------------------------
% md Make Directory (Deprecated)
% ----------------------------------------------------------------------
md = cfg_exbranch;
md.tag = 'md';
md.name = 'Make Directory (Deprecated)';
md.val = {basedir name};
md.help = {
'This facilty allows programming a directory change. Directories are selected in the right listbox.'
'This module is deprecated and has been moved to BasicIO.'
'Jobs which are ready to run may continue using it, but the module inputs can not be changed via GUI. Please switch to the BasicIO module instead.'
}';
md.prog = @my_mkdir;
md.hidden = true;
%=======================================================================
function my_mkdir(varargin)
job = varargin{1};
if ~isempty(job.basedir) && ~isempty(job.name)
mkdir(job.basedir{:},job.name);
end
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_normalise.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_normalise.m
| 25,506 |
utf_8
|
a01a87d691294117634f2d14d848977e
|
function normalise = spm_cfg_normalise
% SPM Configuration file
% automatically generated by the MATLABBATCH utility function GENCODE
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% $Id: spm_cfg_normalise.m 3804 2010-03-31 16:16:21Z ged $
rev = '$Rev: 3804 $';
% ---------------------------------------------------------------------
% source Source Image
% ---------------------------------------------------------------------
source = cfg_files;
source.tag = 'source';
source.name = 'Source Image';
source.help = {'The image that is warped to match the template(s). The result is a set of warps, which can be applied to this image, or any other image that is in register with it.'};
source.filter = 'image';
source.ufilter = '.*';
source.num = [1 1];
% ---------------------------------------------------------------------
% wtsrc Source Weighting Image
% ---------------------------------------------------------------------
wtsrc = cfg_files;
wtsrc.tag = 'wtsrc';
wtsrc.name = 'Source Weighting Image';
wtsrc.val = {''};
wtsrc.help = {'Optional weighting images (consisting of pixel values between the range of zero to one) to be used for registering abnormal or lesioned brains. These images should match the dimensions of the image from which the parameters are estimated, and should contain zeros corresponding to regions of abnormal tissue.'};
wtsrc.filter = 'image';
wtsrc.ufilter = '.*';
wtsrc.num = [0 1];
% ---------------------------------------------------------------------
% subj Subject
% ---------------------------------------------------------------------
subj = cfg_branch;
subj.tag = 'subj';
subj.name = 'Subject';
subj.val = {source wtsrc };
subj.help = {'Data for this subject. The same parameters are used within subject.'};
% ---------------------------------------------------------------------
% esubjs Data
% ---------------------------------------------------------------------
esubjs = cfg_repeat;
esubjs.tag = 'esubjs';
esubjs.name = 'Data';
esubjs.help = {'List of subjects. Images of each subject should be warped differently.'};
esubjs.values = {subj };
esubjs.num = [1 Inf];
% ---------------------------------------------------------------------
% template Template Image
% ---------------------------------------------------------------------
template = cfg_files;
template.tag = 'template';
template.name = 'Template Image';
template.help = {'Specify a template image to match the source image with. The contrast in the template must be similar to that of the source image in order to achieve a good registration. It is also possible to select more than one template, in which case the registration algorithm will try to find the best linear combination of these images in order to best model the intensities in the source image.'};
template.filter = 'image';
template.ufilter = '.*';
template.dir = fullfile(spm('dir'),'templates');
template.num = [1 Inf];
% ---------------------------------------------------------------------
% weight Template Weighting Image
% ---------------------------------------------------------------------
weight = cfg_files;
weight.tag = 'weight';
weight.name = 'Template Weighting Image';
weight.val = {''};
weight.help = {
'Applies a weighting mask to the template(s) during the parameter estimation. With the default brain mask, weights in and around the brain have values of one whereas those clearly outside the brain are zero. This is an attempt to base the normalisation purely upon the shape of the brain, rather than the shape of the head (since low frequency basis functions can not really cope with variations in skull thickness).'
''
'The option is now available for a user specified weighting image. This should have the same dimensions and mat file as the template images, with values in the range of zero to one.'
}';
weight.filter = 'image';
weight.ufilter = '.*';
weight.num = [0 1];
% ---------------------------------------------------------------------
% smosrc Source Image Smoothing
% ---------------------------------------------------------------------
smosrc = cfg_entry;
smosrc.tag = 'smosrc';
smosrc.name = 'Source Image Smoothing';
smosrc.help = {'Smoothing to apply to a copy of the source image. The template and source images should have approximately the same smoothness. Remember that the templates supplied with SPM have been smoothed by 8mm, and that smoothnesses combine by Pythagoras'' rule.'};
smosrc.strtype = 'e';
smosrc.num = [1 1];
smosrc.def = @(val)spm_get_defaults('normalise.estimate.smosrc', val{:});
% ---------------------------------------------------------------------
% smoref Template Image Smoothing
% ---------------------------------------------------------------------
smoref = cfg_entry;
smoref.tag = 'smoref';
smoref.name = 'Template Image Smoothing';
smoref.help = {'Smoothing to apply to a copy of the template image. The template and source images should have approximately the same smoothness. Remember that the templates supplied with SPM have been smoothed by 8mm, and that smoothnesses combine by Pythagoras'' rule.'};
smoref.strtype = 'e';
smoref.num = [1 1];
smoref.def = @(val)spm_get_defaults('normalise.estimate.smoref', val{:});
% ---------------------------------------------------------------------
% regtype Affine Regularisation
% ---------------------------------------------------------------------
regtype = cfg_menu;
regtype.tag = 'regtype';
regtype.name = 'Affine Regularisation';
regtype.help = {'Affine registration into a standard space can be made more robust by regularisation (penalising excessive stretching or shrinking). The best solutions can be obtained by knowing the approximate amount of stretching that is needed (e.g. ICBM templates are slightly bigger than typical brains, so greater zooms are likely to be needed). If registering to an image in ICBM/MNI space, then choose the first option. If registering to a template that is close in size, then select the second option. If you do not want to regularise, then choose the third.'};
regtype.labels = {
'ICBM space template'
'Average sized template'
'No regularisation'
}';
regtype.values = {
'mni'
'subj'
'none'
}';
regtype.def = @(val)spm_get_defaults('normalise.estimate.regtype', val{:});
% ---------------------------------------------------------------------
% cutoff Nonlinear Frequency Cutoff
% ---------------------------------------------------------------------
cutoff = cfg_entry;
cutoff.tag = 'cutoff';
cutoff.name = 'Nonlinear Frequency Cutoff';
cutoff.help = {'Cutoff of DCT bases. Only DCT bases of periods longer than the cutoff are used to describe the warps. The number used will depend on the cutoff and the field of view of the template image(s).'};
cutoff.strtype = 'e';
cutoff.num = [1 1];
cutoff.def = @(val)spm_get_defaults('normalise.estimate.cutoff', val{:});
% ---------------------------------------------------------------------
% nits Nonlinear Iterations
% ---------------------------------------------------------------------
nits = cfg_entry;
nits.tag = 'nits';
nits.name = 'Nonlinear Iterations';
nits.help = {'Number of iterations of nonlinear warping performed.'};
nits.strtype = 'w';
nits.num = [1 1];
nits.def = @(val)spm_get_defaults('normalise.estimate.nits', val{:});
% ---------------------------------------------------------------------
% reg Nonlinear Regularisation
% ---------------------------------------------------------------------
reg = cfg_entry;
reg.tag = 'reg';
reg.name = 'Nonlinear Regularisation';
reg.help = {'The amount of regularisation for the nonlinear part of the spatial normalisation. Pick a value around one. However, if your normalised images appear distorted, then it may be an idea to increase the amount of regularisation (by an order of magnitude) - or even just use an affine normalisation. The regularisation influences the smoothness of the deformation fields.'};
reg.strtype = 'e';
reg.num = [1 1];
reg.def = @(val)spm_get_defaults('normalise.estimate.reg', val{:});
% ---------------------------------------------------------------------
% eoptions Estimation Options
% ---------------------------------------------------------------------
eoptions = cfg_branch;
eoptions.tag = 'eoptions';
eoptions.name = 'Estimation Options';
eoptions.val = {template weight smosrc smoref regtype cutoff nits reg };
eoptions.help = {'Various settings for estimating warps.'};
% ---------------------------------------------------------------------
% est Normalise: Estimate
% ---------------------------------------------------------------------
est = cfg_exbranch;
est.tag = 'est';
est.name = 'Normalise: Estimate';
est.val = {esubjs eoptions };
est.help = {'Computes the warp that best registers a source image (or series of source images) to match a template, saving it to a file imagename''_sn.mat''.'};
est.prog = @spm_run_normalise_estimate;
est.vout = @vout_estimate;
% ---------------------------------------------------------------------
% matname Parameter File
% ---------------------------------------------------------------------
matname = cfg_files;
matname.tag = 'matname';
matname.name = 'Parameter File';
matname.help = {'Select the ''_sn.mat'' file containing the spatial normalisation parameters for that subject.'};
matname.filter = 'mat';
matname.ufilter = '.*_sn\.mat$';
matname.num = [1 1];
% ---------------------------------------------------------------------
% resample Images to Write
% ---------------------------------------------------------------------
resample = cfg_files;
resample.tag = 'resample';
resample.name = 'Images to Write';
resample.help = {'These are the images for warping according to the estimated parameters. They can be any images that are in register with the "source" image used to generate the parameters.'};
resample.filter = 'image';
resample.ufilter = '.*';
resample.num = [1 Inf];
% ---------------------------------------------------------------------
% subj Subject
% ---------------------------------------------------------------------
subj = cfg_branch;
subj.tag = 'subj';
subj.name = 'Subject';
subj.val = {matname resample };
subj.help = {'Data for this subject. The same parameters are used within subject.'};
% ---------------------------------------------------------------------
% wsubjs Data
% ---------------------------------------------------------------------
wsubjs = cfg_repeat;
wsubjs.tag = 'wsubjs';
wsubjs.name = 'Data';
wsubjs.help = {'List of subjects. Images of each subject should be warped differently.'};
wsubjs.values = {subj };
wsubjs.num = [1 Inf];
% ---------------------------------------------------------------------
% preserve Preserve
% ---------------------------------------------------------------------
preserve = cfg_menu;
preserve.tag = 'preserve';
preserve.name = 'Preserve';
preserve.help = {
'Preserve Concentrations: Spatially normalised images are not "modulated". The warped images preserve the intensities of the original images.'
''
'Preserve Total: Spatially normalised images are "modulated" in order to preserve the total amount of signal in the images. Areas that are expanded during warping are correspondingly reduced in intensity.'
}';
preserve.labels = {
'Preserve Concentrations'
'Preserve Amount'
}';
preserve.values = {0 1};
preserve.def = @(val)spm_get_defaults('normalise.write.preserve', val{:});
% ---------------------------------------------------------------------
% bb Bounding box
% ---------------------------------------------------------------------
bb = cfg_entry;
bb.tag = 'bb';
bb.name = 'Bounding box';
bb.help = {'The bounding box (in mm) of the volume which is to be written (relative to the anterior commissure).'};
bb.strtype = 'e';
bb.num = [2 3];
bb.def = @(val)spm_get_defaults('normalise.write.bb', val{:});
% ---------------------------------------------------------------------
% vox Voxel sizes
% ---------------------------------------------------------------------
vox = cfg_entry;
vox.tag = 'vox';
vox.name = 'Voxel sizes';
vox.help = {'The voxel sizes (x, y & z, in mm) of the written normalised images.'};
vox.strtype = 'e';
vox.num = [1 3];
vox.def = @(val)spm_get_defaults('normalise.write.vox', val{:});
% ---------------------------------------------------------------------
% interp Interpolation
% ---------------------------------------------------------------------
interp = cfg_menu;
interp.tag = 'interp';
interp.name = 'Interpolation';
interp.help = {
['The method by which the images are sampled when ' ...
'being written in a different space. ' ...
'(Note that Inf or NaN values are treated as zero, ' ...
'rather than as missing data)']
' Nearest Neighbour:'
' - Fastest, but not normally recommended.'
' Bilinear Interpolation:'
' - OK for PET, realigned fMRI, or segmentations'
' B-spline Interpolation:'
[' - Better quality (but slower) interpolation' ...
'/* \cite{thevenaz00a}*/, especially with higher ' ...
'degree splines. Can produce values outside the ' ...
'original range (e.g. small negative values from an ' ...
'originally all positive image).']
}';
interp.labels = {
'Nearest neighbour'
'Trilinear'
'2nd Degree B-spline'
'3rd Degree B-Spline '
'4th Degree B-Spline '
'5th Degree B-Spline'
'6th Degree B-Spline'
'7th Degree B-Spline'
}';
interp.values = {0 1 2 3 4 5 6 7};
interp.def = @(val)spm_get_defaults('normalise.write.interp', val{:});
% ---------------------------------------------------------------------
% wrap Wrapping
% ---------------------------------------------------------------------
wrap = cfg_menu;
wrap.tag = 'wrap';
wrap.name = 'Wrapping';
wrap.help = {
'These are typically:'
' No wrapping: for PET or images that have already been spatially transformed. '
' Wrap in Y: for (un-resliced) MRI where phase encoding is in the Y direction (voxel space).'
}';
wrap.labels = {
'No wrap'
'Wrap X'
'Wrap Y'
'Wrap X & Y'
'Wrap Z'
'Wrap X & Z'
'Wrap Y & Z'
'Wrap X, Y & Z'
}';
wrap.values = {[0 0 0] [1 0 0] [0 1 0] [1 1 0] [0 0 1] [1 0 1] [0 1 1]...
[1 1 1]};
wrap.def = @(val)spm_get_defaults('normalise.write.wrap', val{:});
% ---------------------------------------------------------------------
% prefix Filename Prefix
% ---------------------------------------------------------------------
prefix = cfg_entry;
prefix.tag = 'prefix';
prefix.name = 'Filename Prefix';
prefix.help = {'Specify the string to be prepended to the filenames of the normalised image file(s). Default prefix is ''w''.'};
prefix.strtype = 's';
prefix.num = [1 Inf];
prefix.def = @(val)spm_get_defaults('normalise.write.prefix', val{:});
% ---------------------------------------------------------------------
% roptions Writing Options
% ---------------------------------------------------------------------
roptions = cfg_branch;
roptions.tag = 'roptions';
roptions.name = 'Writing Options';
roptions.val = {preserve bb vox interp wrap prefix };
roptions.help = {'Various options for writing normalised images.'};
% ---------------------------------------------------------------------
% write Normalise: Write
% ---------------------------------------------------------------------
write = cfg_exbranch;
write.tag = 'write';
write.name = 'Normalise: Write';
write.val = {wsubjs roptions };
write.help = {'Allows previously estimated warps (stored in imagename''_sn.mat'' files) to be applied to series of images.'};
write.prog = @spm_run_normalise_write;
write.vout = @vout_write;
% ---------------------------------------------------------------------
% source Source Image
% ---------------------------------------------------------------------
source = cfg_files;
source.tag = 'source';
source.name = 'Source Image';
source.help = {'The image that is warped to match the template(s). The result is a set of warps, which can be applied to this image, or any other image that is in register with it.'};
source.filter = 'image';
source.ufilter = '.*';
source.num = [1 1];
% ---------------------------------------------------------------------
% wtsrc Source Weighting Image
% ---------------------------------------------------------------------
wtsrc = cfg_files;
wtsrc.tag = 'wtsrc';
wtsrc.name = 'Source Weighting Image';
wtsrc.val = {''};
wtsrc.help = {'Optional weighting images (consisting of pixel values between the range of zero to one) to be used for registering abnormal or lesioned brains. These images should match the dimensions of the image from which the parameters are estimated, and should contain zeros corresponding to regions of abnormal tissue.'};
wtsrc.filter = 'image';
wtsrc.ufilter = '.*';
wtsrc.num = [0 1];
% ---------------------------------------------------------------------
% resample Images to Write
% ---------------------------------------------------------------------
resample = cfg_files;
resample.tag = 'resample';
resample.name = 'Images to Write';
resample.help = {'These are the images for warping according to the estimated parameters. They can be any images that are in register with the "source" image used to generate the parameters.'};
resample.filter = 'image';
resample.ufilter = '.*';
resample.num = [1 Inf];
% ---------------------------------------------------------------------
% subj Subject
% ---------------------------------------------------------------------
subj = cfg_branch;
subj.tag = 'subj';
subj.name = 'Subject';
subj.val = {source wtsrc resample };
subj.help = {'Data for this subject. The same parameters are used within subject.'};
% ---------------------------------------------------------------------
% ewsubjs Data
% ---------------------------------------------------------------------
ewsubjs = cfg_repeat;
ewsubjs.tag = 'ewsubjs';
ewsubjs.name = 'Data';
ewsubjs.help = {'List of subjects. Images of each subject should be warped differently.'};
ewsubjs.values = {subj };
ewsubjs.num = [1 Inf];
% ---------------------------------------------------------------------
% estwrite Normalise: Estimate & Write
% ---------------------------------------------------------------------
estwrite = cfg_exbranch;
estwrite.tag = 'estwrite';
estwrite.name = 'Normalise: Estimate & Write';
estwrite.val = {ewsubjs eoptions roptions };
estwrite.help = {'Computes the warp that best registers a source image (or series of source images) to match a template, saving it to the file imagename''_sn.mat''. This option also allows the contents of the imagename''_sn.mat'' files to be applied to a series of images.'};
estwrite.prog = @spm_run_normalise_estwrite;
estwrite.vout = @vout_estwrite;
% ---------------------------------------------------------------------
% normalise Normalise
% ---------------------------------------------------------------------
normalise = cfg_choice;
normalise.tag = 'normalise';
normalise.name = 'Normalise';
normalise.help = {
'This very ancient module spatially (stereotactically) normalises MRI, PET or SPECT images into a standard space defined by some ideal model or template image[s]. The template images supplied with SPM conform to the space defined by the ICBM, NIH P-20 project, and approximate that of the the space described in the atlas of Talairach and Tournoux (1988). The transformation can also be applied to any other image that has been coregistered with these scans. A few researchers may wish to continue using this strategy, but (when good quality anatomical MRI scans are available) the DARTEL approach is now generally recommended instead.'
''
'Generally, the algorithms work by minimising the sum of squares difference between the image which is to be normalised, and a linear combination of one or more template images. For the least squares registration to produce an unbiased estimate of the spatial transformation, the image contrast in the templates (or linear combination of templates) should be similar to that of the image from which the spatial normalisation is derived. The registration simply searches for an optimum solution. If the starting estimates are not good, then the optimum it finds may not find the global optimum.'
''
'The first step of the normalisation is to determine the optimum 12-parameter affine transformation. Initially, the registration is performed by matching the whole of the head (including the scalp) to the template. Following this, the registration proceeded by only matching the brains together, by appropriate weighting of the template voxels. This is a completely automated procedure (that does not require ``scalp editing'') that discounts the confounding effects of skull and scalp differences. A Bayesian framework is used, such that the registration searches for the solution that maximises the a posteriori probability of it being correct /* \cite{ashburner97b} */. i.e., it maximises the product of the likelihood function (derived from the residual squared difference) and the prior function (which is based on the probability of obtaining a particular set of zooms and shears).'
''
'The affine registration is followed by estimating nonlinear deformations, whereby the deformations are defined by a linear combination of three dimensional discrete cosine transform (DCT) basis functions /* \cite{ashburner99a} */. The default options result in each of the deformation fields being described by 1176parameters, where these represent the coefficients of the deformations in three orthogonal directions. The matching involved simultaneously minimising the membrane energies of the deformation fields and the residual squared difference between the images and template(s).'
''
'The primarily use is for stereotactic normalisation to facilitate inter-subject averaging and precise characterisation of functional anatomy /* \cite{ashburner97bir} */. It is not necessary to spatially normalise the data (this is only a pre-requisite for inter-subject averaging or reporting in the Talairach space). If you wish to circumnavigate this step (e.g. if you have single slice data or do not have an appropriate high resolution MRI scan) simply specify where you think the anterior commissure is with the ORIGIN in the header of the first scan (using the ''Display'' facility) and proceed directly to ''Smoothing''or ''Statistics''.'
''
'All normalised *.img scans are written to the same subdirectory as the original *.img, prefixed with a ''w'' (i.e. w*.img). The details of the transformations are displayed in the results window, and the parameters are saved in the "*_sn.mat" file.'
}';
normalise.values = {est write estwrite };
%normalise.num = [1 Inf];
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function dep = vout_estimate(job)
for k=1:numel(job.subj)
dep(k) = cfg_dep;
dep(k).sname = sprintf('Norm Params File (Subj %d)',k);
dep(k).src_output = substruct('()',{k},'.','params');
dep(k).tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}});
end;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function dep = vout_write(job)
for k=1:numel(job.subj)
dep(k) = cfg_dep;
dep(k).sname = sprintf('Normalised Images (Subj %d)',k);
dep(k).src_output = substruct('()',{k},'.','files');
dep(k).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
end;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function dep = vout_estwrite(job)
depe = vout_estimate(job);
depw = vout_write(job);
dep = [depe depw];
|
github
|
philippboehmsturm/antx-master
|
spm_run_check_reg_adv.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/config/spm_run_check_reg_adv.m
| 7,221 |
utf_8
|
c6c96f98231a4807166f63e0998bed82
|
function varargout = spm_run_check_reg_adv(cmd, varargin)
% Template function to implement callbacks for an cfg_exbranch. The calling
% syntax is
% varargout = spm_run_check_reg_adv(cmd, varargin)
% where cmd is one of
% 'run' - out = spm_run_check_reg_adv('run', job)
% Run a job, and return its output argument
% 'vout' - dep = spm_run_check_reg_adv('vout', job)
% Examine a job structure with all leafs present and return an
% array of cfg_dep objects.
% 'check' - str = spm_run_check_reg_adv('check', subcmd, subjob)
% Examine a part of a fully filled job structure. Return an empty
% string if everything is ok, or a string describing the check
% error. subcmd should be a string that identifies the part of
% the configuration to be checked.
% 'defaults' - defval = spm_run_check_reg_adv('defaults', key)
% Retrieve defaults value. key must be a sequence of dot
% delimited field names into the internal def struct which is
% kept in function local_def. An error is returned if no
% matching field is found.
% spm_run_check_reg_adv('defaults', key, newval)
% Set the specified field in the internal def struct to a new
% value.
% Application specific code needs to be inserted at the following places:
% 'run' - main switch statement: code to compute the results, based on
% a filled job
% 'vout' - main switch statement: code to compute cfg_dep array, based
% on a job structure that has all leafs, but not necessarily
% any values filled in
% 'check' - create and populate switch subcmd switchyard
% 'defaults' - modify initialisation of defaults in subfunction local_defs
% Callbacks can be constructed using anonymous function handles like this:
% 'run' - @(job)spm_run_check_reg_adv('run', job)
% 'vout' - @(job)spm_run_check_reg_adv('vout', job)
% 'check' - @(job)spm_run_check_reg_adv('check', 'subcmd', job)
% 'defaults' - @(val)spm_run_check_reg_adv('defaults', 'defstr', val{:})
% Note the list expansion val{:} - this is used to emulate a
% varargin call in this function handle.
%
% This code is part of a batch job configuration system for MATLAB. See
% help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging
% Volkmar Glauche
% $Id: spm_run_check_reg_adv.m 664 2012-01-18 08:51:41Z vglauche $
rev = '$Rev: 664 $'; %#ok
if ischar(cmd)
switch lower(cmd)
case 'run'
job = local_getjob(varargin{1});
% do computation, return results in variable out
% display images
spm_check_registration(char([job.imdisp.fname]'));
% modify settings, if necessary
global st;
for k = 1:numel(job.imdisp)
st.vols{k}.mapping = job.imdisp(k).mapping;
if isfield(job.imdisp(k).window,'auto')
st.vols{k}.window = 'auto';
else
st.vols{k}.window = job.imdisp(k).window.manual;
end
switch char(fieldnames(job.imdisp(k).blobs))
case 'blob'
switch char(fieldnames(job.imdisp(k).blobs.blob.bsource))
case 'image'
spm_orthviews('addimage',k,job.imdisp(k).blobs.blob.bsource.image{1});
otherwise
warning('Unsupported blob source');
end
if isfield(job.imdisp(k).blobs.blob.window,'manual')
st.vols{k}.blobs{1}.min = job.imdisp(k).blobs.blob.window.manual(1);
st.vols{k}.blobs{1}.max = job.imdisp(k).blobs.blob.window.manual(2);
end
case 'cblob'
for l = 1:numel(job.imdisp(k).blobs.cblob)
switch char(fieldnames(job.imdisp(k).blobs.cblob(l).bsource))
case 'image'
for cimg = 1:numel(job.imdisp(k).blobs.cblob(l).bsource.image)
spm_orthviews('addcolouredimage',k,job.imdisp(k).blobs.cblob(l).bsource.image{cimg},job.imdisp(k).blobs.cblob(l).colour);
end
otherwise
warning('Unsupported blob source');
end
if isfield(job.imdisp(k).blobs.cblob(l).window,'manual')
st.vols{k}.blobs{l}.min = job.imdisp(k).blobs.cblob(l).window.manual(1);
st.vols{k}.blobs{l}.max = job.imdisp(k).blobs.cblob(l).window.manual(2);
end
end
end
end
spm_orthviews('redraw');
if nargout > 0
varargout{1} = out;
end
case 'vout'
job = local_getjob(varargin{1});
% initialise empty cfg_dep array
dep = cfg_dep;
dep = dep(false);
% determine outputs, return cfg_dep array in variable dep
varargout{1} = dep;
case 'check'
if ischar(varargin{1})
subcmd = lower(varargin{1});
subjob = varargin{2};
str = '';
switch subcmd
% implement checks, return status string in variable str
otherwise
cfg_message('unknown:check', ...
'Unknown check subcmd ''%s''.', subcmd);
end
varargout{1} = str;
else
cfg_message('ischar:check', 'Subcmd must be a string.');
end
case 'defaults'
if nargin == 2
varargout{1} = local_defs(varargin{1});
else
local_defs(varargin{1:2});
end
otherwise
cfg_message('unknown:cmd', 'Unknown command ''%s''.', cmd);
end
else
cfg_message('ischar:cmd', 'Cmd must be a string.');
end
function varargout = local_defs(defstr, defval)
persistent defs;
if isempty(defs)
% initialise defaults
end
if ischar(defstr)
% construct subscript reference struct from dot delimited tag string
tags = textscan(defstr,'%s', 'delimiter','.');
subs = struct('type','.','subs',tags{1}');
try
cdefval = subsref(local_def, subs);
catch
cdefval = [];
cfg_message('defaults:noval', ...
'No matching defaults value ''%s'' found.', defstr);
end
if nargin == 1
varargout{1} = cdefval;
else
defs = subsasgn(defs, subs, defval);
end
else
cfg_message('ischar:defstr', 'Defaults key must be a string.');
end
function job = local_getjob(job)
if ~isstruct(job)
cfg_message('isstruct:job', 'Job must be a struct.');
end
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_disp.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_disp.m
| 4,719 |
utf_8
|
9f6f5adf2e1375a3f6df5d5daeb54bae
|
function disp = spm_cfg_disp
% SPM Configuration file for Image Display
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% $Id: spm_cfg_disp.m 4205 2011-02-21 15:39:08Z guillaume $
%-------------------------------------------------------------------------
% data Image to Display
%-------------------------------------------------------------------------
data = cfg_files;
data.tag = 'data';
data.name = 'Image to Display';
data.help = {'Image to display.'};
data.filter = 'image';
data.ufilter = '.*';
data.num = [1 1];
%--------------------------------------------------------------------------
% disp Display Image
%--------------------------------------------------------------------------
disp = cfg_exbranch;
disp.tag = 'disp';
disp.name = 'Display Image';
disp.val = {data};
disp.help = {
'This is an interactive facility that allows orthogonal sections from an image volume to be displayed. Clicking the cursor on either of the three images moves the point around which the orthogonal sections are viewed. The co-ordinates of the cursor are shown both in voxel co-ordinates and millimetres within some fixed framework. The intensity at that point in the image (sampled using the current interpolation scheme) is also given. The position of the cross-hairs can also be moved by specifying the co-ordinates in millimetres to which they should be moved. Clicking on the horizontal bar above these boxes will move the cursor back to the origin (analogous to setting the cross-hair position (in mm) to [0 0 0]).'
''
'The images can be re-oriented by entering appropriate translations, rotations and zooms into the panel on the left. The transformations can then be saved by hitting the "Reorient images..." button. The transformations that were applied to the image are saved to the header information of the selected images. The transformations are considered to be relative to any existing transformations that may be stored. Note that the order that the transformations are applied in is the same as in spm_matrix.m.'
''
'The "Reset..." button next to it is for setting the orientation of images back to transverse. It retains the current voxel sizes, but sets the origin of the images to be the centre of the volumes and all rotations back to zero.'
''
'The right panel shows miscellaneous information about the image. This includes:'
' Dimensions - the x, y and z dimensions of the image.'
' Datatype - the computer representation of each voxel.'
' Intensity - scale-factors and possibly a DC offset.'
' Miscellaneous other information about the image.'
' Vox size - the distance (in mm) between the centres of neighbouring voxels.'
' Origin - the voxel at the origin of the co-ordinate system'
' DIr Cos - Direction cosines. This is a widely used representation of the orientation of an image.'
''
'There are also a few options for different resampling modes, zooms etc. You can also flip between voxel space (as would be displayed by Analyze) or world space (the orientation that SPM considers the image to be in). If you are re-orienting the images, make sure that world space is specified. Blobs (from activation studies) can be superimposed on the images and the intensity windowing can also be changed.'
''
''
'If you have put your images in the correct file format, then (possibly after specifying some rigid-body rotations):'
' The top-left image is coronal with the top (superior) of the head displayed at the top and the left shown on the left. This is as if the subject is viewed from behind.'
' The bottom-left image is axial with the front (anterior) of the head at the top and the left shown on the left. This is as if the subject is viewed from above.'
' The top-right image is sagittal with the front (anterior) of the head at the left and the top of the head shown at the top. This is as if the subject is viewed from the left.'
'/*\begin{figure} \begin{center} \includegraphics[width=150mm]{images/disp1} \end{center} \caption{The Display routine. \label{disp1}}\end{figure} */'
}';
disp.prog = @disp_image;
%==========================================================================
function disp_image(job)
spm_image('Init', job.data{1});
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_st.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_st.m
| 8,731 |
utf_8
|
16a36edc715d472d387db03f6733781d
|
function st = spm_cfg_st
% SPM Configuration file for Slice Timing Correction
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% $Id: spm_cfg_st.m 4269 2011-03-29 16:03:43Z guillaume $
% ---------------------------------------------------------------------
% scans Session
% ---------------------------------------------------------------------
scans = cfg_files;
scans.tag = 'scans';
scans.name = 'Session';
scans.help = {'Select images to slice-time correct.'};
scans.filter = 'image';
scans.ufilter = '.*';
scans.num = [2 Inf];
% ---------------------------------------------------------------------
% generic Data
% ---------------------------------------------------------------------
generic = cfg_repeat;
generic.tag = 'generic';
generic.name = 'Data';
generic.help = {'Subjects or sessions. The same parameters specified below will be applied to all sessions.'};
generic.values = {scans };
generic.num = [1 Inf];
% ---------------------------------------------------------------------
% nslices Number of Slices
% ---------------------------------------------------------------------
nslices = cfg_entry;
nslices.tag = 'nslices';
nslices.name = 'Number of Slices';
nslices.help = {'Enter the number of slices.'};
nslices.strtype = 'n';
nslices.num = [1 1];
% ---------------------------------------------------------------------
% tr TR
% ---------------------------------------------------------------------
tr = cfg_entry;
tr.tag = 'tr';
tr.name = 'TR';
tr.help = {'Enter the TR (in seconds).'};
tr.strtype = 'r';
tr.num = [1 1];
% ---------------------------------------------------------------------
% ta TA
% ---------------------------------------------------------------------
ta = cfg_entry;
ta.tag = 'ta';
ta.name = 'TA';
ta.help = {'Enter the TA (in seconds). It is usually calculated as TR-(TR/nslices). You can simply enter this equation with the variables replaced by appropriate numbers.'};
ta.strtype = 'e';
ta.num = [1 1];
% ---------------------------------------------------------------------
% so Slice order
% ---------------------------------------------------------------------
so = cfg_entry;
so.tag = 'so';
so.name = 'Slice order';
so.help = {
'Enter the slice order. Bottom slice = 1. Sequence types and examples of code to enter are given below.'
''
'ascending (first slice=bottom): [1:1:nslices]'
''
'descending (first slice=top): [nslices:-1:1]'
''
'interleaved (middle-top):'
' for k = 1:nslices,'
' round((nslices-k)/2 + (rem((nslices-k),2) * (nslices - 1)/2)) + 1,'
' end'
''
'interleaved (bottom -> up): [1:2:nslices 2:2:nslices]'
''
'interleaved (top -> down): [nslices:-2:1, nslices-1:-2:1]'
}';
so.strtype = 'e';
so.num = [1 Inf];
% ---------------------------------------------------------------------
% refslice Reference Slice
% ---------------------------------------------------------------------
refslice = cfg_entry;
refslice.tag = 'refslice';
refslice.name = 'Reference Slice';
refslice.help = {'Enter the reference slice'};
refslice.strtype = 'n';
refslice.num = [1 1];
% ---------------------------------------------------------------------
% prefix Filename Prefix
% ---------------------------------------------------------------------
prefix = cfg_entry;
prefix.tag = 'prefix';
prefix.name = 'Filename Prefix';
prefix.help = {'Specify the string to be prepended to the filenames of the slice-time corrected image file(s). Default prefix is ''a''.'};
prefix.strtype = 's';
prefix.num = [1 Inf];
prefix.def = @(val)spm_get_defaults('slicetiming.prefix', val{:});
% ---------------------------------------------------------------------
% st Slice Timing
% ---------------------------------------------------------------------
st = cfg_exbranch;
st.tag = 'st';
st.name = 'Slice Timing';
st.val = {generic nslices tr ta so refslice prefix };
st.help = {
'Correct differences in image acquisition time between slices. Slice-time corrected files are prepended with an ''a''.'
''
'Note: The sliceorder arg that specifies slice acquisition order is a vector of N numbers, where N is the number of slices per volume. Each number refers to the position of a slice within the image file. The order of numbers within the vector is the temporal order in which those slices were acquired. To check the order of slices within an image file, use the SPM Display option and move the cross-hairs to a voxel co-ordinate of z=1. This corresponds to a point in the first slice of the volume.'
''
'The function corrects differences in slice acquisition times. This routine is intended to correct for the staggered order of slice acquisition that is used during echo-planar scanning. The correction is necessary to make the data on each slice correspond to the same point in time. Without correction, the data on one slice will represent a point in time as far removed as 1/2 the TR from an adjacent slice (in the case of an interleaved sequence).'
''
'This routine "shifts" a signal in time to provide an output vector that represents the same (continuous) signal sampled starting either later or earlier. This is accomplished by a simple shift of the phase of the sines that make up the signal. Recall that a Fourier transform allows for a representation of any signal as the linear combination of sinusoids of different frequencies and phases. Effectively, we will add a constant to the phase of every frequency, shifting the data in time.'
''
'Shifter - This is the filter by which the signal will be convolved to introduce the phase shift. It is constructed explicitly in the Fourier domain. In the time domain, it may be described as an impulse (delta function) that has been shifted in time the amount described by TimeShift. The correction works by lagging (shifting forward) the time-series data on each slice using sinc-interpolation. This results in each time series having the values that would have been obtained had the slice been acquired at the same time as the reference slice. To make this clear, consider a neural event (and ensuing hemodynamic response) that occurs simultaneously on two adjacent slices. Values from slice "A" are acquired starting at time zero, simultaneous to the neural event, while values from slice "B" are acquired one second later. Without correction, the "B" values will describe a hemodynamic response that will appear to have began one second EARLIER on the "B" slice than on slice "A". To correct for this, the "B" values need to be shifted towards the Right, i.e., towards the last value.'
''
'This correction assumes that the data are band-limited (i.e. there is no meaningful information present in the data at a frequency higher than that of the Nyquist). This assumption is support by the study of Josephs et al (1997, NeuroImage) that obtained event-related data at an effective TR of 166 msecs. No physio-logical signal change was present at frequencies higher than our typical Nyquist (0.25 HZ).'
''
'When using the slice timing correction it is very important that you input the correct slice order, and if there is any uncertainty then users are encouraged to work with their physicist to determine the actual slice acquisition order.'
''
'One can also consider augmenting the model by including the temporal derivative in the informed basis set instead of slice timing, which can account for +/- 1 second of changes in timing.'
''
'Written by Darren Gitelman at Northwestern U., 1998. Based (in large part) on ACQCORRECT.PRO from Geoff Aguirre and Eric Zarahn at U. Penn.'
}';
st.prog = @spm_run_st;
st.vout = @vout;
st.modality = {'FMRI'};
% ---------------------------------------------------------------------
% ---------------------------------------------------------------------
function dep = vout(job)
for k=1:numel(job.scans)
dep(k) = cfg_dep;
dep(k).sname = sprintf('Slice Timing Corr. Images (Sess %d)', k);
dep(k).src_output = substruct('()',{k}, '.','files');
dep(k).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
end
return;
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_eeg_inv_invert.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_eeg_inv_invert.m
| 7,820 |
utf_8
|
d768c9182c47d6daeccc44b246268094
|
function invert = spm_cfg_eeg_inv_invert
% configuration file for configuring imaging source inversion
% reconstruction
%_______________________________________________________________________
% Copyright (C) 2010 Wellcome Trust Centre for Neuroimaging
% Vladimir Litvak
% $Id: spm_cfg_eeg_inv_invert.m 4326 2011-05-13 14:13:17Z vladimir $
D = cfg_files;
D.tag = 'D';
D.name = 'M/EEG datasets';
D.filter = 'mat';
D.num = [1 Inf];
D.help = {'Select the M/EEG mat files.'};
val = cfg_entry;
val.tag = 'val';
val.name = 'Inversion index';
val.strtype = 'n';
val.help = {'Index of the cell in D.inv where the forward model can be found and the results will be stored.'};
val.val = {1};
all = cfg_const;
all.tag = 'all';
all.name = 'All';
all.val = {1};
condlabel = cfg_entry;
condlabel.tag = 'condlabel';
condlabel.name = 'Condition label';
condlabel.strtype = 's';
condlabel.val = {''};
conditions = cfg_repeat;
conditions.tag = 'conditions';
conditions.name = 'Conditions';
conditions.help = {'Specify the labels of the conditions to be included in the inversion'};
conditions.num = [1 Inf];
conditions.values = {condlabel};
conditions.val = {condlabel};
whatconditions = cfg_choice;
whatconditions.tag = 'whatconditions';
whatconditions.name = 'What conditions to include?';
whatconditions.values = {all, conditions};
whatconditions.val = {all};
standard = cfg_const;
standard.tag = 'standard';
standard.name = 'Standard';
standard.help = {'Use default settings for the inversion'};
standard.val = {1};
invtype = cfg_menu;
invtype.tag = 'invtype';
invtype.name = 'Inversion type';
invtype.help = {'Select the desired inversion type'};
invtype.labels = {'GS', 'ARD', 'MSP (GS+ARD)' 'COH', 'IID'};
invtype.values = {'GS', 'ARD', 'MSP', 'LOR', 'IID'};
invtype.val = {'GS'};
woi = cfg_entry;
woi.tag = 'woi';
woi.name = 'Time window of interest';
woi.strtype = 'r';
woi.num = [1 2];
woi.val = {[-Inf Inf]};
woi.help = {'Time window to include in the inversion (ms)'};
foi = cfg_entry;
foi.tag = 'foi';
foi.name = 'Frequency window of interest';
foi.strtype = 'r';
foi.num = [1 2];
foi.val = {[0 256]};
foi.help = {'Frequency window (the same as high-pass and low-pass in the GUI)'};
hanning = cfg_menu;
hanning.tag = 'hanning';
hanning.name = 'PST Hanning window';
hanning.help = {'Multiply the time series by a Hanning taper to emphasize the central part of the response.'};
hanning.labels = {'yes', 'no'};
hanning.values = {1, 0};
hanning.val = {1};
priorsmask = cfg_files;
priorsmask.tag = 'priorsmask';
priorsmask.name = 'Priors file';
priorsmask.filter = '(.*\.gii$)|(.*\.mat$)|(.*\.nii(,\d+)?$)|(.*\.img(,\d+)?$)';
priorsmask.num = [0 1];
priorsmask.help = {'Select a mask or a mat file with priors.'};
priorsmask.val = {{''}};
space = cfg_menu;
space.tag = 'space';
space.name = 'Prior image space';
space.help = {'Space of the mask image.'};
space.labels = {'MNI', 'Native'};
space.values = {1, 0};
space.val = {1};
priors = cfg_branch;
priors.tag = 'priors';
priors.name = 'Source priors';
priors.help = {'Restrict solutions to pre-specified VOIs'};
priors.val = {priorsmask, space};
locs = cfg_entry;
locs.tag = 'locs';
locs.name = 'Source locations';
locs.strtype = 'r';
locs.num = [Inf 3];
locs.help = {'Input source locations as n x 3 matrix'};
locs.val = {zeros(0, 3)};
radius = cfg_entry;
radius.tag = 'radius';
radius.name = 'Radius of VOI (mm)';
radius.strtype = 'r';
radius.num = [1 1];
radius.val = {32};
restrict = cfg_branch;
restrict.tag = 'restrict';
restrict.name = 'Restrict solutions';
restrict.help = {'Restrict solutions to pre-specified VOIs'};
restrict.val = {locs, radius};
custom = cfg_branch;
custom.tag = 'custom';
custom.name = 'Custom';
custom.help = {'Define custom settings for the inversion'};
custom.val = {invtype, woi, foi, hanning, priors, restrict};
isstandard = cfg_choice;
isstandard.tag = 'isstandard';
isstandard.name = 'Inversion parameters';
isstandard.help = {'Choose whether to use standard or custom inversion parameters.'};
isstandard.values = {standard, custom};
isstandard.val = {standard};
modality = cfg_menu;
modality.tag = 'modality';
modality.name = 'Select modalities';
modality.help = {'Select modalities for the inversion (only relevant for multimodal datasets).'};
modality.labels = {'All', 'EEG', 'MEG', 'MEGPLANAR', 'EEG+MEG', 'MEG+MEGPLANAR', 'EEG+MEGPLANAR'};
modality.values = {
{'All'}
{'EEG'}
{'MEG'}
{'MEGPLANAR'}
{'EEG', 'MEG'}
{'MEG', 'MEGPLANAR'}
{'EEG', 'MEGPLANAR'}
}';
modality.val = {{'All'}};
invert = cfg_exbranch;
invert.tag = 'invert';
invert.name = 'M/EEG source inversion';
invert.val = {D, val, whatconditions, isstandard, modality};
invert.help = {'Run imaging source reconstruction'};
invert.prog = @run_inversion;
invert.vout = @vout_inversion;
invert.modality = {'EEG'};
function out = run_inversion(job)
D = spm_eeg_load(job.D{1});
inverse = [];
if isfield(job.whatconditions, 'condlabel')
inverse.trials = job.whatconditions.condlabel;
end
if isfield(job.isstandard, 'custom')
inverse.type = job.isstandard.custom.invtype;
inverse.woi = fix([max(min(job.isstandard.custom.woi), 1000*D.time(1)) min(max(job.isstandard.custom.woi), 1000*D.time(end))]);
inverse.Han = job.isstandard.custom.hanning;
inverse.lpf = fix(min(job.isstandard.custom.foi));
inverse.hpf = fix(max(job.isstandard.custom.foi));
P = char(job.isstandard.custom.priors.priorsmask);
if ~isempty(P)
[p,f,e] = fileparts(P);
switch lower(e)
case '.gii'
g = gifti(P);
inverse.pQ = cell(1,size(g.cdata,2));
for i=1:size(g.cdata,2)
inverse.pQ{i} = double(g.cdata(:,i));
end
case '.mat'
load(P);
inverse.pQ = pQ;
case {'.img', '.nii'}
S.D = D;
S.fmri = P;
S.space = job.isstandard.custom.priors.space;
D = spm_eeg_inv_fmripriors(S);
inverse.fmri = D.inv{D.val}.inverse.fmri;
load(inverse.fmri.priors);
inverse.pQ = pQ;
otherwise
error('Unknown file type.');
end
end
if ~isempty(job.isstandard.custom.restrict.locs)
inverse.xyz = job.isstandard.custom.restrict.locs;
inverse.rad = job.isstandard.custom.restrict.radius;
end
end
[mod, list] = modality(D, 1, 1);
if strcmp(job.modality{1}, 'All')
inverse.modality = list;
else
inverse.modality = intersect(list, job.modality);
end
if numel(inverse.modality) == 1
inverse.modality = inverse.modality{1};
end
D = {};
for i = 1:numel(job.D)
D{i} = spm_eeg_load(job.D{i});
D{i}.val = job.val;
D{i}.con = 1;
if ~isfield(D{i}, 'inv')
error(sprintf('Forward model is missing for subject %d', i));
elseif numel(D{i}.inv)<D{i}.val || ~isfield(D{i}.inv{D{i}.val}, 'forward')
if D{i}.val>1 && isfield(D{i}.inv{D{i}.val-1}, 'forward')
D{i}.inv{D{i}.val} = D{i}.inv{D{i}.val-1};
warning(sprintf('Duplicating the last forward model for subject %d', i));
else
error(sprintf('Forward model is missing for subject %d', i));
end
end
D{i}.inv{D{i}.val}.inverse = inverse;
end
D = spm_eeg_invert(D);
if ~iscell(D)
D = {D};
end
for i = 1:numel(D)
save(D{i});
end
out.D = job.D;
function dep = vout_inversion(job)
% Output is always in field "D", no matter how job is structured
dep = cfg_dep;
dep.sname = 'M/EEG dataset(s) after imaging source reconstruction';
% reference field "D" from output
dep.src_output = substruct('.','D');
% this can be entered into any evaluated input
dep.tgt_spec = cfg_findspec({{'filter','mat'}});
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_eeg_inv_extract.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_eeg_inv_extract.m
| 3,307 |
utf_8
|
42d3e193e87fc5b983a7382f3f7d68e4
|
function extract = spm_cfg_eeg_inv_extract
% configuration file for extracting source data from imaging source
% reconstruction
%_______________________________________________________________________
% Copyright (C) 2011 Wellcome Trust Centre for Neuroimaging
% Vladimir Litvak
% $Id: spm_cfg_eeg_inv_extract.m 4257 2011-03-18 15:28:29Z vladimir $
D = cfg_files;
D.tag = 'D';
D.name = 'M/EEG datasets';
D.filter = 'mat';
D.num = [1 Inf];
D.help = {'Select the M/EEG mat files.'};
val = cfg_entry;
val.tag = 'val';
val.name = 'Inversion index';
val.strtype = 'n';
val.help = {'Index of the cell in D.inv where the inversion results are be stored.'};
val.val = {1};
xyz = cfg_entry;
xyz.tag = 'xyz';
xyz.name = 'Source location';
xyz.strtype = 'r';
xyz.num = [1 3];
xyz.help = {'Source location (in MNI coordinates)'};
label = cfg_entry;
label.tag = 'label';
label.name = 'Source label';
label.strtype = 's';
label.num = [1 Inf];
label.help = {'Label for the source channel in the output file'};
source = cfg_branch;
source.tag = 'source';
source.name = 'Source';
source.val = {label, xyz};
sources = cfg_repeat;
sources.tag = 'sources';
sources.name = 'Sources to extract';
sources.values = {source};
sources.num = [1 Inf];
sources.help = {'Specify sources to extract data from'};
rad = cfg_entry;
rad.tag = 'rad';
rad.name = 'VOI radius';
rad.strtype = 'r';
rad.num = [1 1];
rad.val = {5};
woi.help = {'Radius around each location to extract an eigenvariate from (mm).'};
type = cfg_menu;
type.tag = 'type';
type.name = 'What to extract';
type.help = {'What to extract: evoked activity or single trials.'};
type.labels = {'Evoked', 'Single trials'};
type.values = {'evoked', 'trials'};
type.val = {'trials'};
fname = cfg_entry;
fname.tag = 'fname';
fname.name = 'Output dataset name';
fname.strtype = 's';
fname.num = [0 Inf];
fname.val = {''};
fname.help = {'Output file name (empty for default)'};
extract = cfg_exbranch;
extract.tag = 'extract';
extract.name = 'M/EEG source extraction';
extract.val = {D, val, sources, rad, type, fname};
extract.help = {'Extract source data from the results of inverse source reconstruction'};
extract.prog = @run_extract;
extract.vout = @vout_extract;
extract.modality = {'EEG'};
function out = run_extract(job)
source = [];
source.XYZ = cat(1, job.source.xyz);
source.label = {job.source.label};
source.rad = job.rad;
source.type = job.type;
if ~isempty(job.fname)
source.fname = job.fname;
end
out.D = {};
for i = 1:numel(job.D)
D = spm_eeg_load(job.D{i});
D.val = job.val;
if ~isfield(D.inv{D.val}, 'inverse') || ~isfield(D.inv{D.val}.inverse, 'J')
error(sprintf('Imaging source reconstruction is missing for subject %d', i));
end
D.inv{D.val}.source = source;
Ds = spm_eeg_inv_extract(D);
out.D{i, 1} = fullfile(Ds.path, Ds.fname);
end
function dep = vout_extract(job)
% Output is always in field "D", no matter how job is structured
% Output is always in field "D", no matter how job is structured
dep = cfg_dep;
dep.sname = 'M/EEG dataset(s) extracted source data';
% reference field "D" from output
dep.src_output = substruct('.','D');
% this can be entered into any evaluated input
dep.tgt_spec = cfg_findspec({{'filter','mat'}});
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_fmri_est.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_fmri_est.m
| 24,501 |
utf_8
|
14607a45526013760c39408f23f0d2fa
|
function fmri_est = spm_cfg_fmri_est
% SPM Configuration file for Model Estimation
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% $Id: spm_cfg_fmri_est.m 3753 2010-03-05 13:06:47Z guillaume $
% ---------------------------------------------------------------------
% spmmat Select SPM.mat
% ---------------------------------------------------------------------
spmmat = cfg_files;
spmmat.tag = 'spmmat';
spmmat.name = 'Select SPM.mat';
spmmat.help = {
'Select the SPM.mat file that contains the design specification. '
'The directory containing this file is known as the input directory.'
}';
spmmat.filter = 'mat';
spmmat.ufilter = '^SPM\.mat$';
spmmat.num = [1 1];
% ---------------------------------------------------------------------
% Classical Classical
% ---------------------------------------------------------------------
Classical = cfg_const;
Classical.tag = 'Classical';
Classical.name = 'Classical';
Classical.val = {1};
Classical.help = {
'Model parameters are estimated using Restricted Maximum Likelihood (ReML). This assumes the error correlation structure is the same at each voxel. This correlation can be specified using either an AR(1) or an Independent and Identically Distributed (IID) error model. These options are chosen at the model specification stage. ReML estimation should be applied to spatially smoothed functional images.'
''
'After estimation, specific profiles of parameters are tested using a linear compound or contrast with the T or F statistic. The resulting statistical map constitutes an SPM. The SPM{T}/{F} is then characterised in terms of focal or regional differences by assuming that (under the null hypothesis) the components of the SPM (ie. residual fields) behave as smooth stationary Gaussian fields.'
}';
% ---------------------------------------------------------------------
% Volume Volume
% ---------------------------------------------------------------------
volBlocktype = cfg_menu;
volBlocktype.tag = 'block_type';
volBlocktype.name = 'Block type';
volBlocktype.val = {'Slices'};
volBlocktype.help = {'Enter the block type, i.e. "Slices" or "Subvolumes"'}';
volBlocktype.labels = {'Slices', 'Subvolumes'}';
volBlocktype.values = {'Slices', 'Subvolumes'}';
Volume = cfg_branch;
Volume.tag = 'volume';
Volume.name = 'Volume';
Volume.val = {volBlocktype};
Volume.help = {'A volume of data is analysed in "blocks", which can be a slice or 3D subvolume, where the extent of each subvolume is determined using a graph partitioning algorithm. Enter the block type, i.e. "Slices" or "Subvolumes".'};
% ---------------------------------------------------------------------
% Slices Slices
% ---------------------------------------------------------------------
SliceNs = cfg_entry;
SliceNs.tag = 'numbers';
SliceNs.name = 'Slice numbers';
SliceNs.help = {' '};
SliceNs.strtype = 'e';
SliceNs.num = [Inf 1];
slBlocktype = cfg_menu;
slBlocktype.tag = 'block_type';
slBlocktype.name = 'Block type';
slBlocktype.val = {'Slices'};
slBlocktype.help = {'Enter the block type, i.e. "Slices" or "Subvolumes"'}';
slBlocktype.labels = {'Slices', 'Subvolumes'}';
slBlocktype.values = {'Slices', 'Subvolumes'}';
Slices = cfg_branch;
Slices.tag = 'slices';
Slices.name = 'Slices';
Slices.val = {SliceNs slBlocktype};
Slices.help = {'Enter Slice Numbers. This can be a single slice or multiple slices. If you select a single slice or only a few slices you must be aware of the interpolation options when, after estimation, displaying the estimated images eg. images of contrasts or AR maps. The default interpolation option may need to be changed to nearest neighbour (NN) (see bottom right hand of graphics window) for you slice maps to be visible.'};
% ---------------------------------------------------------------------
% Clusters
% ---------------------------------------------------------------------
Clustermask = cfg_files;
Clustermask.tag = 'mask';
Clustermask.name = 'Cluster mask';
Clustermask.help = {'Select cluster image'}';
Clustermask.filter = 'image';
Clustermask.ufilter = '.*';
Clustermask.num = [0 1];
clBlocktype = cfg_menu;
clBlocktype.tag = 'block_type';
clBlocktype.name = 'Block type';
clBlocktype.val = {'Slices'};
clBlocktype.help = {'Enter the block type, i.e. "Slices" or "Subvolumes"'}';
clBlocktype.labels = {'Slices', 'Subvolumes'}';
clBlocktype.values = {'Slices', 'Subvolumes'}';
Clusters = cfg_branch;
Clusters.tag = 'clusters';
Clusters.name = 'Clusters';
Clusters.val = {Clustermask clBlocktype};
Clusters.help = {'Because estimation can be time consuming an option is provided to analyse selected clusters rather than the whole volume.'};
% ---------------------------------------------------------------------
% space Analysis Space
% ---------------------------------------------------------------------
space = cfg_choice;
space.tag = 'space';
space.name = 'Analysis Space';
space.val = {Volume};
space.help = {'Because estimation can be time consuming options are provided to analyse selected slices or clusters rather than the whole volume.'};
space.values = {Volume Slices Clusters};
% ---------------------------------------------------------------------
% LogEv - Compute F
% ---------------------------------------------------------------------
LogEv = cfg_menu;
LogEv.tag = 'LogEv';
LogEv.name = 'Log evidence map';
LogEv.val = {'No'};
LogEv.help = {'Computes the log evidence for each voxel'};
LogEv.labels = {'No','Yes'}';
LogEv.values = {'No','Yes'}';
% ---------------------------------------------------------------------
% signal Signal priors
% ---------------------------------------------------------------------
signal = cfg_menu;
signal.tag = 'signal';
signal.name = 'Signal priors';
signal.help = {
'[UGL] Unweighted Graph Laplacian. This spatial prior is the recommended option. Regression coefficients at a given voxel are (softly) constrained to be similar to those at nearby voxels. The strength of this constraint is determined by a spatial precision parameter that is estimated from the data. Different regression coefficients have different spatial precisions allowing each putative experimental effect to have its own spatial regularity. '
''
'[GMRF] Gaussian Markov Random Field. This is equivalent to a normalized UGL. '
''
'[LORETA] Low resolution Tomography Prior. This is equivalent to UGL squared. It is a standatd choice for EEG source localisation algorithms. '
''
'[WGL] Weighted Graph Laplacian. This is a generalization of the UGL, where weights can be used to preserve "edges" of functional responses.'
''
'[Global] Global Shrinkage prior. This is not a spatial prior in the sense that regression coefficients are constrained to be similar to neighboring voxels. Instead, the average effect over all voxels (global effect) is assumed to be zero and all regression coefficients are shrunk towards this value in proporation to the prior precision. This is the same prior that is used for Bayesian estimation at the second level models, except that here the prior precision is estimated separaetly for each slice. '
''
'[Uninformative] A flat prior. Essentially, no prior information is used. If you select this option then VB reduces to Maximum Likelihood (ML)estimation. This option is useful if, for example, you do not wish to use a spatial prior but wish to take advantage of the voxel-wise AR(P) modelling of noise processes. In this case, you would apply the algorithm to images that have been spatially smoothed. For P=0, ML estimation in turn reduces to Ordinary Least Squares (OLS) estimates, and for P>0 ML estimation is equivalent to a weighted least squares (WLS) but where the weights are different at each voxel (reflecting the different noise correlation at each voxel). '
}';
signal.labels = {
'UGL'
'GMRF'
'LORETA'
'WGL'
'Global'
'Uninformative'
}';
signal.values = {
'UGL'
'GMRF'
'LORETA'
'WGL'
'Global'
'Uninformative'
}';
signal.val = {'UGL'};
% ---------------------------------------------------------------------
% ARP AR model order
% ---------------------------------------------------------------------
ARP = cfg_entry;
ARP.tag = 'ARP';
ARP.name = 'AR model order';
ARP.help = {
'An AR model order of 3 is the default. Cardiac and respiratory artifacts are periodic in nature and therefore require an AR order of at least 2. In previous work, voxel-wise selection of the optimal model order showed that a value of 3 was the highest order required. '
''
'Higher model orders have little effect on the estimation time. If you select a model order of zero this corresponds to the assumption that the errors are IID. This AR specification overrides any choices that were made in the model specification stage.'
''
'Voxel-wise AR models are fitted separately for each session of data. For each session this therefore produces maps of AR(1), AR(2) etc coefficients in the output directory. '
}';
ARP.strtype = 'e';
ARP.num = [Inf 1];
ARP.val = {3};
% ---------------------------------------------------------------------
% UGL UGL
% ---------------------------------------------------------------------
UGL = cfg_const;
UGL.tag = 'UGL';
UGL.name = 'UGL';
UGL.val = {1};
UGL.help = {'[UGL] Unweighted graph-Laplacian. This is the default option. This spatial prior is the same as that used for the regression coefficients. Spatial precisions are estimated separately for each AR coefficient eg. the AR(1) coefficient over space, AR(2) over space etc. '};
% ---------------------------------------------------------------------
% GMRF GMRF
% ---------------------------------------------------------------------
GMRF = cfg_const;
GMRF.tag = 'GMRF';
GMRF.name = 'GMRF';
GMRF.val = {1};
GMRF.help = {'[GMRF] Gaussian Markov Random Field. See comments on GMRF priors for regresion coefficients. '};
% ---------------------------------------------------------------------
% LORETA LORETA
% ---------------------------------------------------------------------
LORETA = cfg_const;
LORETA.tag = 'LORETA';
LORETA.name = 'LORETA';
LORETA.val = {1};
LORETA.help = {'[LORETA] Low resolution Tomography Prior. See comments on LORETA priors for regresion coefficients.'};
% ---------------------------------------------------------------------
% tissue_type Tissue-type
% ---------------------------------------------------------------------
tissue_type = cfg_files;
tissue_type.tag = 'tissue_type';
tissue_type.name = 'Tissue-type';
tissue_type.help = {
'[Tissue-type] AR estimates at each voxel are biased towards typical values for that tissue type (eg. gray, white, CSF). If you select this option you will need to then select files that contain tissue type maps (see below). These are typically chosen to be Grey Matter, White Matter and CSF images derived from segmentation of registered structural scans.'
''
'Previous work has shown that there is significant variation in AR values with tissue type. However, GMRF priors have previously been favoured by Bayesian model comparison.'
}';
tissue_type.filter = 'image';
tissue_type.ufilter = '.*';
tissue_type.num = [1 Inf];
% ---------------------------------------------------------------------
% Robust Robust
% ---------------------------------------------------------------------
Robust = cfg_const;
Robust.tag = 'Robust';
Robust.name = 'Robust';
Robust.val = {1};
Robust.help = {'Robust GLM. Uses Mixture of Gaussians noise model.'};
% ---------------------------------------------------------------------
% noise Noise priors
% ---------------------------------------------------------------------
noise = cfg_choice;
noise.tag = 'noise';
noise.name = 'Noise priors';
noise.val = {UGL };
noise.help = {
'There are five noise prior options here (1) UGL, (2) GMRF, (3) LORETA '
'(4) Tissue-type and (5) Robust'
}';
noise.values = {UGL GMRF LORETA tissue_type Robust };
% ---------------------------------------------------------------------
% first First level
% ---------------------------------------------------------------------
first = cfg_menu;
first.tag = 'first';
first.name = 'First level';
first.val = {'No'};
first.help = {
'This is implemented using Bayesian model comparison. For example, to test for the main effect of a factor two models are compared, one where the levels are represented using different regressors and one using the same regressor. This therefore requires explicit fitting of several models at each voxel and is computationally demanding (requiring several hours of computation). The recommended option is therefore NO.'
''
'To use this option you must have already specified your factorial design during the model specification stage. '
}';
first.labels = {
'No'
'Yes'
}';
first.values = {
'No'
'Yes'
}';
% ---------------------------------------------------------------------
% second Second level
% ---------------------------------------------------------------------
second = cfg_menu;
second.tag = 'second';
second.name = 'Second level';
second.val = {'Yes'};
second.help = {
'This option tells SPM to automatically generate the simple contrasts that are necessary to produce the contrast images for a second-level (between-subject) ANOVA. Naturally, these contrasts can also be used to characterise simple effects for each subject. '
''
'With the Bayesian estimation option it is recommended that contrasts are computed during the parameter estimation stage (see ''simple contrasts'' below). The recommended option here is therefore YES.'
''
'To use this option you must have already specified your factorial design during the model specification stage. '
''
'If you wish to use these contrast images for a second-level analysis then you will need to spatially smooth them to take into account between-subject differences in functional anatomy ie. the fact that one persons V5 may be in a different position than anothers. '
}';
second.labels = {
'No'
'Yes'
}';
second.values = {
'No'
'Yes'
}';
% ---------------------------------------------------------------------
% anova ANOVA
% ---------------------------------------------------------------------
anova = cfg_branch;
anova.tag = 'anova';
anova.name = 'ANOVA';
anova.val = {first second };
anova.help = {'Perform 1st or 2nd level Analysis of Variance.'};
% ---------------------------------------------------------------------
% name Name
% ---------------------------------------------------------------------
name = cfg_entry;
name.tag = 'name';
name.name = 'Name';
name.help = {'Name of contrast eg. ''Positive Effect'''};
name.strtype = 's';
name.num = [1 Inf];
% ---------------------------------------------------------------------
% convec Contrast vector
% ---------------------------------------------------------------------
convec = cfg_entry;
convec.tag = 'convec';
convec.name = 'Contrast vector';
convec.help = {'These contrasts are used to generate PPMs which characterise effect sizes at each voxel. This is in contrast to SPMs in which eg. maps of t-statistics show the ratio of the effect size to effect variability (standard deviation). SPMs are therefore a-dimensional. This is not the case for PPMs as the size of the effect is of primary interest. Some care is therefore needed about the scaling of contrast vectors. For example, if you are interested in the differential effect size averaged over conditions then the contrast 0.5 0.5 -0.5 -0.5 would be more suitable than the 1 1 -1 -1 contrast which looks at the differential effect size summed over conditions. '};
convec.strtype = 'e';
convec.num = [Inf 1];
% ---------------------------------------------------------------------
% gcon Simple contrast
% ---------------------------------------------------------------------
gcon = cfg_branch;
gcon.tag = 'gcon';
gcon.name = 'Simple contrast';
gcon.val = {name convec };
gcon.help = {''};
% ---------------------------------------------------------------------
% generic Simple contrasts
% ---------------------------------------------------------------------
generic = cfg_repeat;
generic.tag = 'generic';
generic.name = 'Simple contrasts';
generic.help = {
'''Simple'' contrasts refers to a contrast that spans one-dimension ie. to assess an effect that is increasing or decreasing.'
''
'If you have a factoral design then the contrasts needed to generate the contrast images for a 2nd-level ANOVA (or to assess these simple effects within-subject) can be specified automatically using the ANOVA->Second level option.'
''
'When using the Bayesian estimation option it is computationally more efficient to compute the contrasts when the parameters are estimated. This is because estimated parameter vectors have potentially different posterior covariance matrices at different voxels and these matrices are not stored. If you compute contrasts post-hoc these matrices must be recomputed (an approximate reconstruction based on a Taylor series expansion is used). It is therefore recommended to specify as many contrasts as possible prior to parameter estimation.'
''
'If you wish to use these contrast images for a second-level analysis then you will need to spatially smooth them to take into account between-subject differences in functional anatomy ie. the fact that one persons V5 may be in a different position than anothers. '
}';
generic.values = {gcon };
generic.num = [0 Inf];
% ---------------------------------------------------------------------
% Bayesian Bayesian 1st-level
% ---------------------------------------------------------------------
Bayesian = cfg_branch;
Bayesian.tag = 'Bayesian';
Bayesian.name = 'Bayesian 1st-level';
Bayesian.val = {space signal ARP noise LogEv anova generic };
Bayesian.help = {
'Model parameters are estimated using Variational Bayes (VB). This allows you to specify spatial priors for regression coefficients and regularised voxel-wise AR(P) models for fMRI noise processes. The algorithm does not require functional images to be spatially smoothed. Estimation will take about 5 times longer than with the classical approach. This is why VB is not the default estimation option. '
''
'Model estimation using this option is only efficient if MATLAB can load a whole slice of data into physical memory. With modern PCs this is usually achieved if the within-plane voxel sizes are 3 by 3 mm. This is therefore the minimum recommended voxel size that your spatial normalisation process should produce. Within-plane voxel sizes of 2 by 2 mm usually result in too many voxels per slice and result in estimation times lasting several hours or days. Such a high resolution is therefore to be avoided. '
''
'After estimation, contrasts are used to find regions with effects larger than a user-specified size eg. 1 per cent of the global mean signal. These effects are assessed statistically using a Posterior Probability Map (PPM).'
}';
% ---------------------------------------------------------------------
% Bayesian2 Bayesian 2nd-level
% ---------------------------------------------------------------------
Bayesian2 = cfg_const;
Bayesian2.tag = 'Bayesian2';
Bayesian2.name = 'Bayesian 2nd-level';
Bayesian2.val = {1};
Bayesian2.help = {'Bayesian estimation of 2nd level models. This option uses the Empirical Bayes algorithm with global shrinkage priors that was previously implemented in SPM2. Use of the global shrinkage prior embodies a prior belief that, on average over all voxels, there is no net experimental effect. Some voxels will respond negatively and some positively with a variability determined by the prior precision. This prior precision can be estimated from the data using Empirical Bayes. '};
% ---------------------------------------------------------------------
% method Method
% ---------------------------------------------------------------------
method = cfg_choice;
method.tag = 'method';
method.name = 'Method';
method.val = {Classical };
method.help = {
'There are three possible estimation procedures for fMRI models (1) classical (ReML) estimation of first or second level models, (2) Bayesian estimation of first level models and (3) Bayesian estimation of second level models. Option (2) uses a Variational Bayes (VB) algorithm that is new to SPM5. Option (3) uses the Empirical Bayes algorithm with global shrinkage priors that was also in SPM2. '
''
'To use option (3) you must have already estimated the model using option (1). That is, for second-level models you must run a ReML estimation before running a Bayesian estimation. This is not necessary for option (2). Bayesian estimation of 1st-level models using VB does not require a prior ReML estimation.'
}';
method.values = {Classical Bayesian Bayesian2};
% ---------------------------------------------------------------------
% fmri_est Model estimation
% ---------------------------------------------------------------------
fmri_est = cfg_exbranch;
fmri_est.tag = 'fmri_est';
fmri_est.name = 'Model estimation';
fmri_est.val = {spmmat method };
fmri_est.help = {'Model parameters can be estimated using classical (ReML - Restricted Maximum Likelihood) or Bayesian algorithms. After parameter estimation, the RESULTS button can be used to specify contrasts that will produce Statistical Parametric Maps (SPMs) or Posterior Probability Maps (PPMs) and tables of statistics.'};
fmri_est.prog = @spm_run_fmri_est;
fmri_est.vout = @vout_stats;
fmri_est.modality = {'FMRI' 'PET' 'EEG'};
%==========================================================================
function dep = vout_stats(job)
dep(1) = cfg_dep;
dep(1).sname = 'SPM.mat File';
dep(1).src_output = substruct('.','spmmat');
dep(1).tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}});
%dep(2) = cfg_dep;
%dep(2).sname = 'SPM Variable';
%dep(2).src_output = substruct('.','spmvar');
%dep(2).tgt_spec = cfg_findspec({{'strtype','e'}});
if isfield(job.method, 'Classical')
dep(2) = cfg_dep;
dep(2).sname = 'Beta Images';
dep(2).src_output = substruct('.','beta');
dep(2).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
dep(3) = cfg_dep;
dep(3).sname = 'Analysis Mask';
dep(3).src_output = substruct('.','mask');
dep(3).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
dep(4) = cfg_dep;
dep(4).sname = 'ResMS Image';
dep(4).src_output = substruct('.','resms');
dep(4).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
% can't check whether auto-generated contrasts are generated this is
% specified in input SPM.mat, not this job
end;
|
github
|
philippboehmsturm/antx-master
|
spm_cfg_plot_fdmar.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_plot_fdmar.m
| 1,538 |
utf_8
|
53838da078ffd2b340d1746a4ec0f674
|
function cfg = spm_cfg_plot_fdmar
spmmat = cfg_files;
spmmat.name = 'SPM.mat file';
spmmat.tag = 'spmmat';
spmmat.num = [1 1];
spmmat.filter = '^SPM.mat$';
spmmat.help = {'Select SPM.mat file.'};
%spmmat.check = @has_arfit;
ana = cfg_const;
ana.name = 'SPM analysis mask';
ana.tag = 'ana';
ana.val = {true};
ana.help = {'Plot arfit for all voxels in an analysis.'};
ext = cfg_files;
ext.name = 'External analysis mask';
ext.tag = 'ext';
ext.filter = 'image';
ext.num = [1 1];
ext.help = {['Plot arfit for all voxels in an analysis, that are in the ' ...
'external mask.']};
mask = cfg_choice;
mask.name = 'Masking';
mask.tag = 'mask';
mask.values = {ana ext};
mask.help = {'Specify mask to use'};
sess = cfg_entry;
sess.name = 'Session #';
sess.tag = 'sess';
sess.strtype = 'n';
sess.num = [1 1];
sess.help = {['arfit results can be plotted for only one session at a ' ...
'time.']};
pflag = cfg_menu;
pflag.name = 'Print results to PNG';
pflag.tag = 'pflag';
pflag.labels = {'Yes'; 'No'};
pflag.values = {true; false};
cfg = cfg_exbranch;
cfg.name = 'Plot arfit diagnostics';
cfg.tag = 'plot_fdmar';
cfg.val = {spmmat,mask,sess,pflag};
cfg.prog = @spm_run_plot_fdmar;
function str = has_arfit(spmmat)
try
load(spmmat{1},'SPM');
SPM.xVi.arfit;
str = '';
catch
str = sprintf(['File ''%s'' does not contain a SPM.mat file with arfit ' ...
'information.'], spmmat{1});
end
|
github
|
philippboehmsturm/antx-master
|
paint.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/@slover/paint.m
| 10,669 |
utf_8
|
58c77775943c79df7da192623addf239
|
function obj = paint(obj, params)
% method to display slice overlay
% FORMAT paint(obj, params)
%
% Inputs
% obj - slice overlay object
% params - optional structure containing extra display parameters
% - refreshf - overrides refreshf in object
% - clf - overrides clf in object
% - userdata - if 0, does not add object to userdata field
% (see below)
%
% Outputs
% obj - which may have been filled with defaults
%
% paint attaches the object used for painting to the 'UserData' field of
% the figure handle, unless instructed not to with 0 in userdata flag
%
% $Id: paint.m,v 1.2 2005/05/06 22:59:56 matthewbrett Exp $
fig_struct_fields = {'Position', 'Units'};
if nargin < 2
params = [];
end
params = mars_struct('fillafromb', params, ...
struct('refreshf', obj.refreshf,...
'clf', obj.clf, ...
'userdata', obj.userdata));
% Fill any needed defaults
obj = fill_defaults(obj);
% check if object can be painted
if isempty(obj.img)
warning('slover:noImages', 'No images, object cannot be painted')
return
end
% get coordinates for plane
X=1;Y=2;Z=3;
dims = obj.slicedef;
xmm = dims(X,1):dims(X,2):dims(X,3);
ymm = dims(Y,1):dims(Y,2):dims(Y,3);
zmm = obj.slices;
[y x] = meshgrid(ymm,xmm');
vdims = [length(xmm),length(ymm),length(zmm)];
% no of slices, and panels (an extra for colorbars)
nslices = vdims(Z);
minnpanels = nslices;
cbars = 0;
if ~isempty(obj.cbar)
cbars = length(obj.cbar);
minnpanels = minnpanels+cbars;
end
% Get figure data. The figure may be dead, in which case we may want to
% revive it. If so, we set position etc as stored.
% If written to, the axes may be specified already
dead_f = ~ishandle(obj.figure);
figno = figure(obj.figure);
if dead_f
set(figno, obj.figure_struct);
end
% (re)initialize axes and stuff
% check if the figure is set up correctly
if ~params.refreshf
axisd = flipud(findobj(obj.figure, 'Type','axes','Tag', 'slice overlay panel'));
npanels = length(axisd);
if npanels < vdims(Z)+cbars;
params.refreshf = 1;
end
end
if params.refreshf
% clear figure, axis store
if params.clf, clf; end
% prevent print inversion problems
set(figno,'InvertHardCopy','off');
% put copy of object into UserData for callbacks
if params.userdata
set(figno, 'UserData', obj);
end
% calculate area of display in pixels
parea = obj.area.position;
if ~strcmp(obj.area.units, 'pixels')
ubu = get(obj.figure, 'units');
set(obj.figure, 'units','pixels');
tmp = get(obj.figure, 'Position');
ascf = tmp(3:4);
if ~strcmp(obj.area.units, 'normalized')
set(obj.figure, 'units',obj.area.units);
tmp = get(obj.figure, 'Position');
ascf = ascf ./ tmp(3:4);
end
set(figno, 'Units', ubu);
parea = parea .* repmat(ascf, 1, 2);
end
asz = parea(3:4);
% by default, make most parsimonious fit to figure
yxratio = length(ymm)*dims(Y,2)/(length(xmm)*dims(X,2));
if isempty(obj.xslices)
% iteration needed to optimize, surprisingly. Thanks to Ian NS
axlen(X,:)=asz(1):-1:1;
axlen(Y,:)=yxratio*axlen(X,:);
panels = floor(asz'*ones(1,size(axlen,2))./axlen);
estnpanels = prod(panels);
tmp = find(estnpanels >= minnpanels);
if isempty(tmp)
error('Whoops, cannot fit panels onto figure');
end
b = tmp(1); % best fitting scaling
panels = panels(:,b);
axlen = axlen(:, b);
else
% if xslices is specified, assume X is flush with X figure dimensions
panels(X:Y,1) = [obj.xslices; 0];
axlen(X:Y,1) = [asz(X)/panels(X); 0];
end
% Axis dimensions are in pixels. This prevents aspect ratio rescaling
panels(Y) = ceil(minnpanels/panels(X));
axlen(Y) = axlen(X)*yxratio;
% centre (etc) panels in display area as required
divs = [Inf 2 1];the_ds = [0;0];
the_ds(X) = divs(strcmp(obj.area.halign, {'left','center','right'}));
the_ds(Y) = divs(strcmp(obj.area.valign, {'bottom','middle','top'}));
startc = parea(1:2)' + (asz'-(axlen.*panels))./the_ds;
% make axes for panels
r=0;c=1;
npanels = prod(panels);
lastempty = npanels-cbars;
axisd = nan(1, npanels);
for i = 1:npanels
% panel userdata
if i<=nslices
u.type = 'slice';
u.no = zmm(i);
elseif i > lastempty
u.type = 'cbar';
u.no = i - lastempty;
else
u.type = 'empty';
u.no = i - nslices;
end
axpos = [r*axlen(X)+startc(X) (panels(Y)-c)*axlen(Y)+startc(Y) axlen'];
axisd(i) = axes(...
'Parent',figno,...
'XTick',[],...
'XTickLabel',[],...
'YTick',[],...
'YTickLabel',[],...
'Box','on',...
'XLim',[1 vdims(X)],...
'YLim',[1 vdims(Y)],...
'Units', 'pixels',...
'Position',axpos,...
'Tag','slice overlay panel',...
'UserData',u);
r = r+1;
if r >= panels(X)
r = 0;
c = c+1;
end
end
end
% sort out labels
if ischar(obj.labels)
do_labels = ~strcmpi(obj.labels, 'none');
else
do_labels = 1;
end
if do_labels
labels = obj.labels;
if iscell(labels.format)
if length(labels.format)~=vdims(Z)
error('Oh dear, expecting %d labels, but found %d', ...
vdims(Z), length(labels.contents));
end
else
% format string for mm from AC labelling
fstr = labels.format;
labels.format = cell(vdims(Z),1);
acpt = obj.transform * [0 0 0 1]';
for i = 1:vdims(Z)
labels.format(i) = {sprintf(fstr,zmm(i)-acpt(Z))};
end
end
end
% split images into picture and contour
itypes = {obj.img(:).type};
tmp = strcmpi(itypes, 'contour');
contimgs = find(tmp);
pictimgs = find(~tmp);
% modify picture image colormaps with any new colours
npimgs = length(pictimgs);
lrn = zeros(npimgs,3);
cmaps = cell(npimgs);
for i = 1:npimgs
cmaps(i)={obj.img(pictimgs(i)).cmap};
lrnv = [obj.img(pictimgs(i)).outofrange, obj.img(pictimgs(i)).nancol];
for j = 1:length(lrnv)
if numel(lrnv{j})==1
lrn(i,j) = lrnv{j};
else
cmaps(i) = {[cmaps{i}; lrnv{j}(1:3)]};
lrn(i,j) = size(cmaps{i},1);
end
end
end
% cycle through slices displaying images
nvox = prod(vdims(1:2));
pandims = [vdims([2 1]) 3]; % NB XY transpose for display
zimg = zeros(pandims);
for i = 1:nslices
ixyzmm = [x(:)';y(:)';ones(1,nvox)*zmm(i);ones(1,nvox)];
img = zimg;
for j = 1:npimgs
thisimg = obj.img(pictimgs(j));
i1 = sf_slice2panel(thisimg, ixyzmm, obj.transform, vdims);
% rescale to colormap
[csdata badvals]= pr_scaletocmap(...
i1,...
thisimg.range(1),...
thisimg.range(2),...
thisimg.cmap,...
lrn(j,:));
% take indices from colormap to make true colour image
iimg = reshape(cmaps{j}(csdata(:),:),pandims);
tmp = repmat(logical(~badvals),[1 1 3]);
if strcmpi(thisimg.type, 'truecolour')
img(tmp) = img(tmp) + iimg(tmp)*thisimg.prop;
else % split colormap effect
img(tmp) = iimg(tmp)*thisimg.prop;
end
end
% threshold out of range values
img(img>1) = 1;
image('Parent', axisd(i),...
'ButtonDownFcn', obj.callback,...
'CData',img);
% do contour plot
for j=1:length(contimgs)
thisimg = obj.img(contimgs(j));
i1 = sf_slice2panel(thisimg, ixyzmm, obj.transform, vdims);
if any(any(isfinite(i1)))
i1(i1<min(thisimg.range))=min(thisimg.range);
i1(i1>max(thisimg.range))=max(thisimg.range);
if ~any(diff(i1(isfinite(i1)))), continue, end % skip empty planes
if mars_struct('isthere', thisimg, 'linespec')
linespec = thisimg.linespec;
else
linespec = 'w-';
end
set(axisd(i),'NextPlot','add');
if mars_struct('isthere', thisimg, 'contours')
[c h] = contour(axisd(i), i1, thisimg.contours, linespec);
else
[c h] = contour(axisd(i), i1, linespec);
end
if ~isempty(h)
if ~mars_struct('isthere', thisimg, 'linespec')
% need to reset colours; contour assumes you just set the figure's
% colormap, but to overlay coloured contours on a greyscale image,
% one needs to have everything in truecolour, setting individual
% contour lines to their appropriate colour.
% (updated for MATLAB 7 and above)
convals = get(h, 'LevelList');
if ~isempty(convals)
csdata = pr_scaletocmap(...
convals,...
thisimg.range(1),...
thisimg.range(2),...
thisimg.cmap,...
[1 size(thisimg.cmap,1) 1]);
colvals = thisimg.cmap(csdata(:),:)*thisimg.prop;
for ch = get(h, 'Children')' % (NB: transpose needed to loop)
CData = get(ch, 'CData'); % (CData is constant with final NaN)
colval = colvals(find(convals == CData(1), 1), :);
set(ch, 'EdgeColor', colval)
end
end
end
if mars_struct('isthere', thisimg, 'linewidth')
set(h, 'LineWidth', thisimg.linewidth);
end
end
end
end
if do_labels
text('Parent',axisd(i),...
'Color', labels.colour,...
'FontUnits', 'normalized',...
'VerticalAlignment','bottom',...
'HorizontalAlignment','left',...
'Position', [1 1],...
'FontSize',labels.size,...
'ButtonDownFcn', obj.callback,...
'String', labels.format{i});
end
end
for i = (nslices+1):npanels
set(axisd(i),'Color',[0 0 0]);
end
% add colorbar(s)
for i = 1:cbars
axno = axisd(end-cbars+i);
cbari = obj.img(obj.cbar(i));
cml = size(cbari.cmap,1);
p = get(axno, 'Position'); % position of last axis
cw = p(3)*0.2;
ch = p(4)*0.75;
pc = p(3:4)/2;
[axlims idxs] = sort(cbari.range);
a=axes(...
'Parent',figno,...
'XTick',[],...
'XTickLabel',[],...
'Units', 'pixels',...
'YLim', axlims,...
'FontUnits', 'normalized',...
'FontSize', 0.075,...
'YColor',[1 1 1],...
'Tag', 'cbar',...
'Box', 'off',...
'Position',[p(1)+pc(1)-cw/2,p(2)+pc(2)-ch/2,cw,ch]...
);
image('Parent', a,...
'YData', axlims(idxs),...
'CData', reshape(cbari.cmap,[cml,1,3]));
end % colourbars
% Get stuff for figure, in case it dies later
obj.figure_struct = mars_struct('split', get(figno), fig_struct_fields);
return
% subfunctions
% ------------
function i1 = sf_slice2panel(img, xyzmm, transform, vdims)
% to voxel space of image
vixyz = (transform*img.vol.mat) \ xyzmm;
% raw data
if mars_struct('isthere', img.vol, 'imgdata')
V = img.vol.imgdata;
else
V = img.vol;
end
i1 = spm_sample_vol(V,vixyz(1,:),vixyz(2,:),vixyz(3,:), ...
[img.hold img.background]);
if mars_struct('isthere', img, 'func')
eval(img.func);
end
% transpose to reverse X and Y for figure
i1 = reshape(i1, vdims(1:2))';
return
|
github
|
philippboehmsturm/antx-master
|
pr_basic_ui.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/@slover/private/pr_basic_ui.m
| 3,679 |
utf_8
|
88d91189a824825f094d4979cbdc7fb4
|
function obj = pr_basic_ui(imgs, dispf)
% GUI to request parameters for slover routine
% FORMAT obj = pr_basic_ui(imgs, dispf)
%
% GUI requests choices while accepting many defaults
%
% imgs - string or cell array of image names to display
% (defaults to GUI select if no arguments passed)
% dispf - optional flag: if set, displays overlay (default = 1)
%
% $Id: pr_basic_ui.m,v 1.1 2005/04/20 15:05:00 matthewbrett Exp $
if nargin < 1
imgs = '';
end
if isempty(imgs)
imgs = spm_select(Inf, 'image', 'Image(s) to display');
end
if ischar(imgs)
imgs = cellstr(imgs);
end
if nargin < 2
dispf = 1;
end
spm_input('!SetNextPos', 1);
% load images
nimgs = size(imgs);
% process names
nchars = 20;
imgns = spm_str_manip(imgs, ['rck' num2str(nchars)]);
% Get new default object
obj = slover;
% identify image types
cscale = [];
deftype = 1;
obj.cbar = [];
for i = 1:nimgs
obj.img(i).vol = spm_vol(imgs{i});
options = {'Structural','Truecolour', ...
'Blobs','Negative blobs','Contours'};
% if there are SPM results in the workspace, add this option
[XYZ Z M] = pr_get_spm_results;
if ~isempty(XYZ)
options = {'Structural with SPM blobs', options{:}};
end
itype = spm_input(sprintf('Img %d: %s - image type?', i, imgns{i}), '+1', ...
'm', char(options),options, deftype);
imgns(i) = {sprintf('Img %d (%s)',i,itype{1})};
[mx mn] = slover('volmaxmin', obj.img(i).vol);
if ~isempty(strmatch('Structural', itype))
obj.img(i).type = 'truecolour';
obj.img(i).cmap = gray;
obj.img(i).range = [mn mx];
deftype = 2;
cscale = [cscale i];
if strcmp(itype,'Structural with SPM blobs')
obj = add_spm(obj);
end
else
cprompt = ['Colormap: ' imgns{i}];
switch itype{1}
case 'Truecolour'
obj.img(i).type = 'truecolour';
dcmap = 'flow.lut';
drange = [mn mx];
cscale = [cscale i];
obj.cbar = [obj.cbar i];
case 'Blobs'
obj.img(i).type = 'split';
dcmap = 'hot';
drange = [0 mx];
obj.img(i).prop = 1;
obj.cbar = [obj.cbar i];
case 'Negative blobs'
obj.img(i).type = 'split';
dcmap = 'winter';
drange = [0 mn];
obj.img(i).prop = 1;
obj.cbar = [obj.cbar i];
case 'Contours'
obj.img(i).type = 'contour';
dcmap = 'white';
drange = [mn mx];
obj.img(i).prop = 1;
end
obj.img(i).cmap = sf_return_cmap(cprompt, dcmap);
obj.img(i).range = spm_input('Img val range for colormap','+1', 'e', drange, 2);
end
end
ncmaps=length(cscale);
if ncmaps == 1
obj.img(cscale).prop = 1;
else
remcol=1;
for i = 1:ncmaps
ino = cscale(i);
obj.img(ino).prop = spm_input(sprintf('%s intensity',imgns{ino}),...
'+1', 'e', ...
remcol/(ncmaps-i+1),1);
remcol = remcol - obj.img(ino).prop;
end
end
obj.transform = deblank(spm_input('Image orientation', '+1', ['Axial|' ...
' Coronal|Sagittal'], strvcat('axial','coronal','sagittal'), ...
1));
% use SPM figure window
obj.figure = spm_figure('GetWin', 'Graphics');
% slices for display
obj = fill_defaults(obj);
slices = obj.slices;
obj.slices = spm_input('Slices to display (mm)', '+1', 'e', ...
sprintf('%0.0f:%0.0f:%0.0f',...
slices(1),...
mean(diff(slices)),...
slices(end))...
);
% and do the display
if dispf, obj = paint(obj); end
return
% Subfunctions
% ------------
function cmap = sf_return_cmap(prompt,defmapn)
cmap = [];
while isempty(cmap)
[cmap w]= slover('getcmap', spm_input(prompt,'+1','s', defmapn));
if isempty(cmap), disp(w);end
end
return
|
github
|
philippboehmsturm/antx-master
|
delete.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/@xmltree/delete.m
| 1,203 |
utf_8
|
f523d5fa52766f6af01c283da5bb87bf
|
function tree = delete(tree,uid)
% XMLTREE/DELETE Delete (delete a subtree given its UID)
%
% tree - XMLTree object
% uid - array of UID's of subtrees to be deleted
%_______________________________________________________________________
%
% Delete a subtree given its UID
% The tree parameter must be in input AND in output
%_______________________________________________________________________
% Copyright (C) 2002-2008 http://www.artefact.tk/
% Guillaume Flandin <[email protected]>
% $Id: delete.m 1460 2008-04-21 17:43:18Z guillaume $
error(nargchk(2,2,nargin));
uid = uid(:);
for i=1:length(uid)
if uid(i)==1
warning('[XMLTree] Cannot delete root element.');
else
p = tree.tree{uid(i)}.parent;
tree = sub_delete(tree,uid(i));
tree.tree{p}.contents(find(tree.tree{p}.contents==uid(i))) = [];
end
end
%=======================================================================
function tree = sub_delete(tree,uid)
if isfield(tree.tree{uid},'contents')
for i=1:length(tree.tree{uid}.contents)
tree = sub_delete(tree,tree.tree{uid}.contents(i));
end
end
tree.tree{uid} = struct('type','deleted');
|
github
|
philippboehmsturm/antx-master
|
save.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/@xmltree/save.m
| 5,121 |
utf_8
|
fa70739c5d89fa5e5759fe4d0dd5d1b3
|
function varargout = save(tree, filename)
% XMLTREE/SAVE Save an XML tree in an XML file
% FORMAT varargout = save(tree,filename)
%
% tree - XMLTree
% filename - XML output filename
% varargout - XML string
%_______________________________________________________________________
%
% Convert an XML tree into a well-formed XML string and write it into
% a file or return it as a string if no filename is provided.
%_______________________________________________________________________
% Copyright (C) 2002-2008 http://www.artefact.tk/
% Guillaume Flandin <[email protected]>
% $Id: save.m 4393 2011-07-18 14:52:32Z guillaume $
error(nargchk(1,2,nargin));
prolog = '<?xml version="1.0" ?>\n';
%- Return the XML tree as a string
if nargin == 1
varargout{1} = [sprintf(prolog) ...
print_subtree(tree,'',root(tree))];
%- Output specified
else
%- Filename provided
if ischar(filename)
[fid, msg] = fopen(filename,'w');
if fid==-1, error(msg); end
if isempty(tree.filename), tree.filename = filename; end
%- File identifier provided
elseif isnumeric(filename) && numel(filename) == 1
fid = filename;
prolog = ''; %- With this option, do not write any prolog
else
error('[XMLTree] Invalid argument.');
end
fprintf(fid,prolog);
save_subtree(tree,fid,root(tree));
if ischar(filename), fclose(fid); end
if nargout == 1
varargout{1} = print_subtree(tree,'',root(tree));
end
end
%=======================================================================
function xmlstr = print_subtree(tree,xmlstr,uid,order)
if nargin < 4, order = 0; end
xmlstr = [xmlstr blanks(3*order)];
switch tree.tree{uid}.type
case 'element'
xmlstr = sprintf('%s<%s',xmlstr,tree.tree{uid}.name);
for i=1:length(tree.tree{uid}.attributes)
xmlstr = sprintf('%s %s="%s"', xmlstr, ...
tree.tree{uid}.attributes{i}.key,...
tree.tree{uid}.attributes{i}.val);
end
if isempty(tree.tree{uid}.contents)
xmlstr = sprintf('%s/>\n',xmlstr);
else
xmlstr = sprintf('%s>\n',xmlstr);
for i=1:length(tree.tree{uid}.contents)
xmlstr = print_subtree(tree,xmlstr, ...
tree.tree{uid}.contents(i),order+1);
end
xmlstr = [xmlstr blanks(3*order)];
xmlstr = sprintf('%s</%s>\n',xmlstr,...
tree.tree{uid}.name);
end
case 'chardata'
xmlstr = sprintf('%s%s\n',xmlstr, ...
entity(tree.tree{uid}.value));
case 'cdata'
xmlstr = sprintf('%s<![CDATA[%s]]>\n',xmlstr, ...
tree.tree{uid}.value);
case 'pi'
xmlstr = sprintf('%s<?%s %s?>\n',xmlstr, ...
tree.tree{uid}.target, tree.tree{uid}.value);
case 'comment'
xmlstr = sprintf('%s<!-- %s -->\n',xmlstr,...
tree.tree{uid}.value);
otherwise
warning(sprintf('Type %s unknown: not saved', ...
tree.tree{uid}.type));
end
%=======================================================================
function save_subtree(tree,fid,uid,order)
if nargin < 4, order = 0; end
fprintf(fid,blanks(3*order));
switch tree.tree{uid}.type
case 'element'
fprintf(fid,'<%s',tree.tree{uid}.name);
for i=1:length(tree.tree{uid}.attributes)
fprintf(fid,' %s="%s"',...
tree.tree{uid}.attributes{i}.key, ...
tree.tree{uid}.attributes{i}.val);
end
if isempty(tree.tree{uid}.contents)
fprintf(fid,'/>\n');
else
fprintf(fid,'>\n');
for i=1:length(tree.tree{uid}.contents)
save_subtree(tree,fid,...
tree.tree{uid}.contents(i),order+1)
end
fprintf(fid,blanks(3*order));
fprintf(fid,'</%s>\n',tree.tree{uid}.name);
end
case 'chardata'
fprintf(fid,'%s\n',entity(tree.tree{uid}.value));
case 'cdata'
fprintf(fid,'<![CDATA[%s]]>\n',tree.tree{uid}.value);
case 'pi'
fprintf(fid,'<?%s %s?>\n',tree.tree{uid}.target, ...
tree.tree{uid}.value);
case 'comment'
fprintf(fid,'<!-- %s -->\n',tree.tree{uid}.value);
otherwise
warning(sprintf('[XMLTree] Type %s unknown: not saved', ...
tree.tree{uid}.type));
end
%=======================================================================
function str = entity(str)
% This has the side effect of strtrim'ming the char array.
str = char(strrep(cellstr(str), '&', '&' ));
str = char(strrep(cellstr(str), '<', '<' ));
str = char(strrep(cellstr(str), '>', '>' ));
str = char(strrep(cellstr(str), '"', '"'));
str = char(strrep(cellstr(str), '''', '''));
|
github
|
philippboehmsturm/antx-master
|
branch.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/@xmltree/branch.m
| 1,763 |
utf_8
|
f109760669fd1d0e0de8fc92a2a29e7d
|
function subtree = branch(tree,uid)
% XMLTREE/BRANCH Branch Method
% FORMAT uid = parent(tree,uid)
%
% tree - XMLTree object
% uid - UID of the root element of the subtree
% subtree - XMLTree object (a subtree from tree)
%_______________________________________________________________________
%
% Return a subtree from a tree.
%_______________________________________________________________________
% Copyright (C) 2002-2008 http://www.artefact.tk/
% Guillaume Flandin <[email protected]>
% $Id: branch.m 1460 2008-04-21 17:43:18Z guillaume $
error(nargchk(2,2,nargin));
if uid > length(tree) || ...
numel(uid)~=1 || ...
~strcmp(tree.tree{uid}.type,'element')
error('[XMLTree] Invalid UID.');
end
subtree = xmltree;
subtree = set(subtree,root(subtree),'name',tree.tree{uid}.name);
%- fix by Piotr Dollar to copy attributes for the root node:
subtree = set(subtree,root(subtree),'attributes',tree.tree{uid}.attributes);
child = children(tree,uid);
for i=1:length(child)
l = length(subtree);
subtree = sub_branch(tree,subtree,child(i),root(subtree));
subtree.tree{root(subtree)}.contents = [subtree.tree{root(subtree)}.contents l+1];
end
%=======================================================================
function tree = sub_branch(t,tree,uid,p)
l = length(tree);
tree.tree{l+1} = t.tree{uid};
tree.tree{l+1}.uid = l + 1;
tree.tree{l+1}.parent = p;
tree.tree{l+1}.contents = [];
if isfield(t.tree{uid},'contents')
contents = get(t,uid,'contents');
m = length(tree);
for i=1:length(contents)
tree.tree{l+1}.contents = [tree.tree{l+1}.contents m+1];
tree = sub_branch(t,tree,contents(i),l+1);
m = length(tree);
end
end
|
github
|
philippboehmsturm/antx-master
|
flush.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/@xmltree/flush.m
| 1,426 |
utf_8
|
fe4b3a9c9e324178be9b06001c9fec8f
|
function tree = flush(tree,uid)
% XMLTREE/FLUSH Flush (Clear a subtree given its UID)
%
% tree - XMLTree object
% uid - array of UID's of subtrees to be cleared
% Default is root
%_______________________________________________________________________
%
% Clear a subtree given its UID (remove all the leaves of the tree)
% The tree parameter must be in input AND in output
%_______________________________________________________________________
% Copyright (C) 2002-2008 http://www.artefact.tk/
% Guillaume Flandin <[email protected]>
% $Id: flush.m 1460 2008-04-21 17:43:18Z guillaume $
error(nargchk(1,2,nargin));
if nargin == 1,
uid = root(tree);
end
uid = uid(:);
for i=1:length(uid)
tree = sub_flush(tree,uid(i));
end
%=======================================================================
function tree = sub_flush(tree,uid)
if isfield(tree.tree{uid},'contents')
% contents is parsed in reverse order because each child is
% deleted and the contents vector is then eventually reduced
for i=length(tree.tree{uid}.contents):-1:1
tree = sub_flush(tree,tree.tree{uid}.contents(i));
end
end
if strcmp(tree.tree{uid}.type,'chardata') ||...
strcmp(tree.tree{uid}.type,'pi') ||...
strcmp(tree.tree{uid}.type,'cdata') ||...
strcmp(tree.tree{uid}.type,'comment')
tree = delete(tree,uid);
end
|
github
|
philippboehmsturm/antx-master
|
copy.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/@xmltree/copy.m
| 1,644 |
utf_8
|
8cbde6d7d6e761ad86ecb0379b54b269
|
function tree = copy(tree,subuid,uid)
% XMLTREE/COPY Copy Method (copy a subtree in another branch)
% FORMAT tree = copy(tree,subuid,uid)
%
% tree - XMLTree object
% subuid - UID of the subtree to copy
% uid - UID of the element where the subtree must be duplicated
%_______________________________________________________________________
%
% Copy a subtree to another branch
% The tree parameter must be in input AND in output
%_______________________________________________________________________
% Copyright (C) 2002-2008 http://www.artefact.tk/
% Guillaume Flandin <[email protected]>
% $Id: copy.m 1460 2008-04-21 17:43:18Z guillaume $
error(nargchk(2,3,nargin));
if nargin == 2
uid = parent(tree,subuid);
end
l = length(tree);
tree = sub_copy(tree,subuid,uid);
tree.tree{uid}.contents = [tree.tree{uid}.contents l+1];
% to have the copy next to the original and not at the end?
% contents = get(tree,parent,'contents');
% i = find(contents==uid);
% tree = set(tree,parent,'contents',[contents(1:i) l+1 contents(i+1:end)]);
%=======================================================================
function tree = sub_copy(tree,uid,p)
l = length(tree);
tree.tree{l+1} = tree.tree{uid};
tree.tree{l+1}.uid = l+1;
tree.tree{l+1}.parent = p;
tree.tree{l+1}.contents = [];
if isfield(tree.tree{uid},'contents')
contents = get(tree,uid,'contents');
m = length(tree);
for i=1:length(contents)
tree.tree{l+1}.contents = [tree.tree{l+1}.contents m+1];
tree = sub_copy(tree,contents(i),l+1);
m = length(tree);
end
end
|
github
|
philippboehmsturm/antx-master
|
convert.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/@xmltree/convert.m
| 5,612 |
utf_8
|
c2c0cfe54bad9ce85b1cccc7c53acfce
|
function s = convert(tree,uid)
% XMLTREE/CONVERT Converter an XML tree in a Matlab structure
%
% tree - XMLTree object
% uid - uid of the root of the subtree, if provided.
% Default is root
% s - converted structure
%_______________________________________________________________________
%
% Convert an xmltree into a Matlab structure, when possible.
% When several identical tags are present, a cell array is used.
% The root tag is not saved in the structure.
% If provided, only the structure corresponding to the subtree defined
% by the uid UID is returned.
%_______________________________________________________________________
% Copyright (C) 2002-2008 http://www.artefact.tk/
% Guillaume Flandin <[email protected]>
% $Id: convert.m 3756 2010-03-05 18:43:37Z guillaume $
% Exemple:
% tree: <toto><titi>field1</titi><tutu>field2</tutu><titi>field3</titi></toto>
% toto = convert(tree);
% <=> toto = struct('titi',{{'field1', 'field3'}},'tutu','field2')
error(nargchk(1,2,nargin));
% Get the root uid of the output structure
if nargin == 1
% Get the root uid of the XML tree
root_uid = root(tree);
else
% Uid provided by user
root_uid = uid;
end
% Initialize the output structure
% struct([]) should be used but this only works with Matlab 6
% So we create a field that we delete at the end
%s = struct(get(tree,root_uid,'name'),''); % struct([])
s = struct('deletedummy','');
%s = sub_convert(tree,s,root_uid,{get(tree,root_uid,'name')});
s = sub_convert(tree,s,root_uid,{});
s = rmfield(s,'deletedummy');
%=======================================================================
function s = sub_convert(tree,s,uid,arg)
type = get(tree,uid,'type');
switch type
case 'element'
child = children(tree,uid);
l = {};
ll = {};
for i=1:length(child)
if isfield(tree,child(i),'name')
ll = { ll{:}, get(tree,child(i),'name') };
end
end
for i=1:length(child)
if isfield(tree,child(i),'name')
name = get(tree,child(i),'name');
nboccur = sum(ismember(l,name));
nboccur2 = sum(ismember(ll,name));
l = { l{:}, name };
if nboccur || (nboccur2>1)
arg2 = { arg{:}, name, {nboccur+1} };
else
arg2 = { arg{:}, name};
end
else
arg2 = arg;
end
s = sub_convert(tree,s,child(i),arg2);
end
if isempty(child)
s = sub_setfield(s,arg{:},'');
end
%- saving attributes : does not work with <a t='q'>b</a>
%- but ok with <a t='q'><c>b</c></a>
% attrb = attributes(tree,'get',uid); %-
% if ~isempty(attrb) %-
% arg2 = {arg{:} 'attributes'}; %-
% s = sub_setfield(s,arg2{:},attrb); %-
% end %-
case 'chardata'
s = sub_setfield(s,arg{:},get(tree,uid,'value'));
%- convert strings into their Matlab equivalent when possible
%- e.g. string '3.14159' becomes double scalar 3.14159
% v = get(tree,uid,'value'); %-
% cv = str2num(v); %-
% if isempty(cv) %-
% s = sub_setfield(s,arg{:},v); %-
% else %-
% s = sub_setfield(s,arg{:},cv); %-
% end %-
case 'cdata'
s = sub_setfield(s,arg{:},get(tree,uid,'value'));
case 'pi'
% Processing instructions are evaluated if possible
app = get(tree,uid,'target');
switch app
case {'matlab',''}
s = sub_setfield(s,arg{:},eval(get(tree,uid,'value')));
case 'unix'
s = sub_setfield(s,arg{:},unix(get(tree,uid,'value')));
case 'dos'
s = sub_setfield(s,arg{:},dos(get(tree,uid,'value')));
case 'system'
s = sub_setfield(s,arg{:},system(get(tree,uid,'value')));
otherwise
try
s = sub_setfield(s,arg{:},feval(app,get(tree,uid,'value')));
catch
warning('[XMLTREE] Unknown target application');
end
end
case 'comment'
% Comments are forgotten
otherwise
warning(sprintf('Type %s unknown : not saved',get(tree,uid,'type')));
end
%=======================================================================
function s = sub_setfield(s,varargin)
% Same as setfield but using '{}' rather than '()'
%if (isempty(varargin) | length(varargin) < 2)
% error('Not enough input arguments.');
%end
subs = varargin(1:end-1);
for i = 1:length(varargin)-1
if (isa(varargin{i}, 'cell'))
types{i} = '{}';
elseif ischar(varargin{i})
types{i} = '.';
subs{i} = varargin{i}; %strrep(varargin{i},' ',''); % deblank field name
else
error('Inputs must be either cell arrays or strings.');
end
end
% Perform assignment
try
s = builtin('subsasgn', s, struct('type',types,'subs',subs), varargin{end});
catch
error(lasterr)
end
|
github
|
philippboehmsturm/antx-master
|
editor.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/@xmltree/editor.m
| 12,428 |
utf_8
|
6344af0067d2405a13d1dabf8e96efc3
|
function editor(tree)
%XMLTREE/EDITOR A Graphical User Interface for an XML tree
% EDITOR(TREE) opens a new Matlab figure displaying the xmltree
% object TREE.
% H = EDITOR(TREE) also returns the figure handle H.
%
% This is a beta version of <xmltree/view> successor
%
% See also XMLTREE
%_______________________________________________________________________
% Copyright (C) 2002-2008 http://www.artefact.tk/
% Guillaume Flandin <[email protected]>
% $Id: editor.m 1460 2008-04-21 17:43:18Z guillaume $
error(nargchk(1,1,nargin));
if ~isempty(getfilename(tree))
title = getfilename(tree);
elseif ~isempty(inputname(1))
title = ['Variable ''' inputname(1) ''''];
else
title = 'Untitled';
end
h = initWindow(title);
setappdata(h,'handles',guihandles(h));
setappdata(h,'save',0);
tree = set(tree,root(tree),'show',1);
setappdata(h,'tree',tree);
doUpdate([],[],h);
set(h,'HandleVisibility','callback');
%=======================================================================
function h = initWindow(title)
wincolor = struct('bg', [0.8 0.8 0.8], ...
'fg', [1.0 1.0 1.0], ...
'title', [0.9 0.9 0.9]);
title = [':: XMLTree Editor :: ' title];
h = figure('Name', title, ...
'Units', 'Points', ...
'NumberTitle', 'off', ...
'Resize', 'on', ...
'Color', wincolor.bg,...
'Position', [200 200 440 330], ...
'MenuBar', 'none', ...
'Tag', mfilename);
set(h, 'CloseRequestFcn', {@doClose,h});
%- Left box
uicontrol('Style', 'listbox', ...
'HorizontalAlignment','left', ...
'Units','Normalized', ...
'Visible','on',...
'BackgroundColor', wincolor.fg, ...
'Max', 1, ...
'Value', 1 , ...
'Enable', 'on', ...
'Position', [0.04 0.12 0.3 0.84], ...
'Callback', {@doList,h}, ...
'String', ' ', ...
'Tag', 'xmllistbox');
%- Right box
uicontrol('Style', 'list', ...
'HorizontalAlignment','left', ...
'Units','Normalized', ...
'Visible','on',...
'BackgroundColor', wincolor.bg, ...
'Min', 0, ...
'Max', 2, ...
'Value', [], ...
'Enable', 'inactive', ...
'Position', [0.38 0.50 0.58 0.46], ...
'Callback', '', ...
'String', ' ', ...
'Tag', 'xmllist');
%- The Add button
uicontrol('Style', 'pushbutton', ...
'Units', 'Normalized', ...
'Position', [0.04 0.03 0.11 0.06], ...
'String', 'Add', ...
'Enable','on',...
'Tag', 'addbutton', ...
'Callback', {@doAdd,h});
%- The Modify button
uicontrol('Style', 'pushbutton', ...
'Units', 'Normalized', ...
'Position', [0.175 0.03 0.11 0.06], ...
'String', 'Modify', ...
'Enable','on',...
'Tag', 'modifybutton', ...
'Callback', {@doModify,h});
%- The Copy button
uicontrol('Style', 'pushbutton', ...
'Units', 'Normalized', ...
'Position', [0.310 0.03 0.11 0.06], ...
'String', 'Copy', ...
'Enable','on',...
'Tag', 'copybutton', ...
'Callback', {@doCopy,h});
%- The Delete button
uicontrol('Style', 'pushbutton', ...
'Units', 'Normalized', ...
'Position', [0.445 0.03 0.11 0.06], ...
'String', 'Delete', ...
'Enable','on',...
'Tag', 'delbutton', ...
'Callback', {@doDelete,h});
%- The Save button
uicontrol('Style', 'pushbutton', ...
'Units', 'Normalized', ...
'Position', [0.580 0.03 0.11 0.06], ...
'String', 'Save', ...
'Tag', 'savebutton', ...
'Callback', {@doSave,h});
%- The Run button
%uicontrol('Style', 'pushbutton', ...
% 'Units', 'Normalized', ...
% 'Position', [0.715 0.03 0.11 0.06], ...
% 'String', 'Run', ...
% 'Enable', 'off', ...
% 'Tag', 'runbutton', ...
% 'Callback', {@doRun,h});
%- The Attributes button
uicontrol('Style', 'pushbutton', ...
'Units', 'Normalized', ...
'Position', [0.715 0.03 0.11 0.06], ...
'String', 'Attr.', ...
'Enable', 'on', ...
'Tag', 'runbutton', ...
'Callback', {@doAttributes,h});
%- The Close button
uicontrol('Style', 'pushbutton', ...
'Units', 'Normalized', ...
'Position', [0.850 0.03 0.11 0.06], ...
'String', 'Close', ...
'Tag', 'closebutton', ...
'Callback', {@doClose,h});
%=======================================================================
function doClose(fig,evd,h)
s = getappdata(h, 'save');
status = 1;
if s
button = questdlg(sprintf('Save changes to the XML tree?'),...
'XMLTree Editor','Yes','No','Cancel','Yes');
if strcmp(button,'Yes')
status = doSave([],[],h);
elseif strcmp(button,'Cancel')
status = 0;
end
end
if status
delete(h);
end
function doAdd(fig,evd,h)
tree = getappdata(h, 'tree');
uidList = getappdata(h, 'uidlist');
handles = getappdata(h, 'handles');
pos = get(handles.xmllistbox,'value');
uid = uidList(pos);
answer = questdlg('Which kind of item to add?', ...
'XMLTree Editor :: Add','Node','Leaf','Node');
switch answer
case 'Node'
tree = add(tree,uid,'element','New_Node');
case 'Leaf'
tree = add(tree,uid,'element','New_Leaf');
l = length(tree);
tree = add(tree,l,'chardata','default');
end
tree = set(tree,uid,'show',1);
setappdata(h, 'tree', tree);
setappdata(h, 'save', 1);
doUpdate([],[],h);
doList([],[],h);
function doModify(fig,evd,h)
tree = getappdata(h, 'tree');
uidList = getappdata(h, 'uidlist');
handles = getappdata(h, 'handles');
pos = get(handles.xmllistbox,'value');
uid = uidList(pos);
contents = children(tree,uid);
if length(contents) > 0 & ...
strcmp(get(tree,contents(1),'type'),'chardata')
str = get(tree,contents(1),'value');
prompt = {'Name :','New value:'};
def = {get(tree,uid,'name'),str};
title = sprintf('Modify %s',get(tree,uid,'name'));
lineNo = 1;
answer = inputdlg(prompt,title,lineNo,def);
if ~isempty(answer)
tree = set(tree,uid,'name',answer{1});
str = answer{2};
tree = set(tree,contents(1),'value',str);
setappdata(h, 'tree', tree);
setappdata(h, 'save', 1);
end
else
str = ['Tag ' get(tree,uid,'name')];
prompt = {'Name :'};
def = {get(tree,uid,'name'),str};
title = sprintf('Modify %s tag',get(tree,uid,'name'));
lineNo = 1;
answer = inputdlg(prompt,title,lineNo,def);
if ~isempty(answer)
tree = set(tree,uid,'name',answer{1});
str = ['Tag ' get(tree,uid,'name')];
setappdata(h, 'tree', tree);
setappdata(h, 'save', 1);
end
end
%- Trying to keep the slider active
set(handles.xmllist, 'Enable', 'on');
set(handles.xmllist, 'String', ' ');
set(handles.xmllist, 'Enable', 'Inactive');
set(handles.xmllist, 'String', str);
doUpdate([],[],h);
doList([],[],h);
function doCopy(fig,evd,h)
tree = getappdata(h, 'tree');
uidList = getappdata(h, 'uidlist');
handles = getappdata(h, 'handles');
pos = get(handles.xmllistbox,'value');
uid = uidList(pos);
if pos ~= 1
tree = copy(tree,uid);
setappdata(h, 'tree', tree);
setappdata(h, 'save', 1);
doUpdate([],[],h);
doList([],[],h);
end
function doDelete(fig,evd,h)
tree = getappdata(h, 'tree');
uidList = getappdata(h, 'uidlist');
handles = getappdata(h, 'handles');
pos = get(handles.xmllistbox,'value');
uid = uidList(pos);
if pos > 1
tree = delete(tree,uid);
set(handles.xmllistbox,'value',pos-1);
setappdata(h, 'save', 1);
end
setappdata(h, 'tree', tree);
doUpdate([],[],h);
doList([],[],h);
function status = doSave(fig,evd,h)
tree = getappdata(h, 'tree');
[filename, pathname] = uiputfile({'*.xml' 'XML file (*.xml)'}, ...
'Save XML file as');
status = ~(isequal(filename,0) | isequal(pathname,0));
if status
save(tree,fullfile(pathname, filename));
set(h,'Name',[':: XMLTree Editor :: ' filename]);
setappdata(h, 'save', 0);
end
function doRun(fig,evd,h)
warndlg('Not implemented','XMLTree :: Run');
function doAttributes(fig,evd,h)
tree = getappdata(h, 'tree');
uidList = getappdata(h, 'uidlist');
handles = getappdata(h, 'handles');
pos = get(handles.xmllistbox,'value');
uid = uidList(pos);
attr = attributes(tree,'get',uid);
if ~isempty(attr)
fprintf('This element has %d attributes.\n',length(attr));
%%%
%%% Do what you want with 'attr'
%%% to modify them, use:
%%% tree = attributes(tree,'set',uid,n,key,val)
%%% to add one, use:
%%% tree = attributes(tree,'add',uid,key,val)
%%% to delete one, use:
%%% tree = attributes(tree,'del',uid[,n]);
%%%
setappdata(h, 'tree', tree);
setappdata(h, 'save', 1); %- only if attributes have been modified
end
%=======================================================================
function doList(fig,evd,h)
tree = getappdata(h, 'tree');
uidList = getappdata(h, 'uidlist');
handles = getappdata(h, 'handles');
uid = uidList(get(handles.xmllistbox, 'value'));
%- Single mouse click
if strcmp(get(h,'SelectionType'),'normal')
contents = children(tree, uid);
if length(contents) > 0 & ...
strcmp(get(tree,contents(1),'type'),'chardata')
str = get(tree,contents(1),'value');
set(handles.addbutton,'Enable','off');
elseif length(contents) == 0
str = '';
tree = add(tree,uid,'chardata',str);
setappdata(h, 'tree', tree);
set(handles.addbutton,'Enable','off');
else
str = ['Tag ' get(tree,uid,'name')];
set(handles.addbutton,'Enable','on');
end
if get(handles.xmllistbox,'value') == 1
set(handles.copybutton,'Enable','off');
set(handles.delbutton,'Enable','off');
else
set(handles.copybutton,'Enable','on');
set(handles.delbutton,'Enable','on');
end
%- Trying to keep the slider active
set(handles.xmllist, 'Enable', 'on');
set(handles.xmllist, 'String', ' ');
set(handles.xmllist, 'Enable', 'Inactive');
set(handles.xmllist, 'String', str);
%- Double mouse click
else
tree = doFlip(tree, uid);
setappdata(h, 'tree', tree);
doUpdate([],[],h);
end
function doUpdate(fig,evd,h)
tree = getappdata(h, 'tree');
handles = getappdata(h, 'handles');
[batchString, uidList] = doUpdateR(tree);
set(handles.xmllistbox, 'String', batchString);
setappdata(h, 'uidlist', uidList);
%=======================================================================
function [batchString, uidList] = doUpdateR(tree, uid, o)
if nargin < 2, uid = root(tree); end
if nargin < 3 | o == 0
o = 0;
sep = ' ';
else
sep = blanks(4*o);
end
if attributes(tree,'length',uid) > 0
batchString = {[sep, get(tree, uid, 'name') ' *']};
else
batchString = {[sep, get(tree, uid, 'name')]};
end
uidList = [get(tree,uid,'uid')];
haselementchild = 0;
contents = get(tree, uid, 'contents');
if isfield(tree, uid, 'show') & get(tree, uid, 'show') == 1
for i=1:length(contents)
if strcmp(get(tree,contents(i),'type'),'element')
[subbatchString, subuidList] = doUpdateR(tree,contents(i),o+1);
batchString = {batchString{:} subbatchString{:}};
uidList = [uidList subuidList];
haselementchild = 1;
end
end
if haselementchild == 1, batchString{1}(length(sep)) = '-'; end
else
for i=1:length(contents)
if strcmp(get(tree,contents(i),'type'),'element')
haselementchild = 1;
end
end
if haselementchild == 1, batchString{1}(length(sep)) = '+'; end
end
function tree = doFlip(tree, uid)
if isfield(tree,uid,'show')
show = get(tree,uid,'show');
else
show = 0;
end
tree = set(tree,uid,'show',~show);
|
github
|
philippboehmsturm/antx-master
|
find.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/@xmltree/find.m
| 5,904 |
utf_8
|
f06a6b831a6222020bfa34df1176ccaa
|
function list = find(varargin)
% XMLTREE/FIND Find elements in a tree with specified characteristics
% FORMAT list = find(varargin)
%
% tree - XMLTree object
% xpath - string path with specific grammar (XPath)
% uid - lists of root uid's
% parameter/value - pair of pattern
% list - list of uid's of matched elements
%
% list = find(tree,xpath)
% list = find(tree,parameter,value[,parameter,value])
% list = find(tree,uid,parameter,value[,parameter,value])
%
% Grammar for addressing parts of an XML document:
% XML Path Language XPath (http://www.w3.org/TR/xpath)
% Example: /element1//element2[1]/element3[5]/element4
%_______________________________________________________________________
%
% Find elements in an XML tree with specified characteristics or given
% a path (using a subset of XPath language).
%_______________________________________________________________________
% Copyright (C) 2002-2008 http://www.artefact.tk/
% Guillaume Flandin <[email protected]>
% $Id: find.m 3934 2010-06-17 14:58:25Z guillaume $
% TODO:
% - clean up subroutines
% - find should only be documented using XPath (other use is internal)
% - handle '*', 'last()' in [] and '@'
% - if a key is invalid, should rather return [] than error ?
if nargin==0
error('[XMLTree] A tree must be provided');
elseif nargin==1
list = 1:length(tree.tree);
return
elseif mod(nargin,2)
list = sub_find_subtree1(varargin{1}.tree,root(varargin{1}),varargin{2:end});
elseif isa(varargin{2},'double') && ...
ndims(varargin{2}) == 2 && ...
min(size(varargin{2})) == 1
list = unique(sub_find_subtree1(varargin{1}.tree,varargin{2:end}));
elseif nargin==2 && ischar(varargin{2})
list = sub_pathfinder(varargin{:});
else
error('[XMLTree] Arguments must be parameter/value pairs.');
end
%=======================================================================
function list = sub_find_subtree1(varargin)
list = [];
for i=1:length(varargin{2})
res = sub_find_subtree2(varargin{1},...
varargin{2}(i),varargin{3:end});
list = [list res];
end
%=======================================================================
function list = sub_find_subtree2(varargin)
uid = varargin{2};
list = [];
if sub_comp_element(varargin{1}{uid},varargin{3:end})
list = [list varargin{1}{uid}.uid];
end
if isfield(varargin{1}{uid},'contents')
list = [list sub_find_subtree1(varargin{1},...
varargin{1}{uid}.contents,varargin{3:end})];
end
%=======================================================================
function match = sub_comp_element(varargin)
match = 0;
try
% v = getfield(varargin{1}, varargin{2}); % slow...
for i=1:floor(nargin/2)
v = subsref(varargin{1}, struct('type','.','subs',varargin{i+1}));
if strcmp(v,varargin{i+2})
match = 1;
end
end
catch
end
% More powerful but much slower
%match = 0;
%for i=1:length(floor(nargin/2)) % bug: remove length !!!
% if isfield(varargin{1},varargin{i+1})
% if ischar(getfield(varargin{1},varargin{i+1})) & ischar(varargin{i+2})
% if strcmp(getfield(varargin{1},varargin{i+1}),char(varargin{i+2}))
% match = 1;
% end
% elseif isa(getfield(varargin{1},varargin{i+1}),'double') & ...
% isa(varargin{i+2},'double')
% if getfield(varargin{1},varargin{i+1}) == varargin{i+2}
% match = 1;
% end
% else
% warning('Cannot compare different objects');
% end
% end
%end
%=======================================================================
function list = sub_pathfinder(tree,pth)
%- Search for the delimiter '/' in the path
i = strfind(pth,'/');
%- Begin search by root
list = root(tree);
%- Walk through the tree
j = 1;
while j <= length(i)
%- Look for recursion '//'
if j<length(i) && i(j+1)==i(j)+1
recursive = 1;
j = j + 1;
else
recursive = 0;
end
%- Catch the current tag 'element[x]'
if j ~= length(i)
element = pth(i(j)+1:i(j+1)-1);
else
element = pth(i(j)+1:end);
end
%- Search for [] brackets
k = xml_findstr(element,'[',1,1);
%- If brackets are present in current element
if ~isempty(k)
l = xml_findstr(element,']',1,1);
val = str2num(element(k+1:l-1));
element = element(1:k-1);
end
%- Use recursivity
if recursive
list = find(tree,list,'name',element);
%- Just look at children
else
if i(j)==1 % if '/root/...' (list = root(tree) in that case)
if sub_comp_element(tree.tree{list},'name',element)
% list = 1; % list still contains root(tree)
else
list = [];
return;
end
else
list = sub_findchild(tree,list,element);
end
end
% If an element is specified using a key
if ~isempty(k)
if val < 1 || val > length(list)+1
error('[XMLTree] Bad key in the path.');
elseif val == length(list)+1
list = [];
return;
end
list = list(val);
end
if isempty(list), return; end
j = j + 1;
end
%=======================================================================
function list = sub_findchild(tree,listt,elmt)
list = [];
for a=1:length(listt)
for b=1:length(tree.tree{listt(a)}.contents)
if sub_comp_element(tree.tree{tree.tree{listt(a)}.contents(b)},'name',elmt)
list = [list tree.tree{tree.tree{listt(a)}.contents(b)}.uid];
end
end
end
|
github
|
philippboehmsturm/antx-master
|
xml_parser.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/@xmltree/private/xml_parser.m
| 16,122 |
utf_8
|
e9c0fb44fd5c086cab09c4df5a6e0087
|
function tree = xml_parser(xmlstr)
% XML (eXtensible Markup Language) Processor
% FORMAT tree = xml_parser(xmlstr)
%
% xmlstr - XML string to parse
% tree - tree structure corresponding to the XML file
%_______________________________________________________________________
%
% xml_parser.m is an XML 1.0 (http://www.w3.org/TR/REC-xml) parser
% written in Matlab. It aims to be fully conforming. It is currently not
% a validating XML processor.
%
% A description of the tree structure provided in output is detailed in
% the header of this m-file.
%_______________________________________________________________________
% Copyright (C) 2002-2008 http://www.artefact.tk/
% Guillaume Flandin <[email protected]>
% $Id: xml_parser.m 4013 2010-07-22 17:12:45Z guillaume $
% XML Processor for MATLAB (The Mathworks, Inc.).
% Copyright (C) 2002-2008 Guillaume Flandin <[email protected]>
%
% This program is free software; you can redistribute it and/or
% modify it under the terms of the GNU General Public License
% as published by the Free Software Foundation; either version 2
% of the License, or any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation Inc, 59 Temple Pl. - Suite 330, Boston, MA 02111-1307, USA.
%-----------------------------------------------------------------------
% Suggestions for improvement and fixes are always welcome, although no
% guarantee is made whether and when they will be implemented.
% Send requests to <[email protected]>
% Check also the latest developments on the following webpage:
% <http://www.artefact.tk/software/matlab/xml/>
%-----------------------------------------------------------------------
% The implementation of this XML parser is much inspired from a
% Javascript parser available at <http://www.jeremie.com/>
% A mex-file xml_findstr.c is also required, to encompass some
% limitations of the built-in findstr Matlab function.
% Compile it on your architecture using 'mex -O xml_findstr.c' command
% if the compiled version for your system is not provided.
% If this function behaves badly (crash or wrong results), comment the
% line '#define __HACK_MXCHAR__' in xml_findstr.c and compile it again.
%-----------------------------------------------------------------------
% Structure of the output tree:
% There are 5 types of nodes in an XML file: element, chardata, cdata,
% pi and comment.
% Each of them contains an UID (Unique Identifier): an integer between
% 1 and the number of nodes of the XML file.
%
% element (a tag <name key="value"> [contents] </name>
% |_ type: 'element'
% |_ name: string
% |_ attributes: cell array of struct 'key' and 'value' or []
% |_ contents: double array of uid's or [] if empty
% |_ parent: uid of the parent ([] if root)
% |_ uid: double
%
% chardata (a character array)
% |_ type: 'chardata'
% |_ value: string
% |_ parent: uid of the parent
% |_ uid: double
%
% cdata (a litteral string <![CDATA[value]]>)
% |_ type: 'cdata'
% |_ value: string
% |_ parent: uid of the parent
% |_ uid: double
%
% pi (a processing instruction <?target value ?>)
% |_ type: 'pi'
% |_ target: string (may be empty)
% |_ value: string
% |_ parent: uid of the parent
% |_ uid: double
%
% comment (a comment <!-- value -->)
% |_ type: 'comment'
% |_ value: string
% |_ parent: uid of the parent
% |_ uid: double
%
%-----------------------------------------------------------------------
% TODO/BUG/FEATURES:
% - [compile] only a warning if TagStart is empty ?
% - [attribution] should look for " and ' rather than only "
% - [main] with normalize as a preprocessing, CDATA are modified
% - [prolog] look for a DOCTYPE in the whole string even if it occurs
% only in a far CDATA tag, bug even if the doctype is inside a comment
% - [tag_element] erode should replace normalize here
% - remove globals? uppercase globals rather persistent (clear mfile)?
% - xml_findstr is indeed xml_strfind according to Mathworks vocabulary
% - problem with entities: do we need to convert them here? (é)
%-----------------------------------------------------------------------
%- XML string to parse and number of tags read
global xmlstring Xparse_count xtree;
%- Check input arguments
error(nargchk(1,1,nargin));
if isempty(xmlstr)
error('[XML] Not enough parameters.')
elseif ~ischar(xmlstr) || sum(size(xmlstr)>1)>1
error('[XML] Input must be a string.')
end
%- Initialize number of tags (<=> uid)
Xparse_count = 0;
%- Remove prolog and white space characters from the XML string
xmlstring = normalize(prolog(xmlstr));
%- Initialize the XML tree
xtree = {};
tree = fragment;
tree.str = 1;
tree.parent = 0;
%- Parse the XML string
tree = compile(tree);
%- Return the XML tree
tree = xtree;
%- Remove global variables from the workspace
clear global xmlstring Xparse_count xtree;
%=======================================================================
% SUBFUNCTIONS
%-----------------------------------------------------------------------
function frag = compile(frag)
global xmlstring xtree Xparse_count;
while 1,
if length(xmlstring)<=frag.str || ...
(frag.str == length(xmlstring)-1 && strcmp(xmlstring(frag.str:end),' '))
return
end
TagStart = xml_findstr(xmlstring,'<',frag.str,1);
if isempty(TagStart)
%- Character data
error('[XML] Unknown data at the end of the XML file.');
xtree{Xparse_count} = chardata;
xtree{Xparse_count}.value = erode(entity(xmlstring(frag.str:end)));
xtree{Xparse_count}.parent = frag.parent;
xtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count];
frag.str = '';
elseif TagStart > frag.str
if strcmp(xmlstring(frag.str:TagStart-1),' ')
%- A single white space before a tag (ignore)
frag.str = TagStart;
else
%- Character data
xtree{Xparse_count} = chardata;
xtree{Xparse_count}.value = erode(entity(xmlstring(frag.str:TagStart-1)));
xtree{Xparse_count}.parent = frag.parent;
xtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count];
frag.str = TagStart;
end
else
if strcmp(xmlstring(frag.str+1),'?')
%- Processing instruction
frag = tag_pi(frag);
else
if length(xmlstring)-frag.str>4 && strcmp(xmlstring(frag.str+1:frag.str+3),'!--')
%- Comment
frag = tag_comment(frag);
else
if length(xmlstring)-frag.str>9 && strcmp(xmlstring(frag.str+1:frag.str+8),'![CDATA[')
%- Litteral data
frag = tag_cdata(frag);
else
%- A tag element (empty (<.../>) or not)
if ~isempty(frag.end)
endmk = ['/' frag.end '>'];
else
endmk = '/>';
end
if strcmp(xmlstring(frag.str+1:frag.str+length(frag.end)+2),endmk) || ...
strcmp(strip(xmlstring(frag.str+1:frag.str+length(frag.end)+2)),endmk)
frag.str = frag.str + length(frag.end)+3;
return
else
frag = tag_element(frag);
end
end
end
end
end
end
%-----------------------------------------------------------------------
function frag = tag_element(frag)
global xmlstring xtree Xparse_count;
close = xml_findstr(xmlstring,'>',frag.str,1);
if isempty(close)
error('[XML] Tag < opened but not closed.');
else
empty = strcmp(xmlstring(close-1:close),'/>');
if empty
close = close - 1;
end
starttag = normalize(xmlstring(frag.str+1:close-1));
nextspace = xml_findstr(starttag,' ',1,1);
attribs = '';
if isempty(nextspace)
name = starttag;
else
name = starttag(1:nextspace-1);
attribs = starttag(nextspace+1:end);
end
xtree{Xparse_count} = element;
xtree{Xparse_count}.name = strip(name);
if frag.parent
xtree{Xparse_count}.parent = frag.parent;
xtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count];
end
if ~isempty(attribs)
xtree{Xparse_count}.attributes = attribution(attribs);
end
if ~empty
contents = fragment;
contents.str = close+1;
contents.end = name;
contents.parent = Xparse_count;
contents = compile(contents);
frag.str = contents.str;
else
frag.str = close+2;
end
end
%-----------------------------------------------------------------------
function frag = tag_pi(frag)
global xmlstring xtree Xparse_count;
close = xml_findstr(xmlstring,'?>',frag.str,1);
if isempty(close)
warning('[XML] Tag <? opened but not closed.')
else
nextspace = xml_findstr(xmlstring,' ',frag.str,1);
xtree{Xparse_count} = pri;
if nextspace > close || nextspace == frag.str+2
xtree{Xparse_count}.value = erode(xmlstring(frag.str+2:close-1));
else
xtree{Xparse_count}.value = erode(xmlstring(nextspace+1:close-1));
xtree{Xparse_count}.target = erode(xmlstring(frag.str+2:nextspace));
end
if frag.parent
xtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count];
xtree{Xparse_count}.parent = frag.parent;
end
frag.str = close+2;
end
%-----------------------------------------------------------------------
function frag = tag_comment(frag)
global xmlstring xtree Xparse_count;
close = xml_findstr(xmlstring,'-->',frag.str,1);
if isempty(close)
warning('[XML] Tag <!-- opened but not closed.')
else
xtree{Xparse_count} = comment;
xtree{Xparse_count}.value = erode(xmlstring(frag.str+4:close-1));
if frag.parent
xtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count];
xtree{Xparse_count}.parent = frag.parent;
end
frag.str = close+3;
end
%-----------------------------------------------------------------------
function frag = tag_cdata(frag)
global xmlstring xtree Xparse_count;
close = xml_findstr(xmlstring,']]>',frag.str,1);
if isempty(close)
warning('[XML] Tag <![CDATA[ opened but not closed.')
else
xtree{Xparse_count} = cdata;
xtree{Xparse_count}.value = xmlstring(frag.str+9:close-1);
if frag.parent
xtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count];
xtree{Xparse_count}.parent = frag.parent;
end
frag.str = close+3;
end
%-----------------------------------------------------------------------
function all = attribution(str)
%- Initialize attributs
nbattr = 0;
all = cell(nbattr);
%- Look for 'key="value"' substrings
while 1,
eq = xml_findstr(str,'=',1,1);
if isempty(str) || isempty(eq), return; end
id = sort([xml_findstr(str,'"',1,1),xml_findstr(str,'''',1,1)]); id=id(1);
nextid = sort([xml_findstr(str,'"',id+1,1),xml_findstr(str,'''',id+1,1)]);nextid=nextid(1);
nbattr = nbattr + 1;
all{nbattr}.key = strip(str(1:(eq-1)));
all{nbattr}.val = entity(str((id+1):(nextid-1)));
str = str((nextid+1):end);
end
%-----------------------------------------------------------------------
function elm = element
global Xparse_count;
Xparse_count = Xparse_count + 1;
elm = struct('type','element','name','','attributes',[],'contents',[],'parent',[],'uid',Xparse_count);
%-----------------------------------------------------------------------
function cdat = chardata
global Xparse_count;
Xparse_count = Xparse_count + 1;
cdat = struct('type','chardata','value','','parent',[],'uid',Xparse_count);
%-----------------------------------------------------------------------
function cdat = cdata
global Xparse_count;
Xparse_count = Xparse_count + 1;
cdat = struct('type','cdata','value','','parent',[],'uid',Xparse_count);
%-----------------------------------------------------------------------
function proce = pri
global Xparse_count;
Xparse_count = Xparse_count + 1;
proce = struct('type','pi','value','','target','','parent',[],'uid',Xparse_count);
%-----------------------------------------------------------------------
function commt = comment
global Xparse_count;
Xparse_count = Xparse_count + 1;
commt = struct('type','comment','value','','parent',[],'uid',Xparse_count);
%-----------------------------------------------------------------------
function frg = fragment
frg = struct('str','','parent','','end','');
%-----------------------------------------------------------------------
function str = prolog(str)
%- Initialize beginning index of elements tree
b = 1;
%- Initial tag
start = xml_findstr(str,'<',1,1);
if isempty(start)
error('[XML] No tag found.')
end
%- Header (<?xml version="1.0" ... ?>)
if strcmpi(str(start:start+2),'<?x')
close = xml_findstr(str,'?>',1,1);
if ~isempty(close)
b = close + 2;
else
warning('[XML] Header tag incomplete.')
end
end
%- Doctype (<!DOCTYPE type ... [ declarations ]>)
start = xml_findstr(str,'<!DOCTYPE',b,1); % length('<!DOCTYPE') = 9
if ~isempty(start)
close = xml_findstr(str,'>',start+9,1);
if ~isempty(close)
b = close + 1;
dp = xml_findstr(str,'[',start+9,1);
if (~isempty(dp) && dp < b)
k = xml_findstr(str,']>',start+9,1);
if ~isempty(k)
b = k + 2;
else
warning('[XML] Tag [ in DOCTYPE opened but not closed.')
end
end
else
warning('[XML] Tag DOCTYPE opened but not closed.')
end
end
%- Skip prolog from the xml string
str = str(b:end);
%-----------------------------------------------------------------------
function str = strip(str)
a = isspace(str);
a = find(a==1);
str(a) = '';
%-----------------------------------------------------------------------
function str = normalize(str)
% Find white characters (space, newline, carriage return, tabs, ...)
i = isspace(str);
i = find(i == 1);
str(i) = ' ';
% replace several white characters by only one
if ~isempty(i)
j = i - [i(2:end) i(end)];
k = find(j == -1);
str(i(k)) = [];
end
%-----------------------------------------------------------------------
function str = entity(str)
str = strrep(str,'<','<');
str = strrep(str,'>','>');
str = strrep(str,'"','"');
str = strrep(str,''','''');
str = strrep(str,'&','&');
%-----------------------------------------------------------------------
function str = erode(str)
if ~isempty(str) && str(1)==' ', str(1)=''; end;
if ~isempty(str) && str(end)==' ', str(end)=''; end;
|
github
|
philippboehmsturm/antx-master
|
save.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/@gifti/save.m
| 20,878 |
utf_8
|
9dda5745b44a50e7b47d1885c7e30435
|
function save(this,filename,encoding)
% Save GIfTI object in a GIfTI format file
% FORMAT save(this,filename)
% this - GIfTI object
% filename - name of GIfTI file to be created [Default: 'untitled.gii']
% encoding - optional argument to specify encoding format, among
% ASCII, Base64Binary, GZipBase64Binary, ExternalFileBinary,
% Collada (.dae), IDTF (.idtf). [Default: 'GZipBase64Binary']
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Guillaume Flandin
% $Id: save.m 4613 2012-01-08 12:04:11Z guillaume $
% Check filename and file format
%--------------------------------------------------------------------------
ext = '.gii';
if nargin == 1
filename = 'untitled.gii';
else
if nargin == 3 && strcmpi(encoding,'collada')
ext = '.dae';
end
if nargin == 3 && strcmpi(encoding,'idtf')
ext = '.idtf';
end
[p,f,e] = fileparts(filename);
if ~ismember(lower(e),{ext})
e = ext;
end
filename = fullfile(p,[f e]);
end
% Open file for writing
%--------------------------------------------------------------------------
fid = fopen(filename,'wt');
if fid == -1
error('Unable to write file %s: permission denied.',filename);
end
% Write file
%--------------------------------------------------------------------------
switch ext
case '.gii'
if nargin < 3, encoding = 'GZipBase64Binary'; end
fid = save_gii(fid,this,encoding);
case '.dae'
fid = save_dae(fid,this);
case '.idtf'
fid = save_idtf(fid,this);
otherwise
error('Unknown file format.');
end
% Close file
%--------------------------------------------------------------------------
fclose(fid);
%==========================================================================
% function fid = save_gii(fid,this,encoding)
%==========================================================================
function fid = save_gii(fid,this,encoding)
% Defaults for DataArray's attributes
%--------------------------------------------------------------------------
[unused,unused,mach] = fopen(fid);
if strncmp('ieee-be',mach,7)
def.Endian = 'BigEndian';
elseif strncmp('ieee-le',mach,7)
def.Endian = 'LittleEndian';
else
error('[GIFTI] Unknown byte order "%s".',mach);
end
def.Encoding = encoding;
def.Intent = 'NIFTI_INTENT_NONE';
def.DataType = 'NIFTI_TYPE_FLOAT32';
def.ExternalFileName = '';
def.ExternalFileOffset = '';
def.offset = 0;
% Edit object DataArray attributes
%--------------------------------------------------------------------------
for i=1:length(this.data)
% Revert the dimension storage
d = this.data{i}.attributes.Dim;
this.data{i}.attributes = rmfield(this.data{i}.attributes,'Dim');
this.data{i}.attributes.Dimensionality = num2str(length(d));
for j=1:length(d)
this.data{i}.attributes.(sprintf('Dim%d',j-1)) = num2str(d(j));
end
% Enforce some conventions
this.data{i}.attributes.ArrayIndexingOrder = 'ColumnMajorOrder';
if ~isfield(this.data{i}.attributes,'DataType') || ...
isempty(this.data{i}.attributes.DataType)
warning('DataType set to default: %s', def.DataType);
this.data{i}.attributes.DataType = def.DataType;
end
if ~isfield(this.data{i}.attributes,'Intent') || ...
isempty(this.data{i}.attributes.Intent)
warning('Intent code set to default: %s', def.Intent);
this.data{i}.attributes.Intent = def.Intent;
end
this.data{i}.attributes.Encoding = def.Encoding;
this.data{i}.attributes.Endian = def.Endian;
this.data{i}.attributes.ExternalFileName = def.ExternalFileName;
this.data{i}.attributes.ExternalFileOffset = def.ExternalFileOffset;
switch this.data{i}.attributes.Encoding
case {'ASCII', 'Base64Binary','GZipBase64Binary' }
case 'ExternalFileBinary'
extfilename = this.data{i}.attributes.ExternalFileName;
if isempty(extfilename)
[p,f] = fileparts(fopen(fid));
extfilename = [f '.dat'];
end
[p,f,e] = fileparts(extfilename);
this.data{i}.attributes.ExternalFileName = fullfile(fileparts(fopen(fid)),[f e]);
this.data{i}.attributes.ExternalFileOffset = num2str(def.offset);
otherwise
error('[GIFTI] Unknown data encoding: %s.',this.data{i}.attributes.Encoding);
end
end
% Prolog
%--------------------------------------------------------------------------
fprintf(fid,'<?xml version="1.0" encoding="UTF-8"?>\n');
fprintf(fid,'<!DOCTYPE GIFTI SYSTEM "http://www.nitrc.org/frs/download.php/115/gifti.dtd">\n');
fprintf(fid,'<GIFTI Version="1.0" NumberOfDataArrays="%d">\n',numel(this.data));
o = @(x) blanks(x*3);
% MetaData
%--------------------------------------------------------------------------
fprintf(fid,'%s<MetaData',o(1));
if isempty(this.metadata)
fprintf(fid,'/>\n');
else
fprintf(fid,'>\n');
for i=1:length(this.metadata)
fprintf(fid,'%s<MD>\n',o(2));
fprintf(fid,'%s<Name><![CDATA[%s]]></Name>\n',o(3),...
this.metadata(i).name);
fprintf(fid,'%s<Value><![CDATA[%s]]></Value>\n',o(3),...
this.metadata(i).value);
fprintf(fid,'%s</MD>\n',o(2));
end
fprintf(fid,'%s</MetaData>\n',o(1));
end
% LabelTable
%--------------------------------------------------------------------------
fprintf(fid,'%s<LabelTable',o(1));
if isempty(this.label)
fprintf(fid,'/>\n');
else
fprintf(fid,'>\n');
for i=1:length(this.label.name)
if ~all(isnan(this.label.rgba(i,:)))
label_rgba = sprintf(' Red="%f" Green="%f" Blue="%f" Alpha="%f"',...
this.label.rgba(i,:));
else
label_rgba = '';
end
fprintf(fid,'%s<Label Key="%d"%s><![CDATA[%s]]></Label>\n',o(2),...
this.label.key(i), label_rgba, this.label.name{i});
end
fprintf(fid,'%s</LabelTable>\n',o(1));
end
% DataArray
%--------------------------------------------------------------------------
for i=1:length(this.data)
fprintf(fid,'%s<DataArray',o(1));
if def.offset
this.data{i}.attributes.ExternalFileOffset = num2str(def.offset);
end
fn = sort(fieldnames(this.data{i}.attributes));
oo = repmat({o(5) '\n'},length(fn),1); oo{1} = ' '; oo{end} = '';
for j=1:length(fn)
if strcmp(fn{j},'ExternalFileName')
[p,f,e] = fileparts(this.data{i}.attributes.(fn{j}));
attval = [f e];
else
attval = this.data{i}.attributes.(fn{j});
end
fprintf(fid,'%s%s="%s"%s',oo{j,1},...
fn{j},attval,sprintf(oo{j,2}));
end
fprintf(fid,'>\n');
% MetaData
%----------------------------------------------------------------------
fprintf(fid,'%s<MetaData>\n',o(2));
for j=1:length(this.data{i}.metadata)
fprintf(fid,'%s<MD>\n',o(3));
fprintf(fid,'%s<Name><![CDATA[%s]]></Name>\n',o(4),...
this.data{i}.metadata(j).name);
fprintf(fid,'%s<Value><![CDATA[%s]]></Value>\n',o(4),...
this.data{i}.metadata(j).value);
fprintf(fid,'%s</MD>\n',o(3));
end
fprintf(fid,'%s</MetaData>\n',o(2));
% CoordinateSystemTransformMatrix
%----------------------------------------------------------------------
for j=1:length(this.data{i}.space)
fprintf(fid,'%s<CoordinateSystemTransformMatrix>\n',o(2));
fprintf(fid,'%s<DataSpace><![CDATA[%s]]></DataSpace>\n',o(3),...
this.data{i}.space(j).DataSpace);
fprintf(fid,'%s<TransformedSpace><![CDATA[%s]]></TransformedSpace>\n',o(3),...
this.data{i}.space(j).TransformedSpace);
fprintf(fid,'%s<MatrixData>%s</MatrixData>\n',o(3),...
sprintf('%f ',this.data{i}.space(j).MatrixData));
fprintf(fid,'%s</CoordinateSystemTransformMatrix>\n',o(2));
end
% Data (saved using MATLAB's ColumnMajorOrder)
%----------------------------------------------------------------------
fprintf(fid,'%s<Data>',o(2));
tp = getdict;
try
tp = tp.(this.data{i}.attributes.DataType);
catch
error('[GIFTI] Unknown DataType.');
end
switch this.data{i}.attributes.Encoding
case 'ASCII'
fprintf(fid, [tp.format ' '], this.data{i}.data);
case 'Base64Binary'
fprintf(fid,base64encode(typecast(this.data{i}.data(:),'uint8')));
% uses native machine format
case 'GZipBase64Binary'
fprintf(fid,base64encode(dzip(typecast(this.data{i}.data(:),'uint8'))));
% uses native machine format
case 'ExternalFileBinary'
extfilename = this.data{i}.attributes.ExternalFileName;
dat = this.data{i}.data;
if isa(dat,'file_array')
dat = subsref(dat,substruct('()',repmat({':'},1,numel(dat.dim))));
end
if ~def.offset
fide = fopen(extfilename,'w'); % uses native machine format
else
fide = fopen(extfilename,'a'); % uses native machine format
end
if fide == -1
error('Unable to write file %s: permission denied.',extfilename);
end
fseek(fide,0,1);
fwrite(fide,dat,tp.class);
def.offset = ftell(fide);
fclose(fide);
otherwise
error('[GIFTI] Unknown data encoding.');
end
fprintf(fid,'</Data>\n');
fprintf(fid,'%s</DataArray>\n',o(1));
end
fprintf(fid,'</GIFTI>\n');
%==========================================================================
% function fid = save_dae(fid,this)
%==========================================================================
function fid = save_dae(fid,this)
o = inline('blanks(x*3)');
% Split the mesh into connected components
%--------------------------------------------------------------------------
s = struct(this);
try
C = spm_mesh_label(s.faces);
d = [];
for i=1:numel(unique(C))
d(i).faces = s.faces(C==i,:);
u = unique(d(i).faces);
d(i).vertices = s.vertices(u,:);
a = 1:max(d(i).faces(:));
a(u) = 1:size(d(i).vertices,1);
%a = sparse(1,double(u),1:1:size(d(i).vertices,1));
d(i).faces = a(d(i).faces);
end
s = d;
end
% Prolog & root of the Collada XML file
%--------------------------------------------------------------------------
fprintf(fid,'<?xml version="1.0"?>\n');
fprintf(fid,'<COLLADA xmlns="http://www.collada.org/2008/03/COLLADASchema" version="1.5.0">\n');
% Assets
%--------------------------------------------------------------------------
fprintf(fid,'%s<asset>\n',o(1));
fprintf(fid,'%s<contributor>\n',o(2));
fprintf(fid,'%s<author_website>%s</author_website>\n',o(3),...
'http://www.fil.ion.ucl.ac.uk/spm/');
fprintf(fid,'%s<authoring_tool>%s</authoring_tool>\n',o(3),spm('Ver'));
fprintf(fid,'%s</contributor>\n',o(2));
fprintf(fid,'%s<created>%s</created>\n',o(2),datestr(now,'yyyy-mm-ddTHH:MM:SSZ'));
fprintf(fid,'%s<modified>%s</modified>\n',o(2),datestr(now,'yyyy-mm-ddTHH:MM:SSZ'));
fprintf(fid,'%s<unit name="millimeter" meter="0.001"/>\n',o(2));
fprintf(fid,'%s<up_axis>Z_UP</up_axis>\n',o(2));
fprintf(fid,'%s</asset>\n',o(1));
% Image, Materials, Effects
%--------------------------------------------------------------------------
%fprintf(fid,'%s<library_images/>\n',o(1));
fprintf(fid,'%s<library_materials>\n',o(1));
for i=1:numel(s)
fprintf(fid,'%s<material id="material%d" name="material%d">\n',o(2),i,i);
fprintf(fid,'%s<instance_effect url="#material%d-effect"/>\n',o(3),i);
fprintf(fid,'%s</material>\n',o(2));
end
fprintf(fid,'%s</library_materials>\n',o(1));
fprintf(fid,'%s<library_effects>\n',o(1));
for i=1:numel(s)
fprintf(fid,'%s<effect id="material%d-effect" name="material%d-effect">\n',o(2),i,i);
fprintf(fid,'%s<profile_COMMON>\n',o(3));
fprintf(fid,'%s<technique sid="COMMON">\n',o(4));
fprintf(fid,'%s<lambert>\n',o(5));
fprintf(fid,'%s<emission>\n',o(6));
fprintf(fid,'%s<color>%f %f %f %d</color>\n',o(7),[0 0 0 1]);
fprintf(fid,'%s</emission>\n',o(6));
fprintf(fid,'%s<ambient>\n',o(6));
fprintf(fid,'%s<color>%f %f %f %d</color>\n',o(7),[0 0 0 1]);
fprintf(fid,'%s</ambient>\n',o(6));
fprintf(fid,'%s<diffuse>\n',o(6));
fprintf(fid,'%s<color>%f %f %f %d</color>\n',o(7),[0.5 0.5 0.5 1]);
fprintf(fid,'%s</diffuse>\n',o(6));
fprintf(fid,'%s<transparent>\n',o(6));
fprintf(fid,'%s<color>%d %d %d %d</color>\n',o(7),[1 1 1 1]);
fprintf(fid,'%s</transparent>\n',o(6));
fprintf(fid,'%s<transparency>\n',o(6));
fprintf(fid,'%s<float>%f</float>\n',o(7),0);
fprintf(fid,'%s</transparency>\n',o(6));
fprintf(fid,'%s</lambert>\n',o(5));
fprintf(fid,'%s</technique>\n',o(4));
fprintf(fid,'%s</profile_COMMON>\n',o(3));
fprintf(fid,'%s</effect>\n',o(2));
end
fprintf(fid,'%s</library_effects>\n',o(1));
% Geometry
%--------------------------------------------------------------------------
fprintf(fid,'%s<library_geometries>\n',o(1));
for i=1:numel(s)
fprintf(fid,'%s<geometry id="shape%d" name="shape%d">\n',o(2),i,i);
fprintf(fid,'%s<mesh>\n',o(3));
fprintf(fid,'%s<source id="shape%d-positions">\n',o(4),i);
fprintf(fid,'%s<float_array id="shape%d-positions-array" count="%d">',o(5),i,numel(s(i).vertices));
fprintf(fid,'%f ',repmat(s(i).vertices',1,[]));
fprintf(fid,'</float_array>\n');
fprintf(fid,'%s<technique_common>\n',o(5));
fprintf(fid,'%s<accessor count="%d" offset="0" source="#shape%d-positions-array" stride="3">\n',o(6),size(s(i).vertices,1),i);
fprintf(fid,'%s<param name="X" type="float" />\n',o(7));
fprintf(fid,'%s<param name="Y" type="float" />\n',o(7));
fprintf(fid,'%s<param name="Z" type="float" />\n',o(7));
fprintf(fid,'%s</accessor>\n',o(6));
fprintf(fid,'%s</technique_common>\n',o(5));
fprintf(fid,'%s</source>\n',o(4));
fprintf(fid,'%s<vertices id="shape%d-vertices">\n',o(4),i);
fprintf(fid,'%s<input semantic="POSITION" source="#shape%d-positions"/>\n',o(5),i);
fprintf(fid,'%s</vertices>\n',o(4));
fprintf(fid,'%s<triangles material="material%d" count="%d">\n',o(4),i,size(s(i).faces,1));
fprintf(fid,'%s<input semantic="VERTEX" source="#shape%d-vertices" offset="0"/>\n',o(5),i);
fprintf(fid,'%s<p>',o(5));
fprintf(fid,'%d ',repmat(s(i).faces',1,[])-1);
fprintf(fid,'</p>\n');
fprintf(fid,'%s</triangles>\n',o(4));
fprintf(fid,'%s</mesh>\n',o(3));
fprintf(fid,'%s</geometry>\n',o(2));
end
fprintf(fid,'%s</library_geometries>\n',o(1));
% Scene
%--------------------------------------------------------------------------
fprintf(fid,'%s<library_visual_scenes>\n',o(1));
fprintf(fid,'%s<visual_scene id="VisualSceneNode" name="SceneNode">\n',o(2));
for i=1:numel(s)
fprintf(fid,'%s<node id="node%d">\n',o(3),i);
fprintf(fid,'%s<instance_geometry url="#shape%d">\n',o(4),i);
fprintf(fid,'%s<bind_material>\n',o(5));
fprintf(fid,'%s<technique_common>\n',o(6));
fprintf(fid,'%s<instance_material symbol="material%d" target="#material%d"/>\n',o(7),i,i);
fprintf(fid,'%s</technique_common>\n',o(6));
fprintf(fid,'%s</bind_material>\n',o(5));
fprintf(fid,'%s</instance_geometry>\n',o(4));
fprintf(fid,'%s</node>\n',o(3));
end
fprintf(fid,'%s</visual_scene>\n',o(2));
fprintf(fid,'%s</library_visual_scenes>\n',o(1));
fprintf(fid,'%s<scene>\n',o(1));
fprintf(fid,'%s<instance_visual_scene url="#VisualSceneNode" />\n',o(2));
fprintf(fid,'%s</scene>\n',o(1));
% End of XML
%--------------------------------------------------------------------------
fprintf(fid,'</COLLADA>\n');
%==========================================================================
% function fid = save_idtf(fid,this)
%==========================================================================
function fid = save_idtf(fid,this)
o = inline('blanks(x*3)');
s = struct(this);
% Compute normals
%--------------------------------------------------------------------------
if ~isfield(s,'normals')
try
s.normals = spm_mesh_normals(...
struct('vertices',s.vertices,'faces',s.faces),true);
catch
s.normals = [];
end
end
% Split the mesh into connected components
%--------------------------------------------------------------------------
try
C = spm_mesh_label(s.faces);
d = [];
try
if size(s.cdata,2) == 1 && (any(s.cdata>1) || any(s.cdata<0))
mi = min(s.cdata); ma = max(s.cdata);
s.cdata = (s.cdata-mi)/ (ma-mi);
else
end
end
for i=1:numel(unique(C))
d(i).faces = s.faces(C==i,:);
u = unique(d(i).faces);
d(i).vertices = s.vertices(u,:);
d(i).normals = s.normals(u,:);
a = 1:max(d(i).faces(:));
a(u) = 1:size(d(i).vertices,1);
%a = sparse(1,double(u),1:1:size(d(i).vertices,1));
d(i).faces = a(d(i).faces);
d(i).mat = s.mat;
try
d(i).cdata = s.cdata(u,:);
if size(d(i).cdata,2) == 1
d(i).cdata = repmat(d(i).cdata,1,3);
end
end
end
s = d;
end
% FILE_HEADER
%--------------------------------------------------------------------------
fprintf(fid,'FILE_FORMAT "IDTF"\n');
fprintf(fid,'FORMAT_VERSION 100\n\n');
% NODES
%--------------------------------------------------------------------------
for i=1:numel(s)
fprintf(fid,'NODE "MODEL" {\n');
fprintf(fid,'%sNODE_NAME "%s"\n',o(1),sprintf('Mesh%04d',i));
fprintf(fid,'%sPARENT_LIST {\n',o(1));
fprintf(fid,'%sPARENT_COUNT %d\n',o(2),1);
fprintf(fid,'%sPARENT %d {\n',o(2),0);
fprintf(fid,'%sPARENT_NAME "%s"\n',o(3),'<NULL>');
fprintf(fid,'%sPARENT_TM {\n',o(3));
I = s(i).mat; % eye(4);
for j=1:size(I,2)
fprintf(fid,'%s',o(4)); fprintf(fid,'%f ',I(:,j)'); fprintf(fid,'\n');
end
fprintf(fid,'%s}\n',o(3));
fprintf(fid,'%s}\n',o(2));
fprintf(fid,'%s}\n',o(1));
fprintf(fid,'%sRESOURCE_NAME "%s"\n',o(1),sprintf('Mesh%04d',i));
%fprintf(fid,'%sMODEL_VISIBILITY "BOTH"\n',o(1));
fprintf(fid,'}\n\n');
end
% NODE_RESOURCES
%--------------------------------------------------------------------------
for i=1:numel(s)
fprintf(fid,'RESOURCE_LIST "MODEL" {\n');
fprintf(fid,'%sRESOURCE_COUNT %d\n',o(1),1);
fprintf(fid,'%sRESOURCE %d {\n',o(1),0);
fprintf(fid,'%sRESOURCE_NAME "%s"\n',o(2),sprintf('Mesh%04d',i));
fprintf(fid,'%sMODEL_TYPE "MESH"\n',o(2));
fprintf(fid,'%sMESH {\n',o(2));
fprintf(fid,'%sFACE_COUNT %d\n',o(3),size(s(i).faces,1));
fprintf(fid,'%sMODEL_POSITION_COUNT %d\n',o(3),size(s(i).vertices,1));
fprintf(fid,'%sMODEL_NORMAL_COUNT %d\n',o(3),size(s(i).normals,1));
if ~isfield(s(i),'cdata') || isempty(s(i).cdata)
c = 0;
else
c = size(s(i).cdata,1);
end
fprintf(fid,'%sMODEL_DIFFUSE_COLOR_COUNT %d\n',o(3),c);
fprintf(fid,'%sMODEL_SPECULAR_COLOR_COUNT %d\n',o(3),0);
fprintf(fid,'%sMODEL_TEXTURE_COORD_COUNT %d\n',o(3),0);
fprintf(fid,'%sMODEL_BONE_COUNT %d\n',o(3),0);
fprintf(fid,'%sMODEL_SHADING_COUNT %d\n',o(3),1);
fprintf(fid,'%sMODEL_SHADING_DESCRIPTION_LIST {\n',o(3));
fprintf(fid,'%sSHADING_DESCRIPTION %d {\n',o(4),0);
fprintf(fid,'%sTEXTURE_LAYER_COUNT %d\n',o(5),0);
fprintf(fid,'%sSHADER_ID %d\n',o(5),0);
fprintf(fid,'%s}\n',o(4));
fprintf(fid,'%s}\n',o(3));
fprintf(fid,'%sMESH_FACE_POSITION_LIST {\n',o(3));
fprintf(fid,'%d %d %d\n',s(i).faces'-1);
fprintf(fid,'%s}\n',o(3));
fprintf(fid,'%sMESH_FACE_NORMAL_LIST {\n',o(3));
fprintf(fid,'%d %d %d\n',s(i).faces'-1);
fprintf(fid,'%s}\n',o(3));
fprintf(fid,'%sMESH_FACE_SHADING_LIST {\n',o(3));
fprintf(fid,'%d\n',zeros(size(s(i).faces,1),1));
fprintf(fid,'%s}\n',o(3));
if c
fprintf(fid,'%sMESH_FACE_DIFFUSE_COLOR_LIST {\n',o(3));
fprintf(fid,'%d %d %d\n',s(i).faces'-1);
fprintf(fid,'%s}\n',o(3));
end
fprintf(fid,'%sMODEL_POSITION_LIST {\n',o(3));
fprintf(fid,'%f %f %f\n',s(i).vertices');
fprintf(fid,'%s}\n',o(3));
fprintf(fid,'%sMODEL_NORMAL_LIST {\n',o(3));
fprintf(fid,'%f %f %f\n',s(i).normals');
fprintf(fid,'%s}\n',o(3));
if c
fprintf(fid,'%sMODEL_DIFFUSE_COLOR_LIST {\n',o(3));
fprintf(fid,'%f %f %f\n',s(i).cdata');
fprintf(fid,'%s}\n',o(3));
end
fprintf(fid,'%s}\n',o(2));
fprintf(fid,'%s}\n',o(1));
fprintf(fid,'}\n');
end
|
github
|
philippboehmsturm/antx-master
|
gifti.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/@gifti/gifti.m
| 3,622 |
utf_8
|
770f3ed1f17658bff49edbacd0062416
|
function this = gifti(varargin)
% GIfTI Geometry file format class
% Geometry format under the Neuroimaging Informatics Technology Initiative
% (NIfTI):
% http://www.nitrc.org/projects/gifti/
% http://nifti.nimh.nih.gov/
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Guillaume Flandin
% $Id: gifti.m 3999 2010-07-19 10:54:18Z guillaume $
switch nargin
case 0
this = giftistruct;
this = class(this,'gifti');
case 1
if isa(varargin{1},'gifti')
this = varargin{1};
elseif isstruct(varargin{1})
f = {'faces', 'face', 'tri' 'vertices', 'vert', 'pnt', 'cdata'};
ff = {'faces', 'faces', 'faces', 'vertices', 'vertices', 'vertices', 'cdata'};
[c, ia] = intersect(f,fieldnames(varargin{1}));
if ~isempty(c)
this = gifti;
for i=1:length(c)
this = subsasgn(this,...
struct('type','.','subs',ff{ia(i)}),...
varargin{1}.(c{i}));
end
elseif isempty(setxor(fieldnames(varargin{1}),...
{'metadata','label','data'}))
this = class(varargin{1},'gifti');
else
error('[GIFTI] Invalid structure.');
end
elseif ishandle(varargin{1})
this = struct('vertices',get(varargin{1},'Vertices'), ...
'faces', get(varargin{1},'Faces'));
if ~isempty(get(varargin{1},'FaceVertexCData'));
this.cdata = get(varargin{1},'FaceVertexCData');
end
this = gifti(this);
elseif isnumeric(varargin{1})
this = gifti;
this = subsasgn(this,...
struct('type','.','subs','cdata'),...
varargin{1});
elseif ischar(varargin{1})
if size(varargin{1},1)>1
this = gifti(cellstr(varargin{1}));
return;
end
[p,n,e] = fileparts(varargin{1});
if strcmpi(e,'.mat')
try
this = gifti(load(varargin{1}));
catch
error('[GIFTI] Loading of file %s failed.', varargin{1});
end
else
this = read_gifti_file(varargin{1},giftistruct);
this = class(this,'gifti');
end
elseif iscellstr(varargin{1})
fnames = varargin{1};
this(numel(fnames)) = giftistruct;
this = class(this,'gifti');
for i=1:numel(fnames)
this(i) = gifti(fnames{i});
end
else
error('[GIFTI] Invalid object construction.');
end
otherwise
error('[GIFTI] Invalid object construction.');
end
%==========================================================================
function s = giftistruct
s = struct(...
'metadata', ...
struct(...
'name', {}, ...
'value', {} ...
), ...
'label', ...
struct(...
'name', {}, ...
'index', {} ...
), ...
'data', ...
struct(...
'attributes', {}, ...
'metadata', struct('name',{}, 'value',{}), ...
'space', {}, ...
'data', {} ...
) ...
);
|
github
|
philippboehmsturm/antx-master
|
read_gifti_file.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/@gifti/private/read_gifti_file.m
| 6,672 |
utf_8
|
6b1ffd0854407b6710a55c2345f19d7e
|
function this = read_gifti_file(filename, this)
% Low level reader of GIfTI 1.0 files
% FORMAT this = read_gifti_file(filename, this)
% filename - XML GIfTI filename
% this - structure with fields 'metaData', 'label' and 'data'.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Guillaume Flandin
% $Id: read_gifti_file.m 4613 2012-01-08 12:04:11Z guillaume $
% Import XML-based GIfTI file
%--------------------------------------------------------------------------
try
t = xmltree(filename);
catch
error('[GIFTI] Loading of XML file %s failed.', filename);
end
% Root element of a GIFTI file
%--------------------------------------------------------------------------
if ~strcmp(get(t,root(t),'name'),'GIFTI')
error('[GIFTI] %s is not a GIFTI 1.0 file.', filename);
end
attr = cell2mat(attributes(t,'get',root(t)));
attr = cell2struct({attr.val},strrep({attr.key},':','___'),2);
if ~all(ismember({'Version','NumberOfDataArrays'},fieldnames(attr)))
error('[GIFTI] Missing mandatory attributes for GIFTI root element.');
end
if str2double(attr.Version) ~= 1
warning('[GIFTI] Unknown specification version of GIFTI file (%s).',attr.Version);
end
nbData = str2double(attr.NumberOfDataArrays);
% Read children elements
%--------------------------------------------------------------------------
uid = children(t,root(t));
for i=1:length(uid)
switch get(t,uid(i),'name')
case 'MetaData'
this.metadata = gifti_MetaData(t,uid(i));
case 'LabelTable'
this.label = gifti_LabelTable(t,uid(i));
case 'DataArray'
this.data{end+1} = gifti_DataArray(t,uid(i),filename);
otherwise
warning('[GIFTI] Unknown element "%s": ignored.',get(t,uid(i),'name'));
end
end
if nbData ~= length(this.data)
warning('[GIFTI] Mismatch between expected and effective number of datasets.');
end
%==========================================================================
function s = gifti_MetaData(t,uid)
s = struct('name',{}, 'value',{});
c = children(t,uid);
for i=1:length(c)
for j=children(t,c(i))
s(i).(lower(get(t,j,'name'))) = get(t,children(t,j),'value');
end
end
%==========================================================================
function s = gifti_LabelTable(t,uid)
s = struct('name',{}, 'key',[], 'rgba',[]);
c = children(t,uid);
for i=1:length(c)
a = attributes(t,'get',c(i));
s(1).rgba(i,1:4) = NaN;
for j=1:numel(a)
switch lower(a{j}.key)
case {'key','index'}
s(1).key(i) = str2double(a{j}.val);
case 'red'
s(1).rgba(i,1) = str2double(a{j}.val);
case 'green'
s(1).rgba(i,2) = str2double(a{j}.val);
case 'blue'
s(1).rgba(i,3) = str2double(a{j}.val);
case 'alpha'
s(1).rgba(i,4) = str2double(a{j}.val);
otherwise
end
end
s(1).name{i} = get(t,children(t,c(i)),'value');
end
%==========================================================================
function s = gifti_DataArray(t,uid,filename)
s = struct(...
'attributes', {}, ...
'data', {}, ...
'metadata', struct([]), ...
'space', {} ...
);
attr = cell2mat(attributes(t,'get',uid));
s(1).attributes = cell2struct({attr.val},{attr.key},2);
s(1).attributes.Dim = [];
for i=1:str2double(s(1).attributes.Dimensionality)
f = sprintf('Dim%d',i-1);
s(1).attributes.Dim(i) = str2double(s(1).attributes.(f));
s(1).attributes = rmfield(s(1).attributes,f);
end
s(1).attributes = rmfield(s(1).attributes,'Dimensionality');
if isfield(s(1).attributes,'ExternalFileName') && ...
~isempty(s(1).attributes.ExternalFileName)
s(1).attributes.ExternalFileName = fullfile(fileparts(filename),...
s(1).attributes.ExternalFileName);
end
c = children(t,uid);
for i=1:length(c)
switch get(t,c(i),'name')
case 'MetaData'
s(1).metadata = gifti_MetaData(t,c(i));
case 'CoordinateSystemTransformMatrix'
s(1).space(end+1) = gifti_Space(t,c(i));
case 'Data'
s(1).data = gifti_Data(t,c(i),s(1).attributes);
otherwise
error('[GIFTI] Unknown DataArray element "%s".',get(t,c(i),'name'));
end
end
%==========================================================================
function s = gifti_Space(t,uid)
s = struct('DataSpace','', 'TransformedSpace','', 'MatrixData',[]);
for i=children(t,uid)
s.(get(t,i,'name')) = get(t,children(t,i),'value');
end
s.MatrixData = reshape(str2num(s.MatrixData),4,4)';
%==========================================================================
function d = gifti_Data(t,uid,s)
tp = getdict;
try
tp = tp.(s.DataType);
catch
error('[GIFTI] Unknown DataType.');
end
[unused,unused,mach] = fopen(1);
sb = @deal; %inline('x');
try
if (strcmp(s.Endian,'LittleEndian') && ~isempty(strmatch('ieee-be',mach))) ...
|| (strcmp(s.Endian,'BigEndian') && ~isempty(strmatch('ieee-le',mach)))
sb = @swapbyte;
end
catch
% Byte Order can be absent if encoding is ASCII, assume native otherwise
end
switch s.Encoding
case 'ASCII'
d = sscanf(get(t,children(t,uid),'value'),tp.format);
case 'Base64Binary'
d = typecast(sb(base64decode(get(t,children(t,uid),'value'))), tp.cast);
case 'GZipBase64Binary'
d = typecast(dunzip(sb(base64decode(get(t,children(t,uid),'value')))), tp.cast);
case 'ExternalFileBinary'
[p,f,e] = fileparts(s.ExternalFileName);
if isempty(p)
s.ExternalFileName = fullfile(pwd,[f e]);
end
if true
fid = fopen(s.ExternalFileName,'r');
if fid == -1
error('[GIFTI] Unable to read binary file %s.',s.ExternalFileName);
end
fseek(fid,str2double(s.ExternalFileOffset),0);
d = sb(fread(fid,prod(s.Dim),['*' tp.class]));
fclose(fid);
else
d = file_array(s.ExternalFileName, s.Dim, tp.class, ...
str2double(s.ExternalFileOffset),1,0,'ro');
end
otherwise
error('[GIFTI] Unknown data encoding: %s.',s.Encoding);
end
if length(s.Dim) == 1, s.Dim(end+1) = 1; end
switch s.ArrayIndexingOrder
case 'RowMajorOrder'
d = permute(reshape(d,fliplr(s.Dim)),length(s.Dim):-1:1);
case 'ColumnMajorOrder'
d = reshape(d,s.Dim);
otherwise
error('[GIFTI] Unknown array indexing order.');
end
|
github
|
philippboehmsturm/antx-master
|
isintent.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/@gifti/private/isintent.m
| 2,094 |
utf_8
|
558a3aa4dffb45d067e660999e803050
|
function [a, b] = isintent(this,intent)
% Correspondance between fieldnames and NIfTI intents
% FORMAT ind = isintent(this,intent)
% this - GIfTI object
% intent - fieldnames
% a - indices of found intent(s)
% b - indices of dataarrays of found intent(s)
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Guillaume Flandin
% $Id: isintent.m 4717 2012-04-19 11:02:50Z guillaume $
a = [];
b = [];
if ischar(intent), intent = cellstr(intent); end
c = cdata;
for i=1:length(this(1).data)
switch this(1).data{i}.attributes.Intent(14:end)
case 'POINTSET'
[tf, loc] = ismember('vertices',intent);
if tf
a(end+1) = loc;
b(end+1) = i;
end
[tf, loc] = ismember('mat',intent);
if tf
a(end+1) = loc;
b(end+1) = i;
end
case 'TRIANGLE'
[tf, loc] = ismember('faces',intent);
if tf
a(end+1) = loc;
b(end+1) = i;
end
case 'VECTOR'
[tf, loc] = ismember('normals',intent);
if tf
a(end+1) = loc;
b(end+1) = i;
end
case {'NONE', 'LABEL', 'SHAPE', 'TIME_SERIES', 'RGB_VECTOR', ...
'RGBA_VECTOR' c{:}}
[tf, loc] = ismember('cdata',intent);
if tf
a(end+1) = loc;
b(end+1) = i;
end
otherwise
fprintf('Intent %s is ignored.\n',this.data{i}.attributes.Intent);
end
end
%[d,i] = unique(a);
%if length(d) < length(a)
% warning('Several fields match intent type. Using first.');
% a = a(i);
% b = b(i);
%end
function c = cdata
c = {
'CORREL'
'TTEST'
'FTEST'
'ZSCORE'
'CHISQ'
'BETA'
'BINOM'
'GAMMA'
'POISSON'
'NORMAL'
'FTEST_NONC'
'CHISQ_NONC'
'LOGISTIC'
'LAPLACE'
'UNIFORM'
'TTEST_NONC'
'WEIBULL'
'CHI'
'INVGAUSS'
'EXTVAL'
'PVAL'
'LOGPVAL'
'LOG10PVAL'
'ESTIMATE'
'LABEL'
'NEURONAMES'
};
|
github
|
philippboehmsturm/antx-master
|
mne_load_coil_def.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/mne/mne_load_coil_def.m
| 8,644 |
utf_8
|
772b6afb3be6c17199d073e9078d092f
|
function [CoilDef,Header] = mne_load_coil_def(fname);
%
%
% [CoilDef,Header] = mne_load_coil_def(fname);
% CoilDef = mne_load_coil_def(fname);
%
% If file name is not specified, the standard coil definition file
% $MNE_ROOT/setup/mne/coil_def.dat or $MNE_ROOT/share/mne/coil_def.dat is read
%
% The content of the coil definition file is described in
% section 5.6 of the MNE manual
%
% This routine is modified from the original BrainStorm routine
% created by John C. Mosher
%
%
% John C. Mosher
% Los Alamos National Laboratory
%
% Author : Matti Hamalainen, MGH Martinos Center
% License : BSD 3-clause
%
% Copyright (c) 2005 BrainStorm MMIV by the University of Southern California
% Principal Investigator:
% ** Professor Richard M. Leahy, USC Signal & Image Processing Institute
%
%
% Revision 1.5 2006/09/08 19:27:13 msh
% Added KIT coil type to mne_load_coil_def
% Allow reading of measurement info by specifying just a file name.
%
% Revision 1.4 2006/04/25 12:29:10 msh
% Added Magnes and CTF reference coil drawings.
%
% Revision 1.3 2006/04/23 15:29:40 msh
% Added MGH to the copyright
%
% Revision 1.2 2006/04/17 15:01:34 msh
% More small improvements.
%
% Revision 1.1 2006/04/17 11:52:15 msh
% Added coil definition stuff
%
%
me='MNE:mne_load_coil_def';
%% Setup the default inputs
if nargin == 0
fname = mne_file_name('setup/mne/coil_def.dat');
if ~exist(fname,'file')
fname = mne_file_name('share/mne/coil_def.dat');
if ~exist(fname,'file')
error(me,'The standard coil definition file was not found');
end
end
end
% Read in the coil_def information
%% Open, Read in entire file, close
fid = fopen(fname,'rt');
if fid < 0
error(me,'Could not open coil definition file %s',fname);
end
istr = 1; % string indexer
str_array = cell(1000,1); % preallocate
str_array{istr} = fgetl(fid); % get first string
while ischar(str_array{istr}),
istr = istr + 1;
str_array{istr} = fgetl(fid); % get next string
end
fclose(fid);
str_array = str_array(1:(istr-1)); % trim allocation
%% Read the Header, find the structure
% Gather the header lines
HeaderLines = strmatch('#',str_array); % lines that begin with a comment
% where are the structure lines
StructureLines = strmatch('# struct',str_array); % subset of header lines
% should be two
if length(StructureLines) ~= 2,
error(me,'%s anticipates two lines of structures',mfilename)
end
% with each structure line is a format line
FormatLines = strmatch('# format',str_array); % subset of header lines
% assume there are also two
FieldNames = cell(1,2);
Format = cell(1,2);
% first structure is the coil information
% won't actually use the second structure, just its format
for i = 1:2,
FieldNames{i} = strread(str_array{StructureLines(i)},'%s');
FieldNames{i}(1:2) = []; % strip the comment symbol and struct keyword
[ignore,Format{i}] = strtok(str_array{FormatLines(i)},'''');
Format{i} = strrep(Format{i},'''',''); % strip the single quotes
end
%% Allocate the arrays for loading
% interleave every fieldname with a null value
struct_arg = [FieldNames{1} cell(length(FieldNames{1}),1)]';
% each column an argument pair
% Preallocate a structure
[CoilDef(1:100)] = deal(struct(struct_arg{:}));
% Convert the rest of the string array to a structure
iCoil = 0; % counter
iLine = HeaderLines(end); % next line after header
while iLine < length(str_array), % number of lines in file
iCoil = iCoil + 1; % next coil definition
iLine = iLine + 1; % next line
% first read the integer information on the coil
% begin by breaking the line into two parts, numeric and description
[numeric_items, description] = strtok(str_array{iLine},'"');
temp = sscanf(numeric_items,Format{1}); % extra %s doesn't matter
% assign temp in the order of the fields
for i = 1:(length(FieldNames{1})-1),
CoilDef(iCoil).(FieldNames{1}{i}) = temp(i);
end
% then assign the description
% let's strip the quotes first
description = strrep(description,'"','');
CoilDef(iCoil).(FieldNames{1}{end}) = description;
% now read the coil definition
CoilDef(iCoil).coildefs = zeros(CoilDef(iCoil).num_points,7);
for i = 1:CoilDef(iCoil).num_points,
iLine = iLine + 1;
CoilDef(iCoil).coildefs(i,:) = sscanf(str_array{iLine},...
Format{2})';
end
% now draw it
% local subfunction below
CoilDef(iCoil).FV = draw_sensor(CoilDef(iCoil));
end
CoilDef = CoilDef(1:iCoil); % trim allocation
Header = str_array(HeaderLines);
function FV = draw_sensor(CoilDef);
% create a patch based on the sensor type
% The definitions as of 14 October 2005:
% for i = 1:3:length(CoilDef),fprintf('%d %s\n',CoilDef(i).id,CoilDef(i).description);end
% 2 Neuromag-122 planar gradiometer size = 27.89 mm base = 16.20 mm
% 2000 Point magnetometer
% 3012 Vectorview planar gradiometer T1 size = 26.39 mm base = 16.80 mm
% 3013 Vectorview planar gradiometer T2 size = 26.39 mm base = 16.80 mm
% 3022 Vectorview magnetometer T1 size = 25.80 mm
% 3023 Vectorview magnetometer T2 size = 25.80 mm
% 3024 Vectorview magnetometer T3 size = 21.00 mm
% 4001 Magnes WH2500 magnetometer size = 11.50 mm
% 4002 Magnes WH3600 gradiometer size = 18.00 mm base = 50.00 mm
% 5001 CTF axial gradiometer size = 18.00 mm base = 50.00 mm
FV = struct('faces',[],'vertices',[]); % standard convention
% recall that vertices are 1 per ROW, not column, of matrix
switch CoilDef.id
case {2,3012,3013,3011}
% square figure eight
% wound by right hand rule such that +x side is "up" (+z)
LongSide = CoilDef.size*1000; % length of long side in mm
Offset = 2.5; % mm offset of the center portion of planar grad coil
FV.vertices = [0 0 0; Offset 0 0; ...
Offset -LongSide/2 0; LongSide/2 -LongSide/2 0; ...
LongSide/2 LongSide/2 0; ...
Offset LongSide/2 0; Offset 0 0; ...
0 0 0; -Offset 0 0; -Offset -LongSide/2 0; ...
-LongSide/2 -LongSide/2 0; ...
-LongSide/2 LongSide/2 0; ...
-Offset LongSide/2 0; -Offset 0 0]/1000;
FV.faces = [1:length(FV.vertices)];
case 2000
% point source
LongSide = 2; % mm, tiny square
FV.vertices = [-1 1 0;1 1 0;1 -1 0; -1 -1 0]*LongSide/1000/2;
FV.faces = [1:length(FV.vertices)];
case {3022, 3023, 3024}
% square magnetometer
LongSide = CoilDef.size*1000; % mm, length of one side
FV.vertices = [-1 1 0;1 1 0;1 -1 0; -1 -1 0]*LongSide/1000/2;
FV.faces = [1:length(FV.vertices)];
case {4001,4003,5002}
% round magnetometer
Radius = CoilDef.size*1000/2; % mm, radius of coil
Len_cir = 15; % number of points for circle
circle = cos(2*pi*[0:(Len_cir-1)]/Len_cir) + ...
sqrt(-1)*sin(2*pi*[0:(Len_cir-1)]/Len_cir); % complex circle unit
FV.vertices = ...
[real(circle)' imag(circle)' zeros(Len_cir,1)]*Radius/1000;
FV.faces = [1:length(FV.vertices)];
case {4002, 5001, 5003, 4004, 6001}
% round coil 1st order gradiometer
Radius = CoilDef.size*1000/2; % mm radius
Baseline = CoilDef.baseline*1000; % axial separation
Len_cir = 15; % number of points for circle
% This time, go all the way around circle to close it fully
circle = cos(2*pi*[0:Len_cir]/Len_cir) + ...
sqrt(-1)*sin(2*pi*[0:Len_cir]/Len_cir); % complex circle unit
circle = circle*Radius; % scaled
FV.vertices = ...
[[real(circle)' imag(circle)' zeros(Len_cir+1,1)];... % first coil
[real(circle)' -imag(circle)' zeros(Len_cir+1,1)+Baseline]]/1000; % 2nd coil
FV.faces = [1:length(FV.vertices)];
case {5004,4005}
% round coil 1st order off-diagonal gradiometer
Radius = CoilDef.size*1000/2; % mm radius
Baseline = CoilDef.baseline*1000; % axial separation
Len_cir = 15; % number of points for circle
% This time, go all the way around circle to close it fully
circle = cos(2*pi*[0:Len_cir]/Len_cir) + ...
sqrt(-1)*sin(2*pi*[0:Len_cir]/Len_cir); % complex circle unit
circle = circle*Radius; % scaled
FV.vertices = ...
[[real(circle)'+Baseline/2.0 imag(circle)' zeros(Len_cir+1,1)];... % first coil
[real(circle)'-Baseline/2.0 -imag(circle)' zeros(Len_cir+1,1)]]/1000; % 2nd coil
FV.faces = [1:length(FV.vertices)];
otherwise
FV = [];
end
|
github
|
philippboehmsturm/antx-master
|
fiff_find_evoked.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/mne/fiff_find_evoked.m
| 2,846 |
utf_8
|
f7c5e4fd4395754f0e87d3fe6e984d62
|
function [data_sets] = fiff_find_evoked(fname)
%
% [data_sets] = fiff_find_evoked(fname)
%
% Find all evoked data sets in a fif file and create a list of descriptors
%
%
% Author : Matti Hamalainen, MGH Martinos Center
% License : BSD 3-clause
%
global FIFF;
if isempty(FIFF)
FIFF = fiff_define_constants();
end
me = 'MNE:fiff_find_evoked';
%
% Open the file
%
[ fid, tree ] = fiff_open(fname);
data_sets = struct('comment',{},'aspect_kind',{},'aspect_name',{});
%
% Find all evoked data sets
%
evoked = fiff_dir_tree_find(tree, FIFF.FIFFB_EVOKED);
if length(evoked) == 0
fclose(fid);
return
end
%
% Identify the aspects
%
naspect = 0;
for k = 1:length(evoked)
sets(k).aspects = fiff_dir_tree_find(evoked(k), FIFF.FIFFB_ASPECT);
sets(k).naspect = length(sets(k).aspects);
naspect = naspect + sets(k).naspect;
end
%
% Collect the desired information
%
count = 1;
for k = 1:length(evoked)
evoked_comment = find_tag(evoked(k), FIFF.FIFF_COMMENT);
for a = 1:sets(k).naspect
aspect_comment = find_tag(sets(k).aspects(a), FIFF.FIFF_COMMENT);
aspect_kind = find_tag(sets(k).aspects(a), FIFF.FIFF_ASPECT_KIND);
if ~isempty(aspect_comment)
data_sets(count).comment = aspect_comment.data;
elseif ~isempty(evoked_comment)
data_sets(count).comment = evoked_comment.data;
else
data_sets(count).comment = 'No comment';
end
if ~isempty(aspect_kind)
data_sets(count).aspect_kind = aspect_kind.data;
else
data_sets(count).aspect_kind = -1;
end
switch data_sets(count).aspect_kind
case FIFF.FIFFV_ASPECT_AVERAGE
data_sets(count).aspect_name = 'Average';
case FIFF.FIFFV_ASPECT_STD_ERR
data_sets(count).aspect_name = 'Standard error';
case FIFF.FIFFV_ASPECT_SINGLE
data_sets(count).aspect_name = 'Single';
case FIFF.FIFFV_ASPECT_SUBAVERAGE
data_sets(count).aspect_name = 'Subaverage';
case FIFF.FIFFV_ASPECT_ALTAVERAGE
data_sets(count).aspect_name = 'Alt. subaverage';
case FIFF.FIFFV_ASPECT_SAMPLE
data_sets(count).aspect_name = 'Sample';
case FIFF.FIFFV_ASPECT_POWER_DENSITY
data_sets(count).aspect_name = 'Power density spectrum';
case FIFF.FIFFV_ASPECT_DIPOLE_WAVE
data_sets(count).aspect_name = 'Dipole source waveform';
otherwise
data_sets(count).aspect_name = 'Unknown';
end
count = count + 1;
end
end
fclose(fid);
return
function [tag] = find_tag(node, findkind)
for p = 1:node.nent
kind = node.dir(p).kind;
pos = node.dir(p).pos;
if kind == findkind
tag = fiff_read_tag(fid, pos);
return
end
end
tag = [];
return
end
end
|
github
|
philippboehmsturm/antx-master
|
bemcp_example.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/bemcp/bemcp_example.m
| 21,651 |
utf_8
|
253b283a3e15ed5e68f2c888f37b65ff
|
function bemcp_example
% Simple function to test/demonstrate how the Boundary element functions are
% used in combination with Fildtrip/Forwinv routines.
%
% 1. A model is created as 3 concentric meshed spheres (using FT's
% icosahedron routines),
% 2. then random electrodes are placed on the upper part of the outer
% sphere.
% 3. the model is then "prepared" with 'ft_prepare_bemmodel', this bits
% takes most time as it requires LOTS of calculation.
% 4. sensors and volumes are plugged together by 'forwinv_prepare_vol_sens'
% 5. Finally the leadfiled for 3 orthogonal sources placed at one location
% is calculated with 'forwinv_compute_leadfield.m'
% 6. Display the 3 leadfields
%
% NOTE:
% this bit of code needs access to low level fieldtrip/forwinv routines
% which have been copy/pasted here under.
% Be aware that this way of programming is generally NOT advisable!
% I used it only to ensure a quick & dirty check of the BEM module...
% Christophe Phillips
% $Id: bemcp_example.m 2801 2009-02-27 17:26:22Z christophe $
% create volume conductor starting from unit sphere
[pnt, tri] = icosahedron162;
vol = [];
vol.cond = [1 1/80 1];
vol.source = 1; % index of source compartment
vol.skin = 3; % index of skin surface
% brain
vol.bnd(1).pnt = pnt*88;
vol.bnd(1).tri = tri;
% skull
vol.bnd(2).pnt = pnt*92;
vol.bnd(2).tri = tri;
% skin
vol.bnd(3).pnt = pnt*100;
vol.bnd(3).tri = tri;
% create the BEM system matrix
cfg = [];
cfg.method = 'bemcp';
vol1 = ft_prepare_bemmodel(cfg, vol);
% create some random electrodes
pnt = randn(200,3);
pnt = pnt(pnt(:,3)>0, :); % only those on the upper half
sens = [];
for i=1:size(pnt,1)
sens.pnt(i,:) = pnt(i,:) / norm(pnt(i,:)); % scale towards the skin surface
sens.label{i} = sprintf('%02d', i);
end
% prepare the sensor array and volume conduction, i.e. set up the linear
% interpolation from vertices to electrodes
[vol2, sens] = forwinv_prepare_vol_sens(vol1, sens);
lf = forwinv_compute_leadfield([0 0 50], sens, vol2);
figure; triplot(sens.pnt, [], lf(:,1)); colorbar
figure; triplot(sens.pnt, [], lf(:,2)); colorbar
figure; triplot(sens.pnt, [], lf(:,3)); colorbar
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Subfunctions from FieldTrip
function [pnt, dhk] = icosahedron162
% ICOSAHEDRON162 creates a 2-fold refined icosahedron
% Copyright (C) 2003, Robert Oostenveld
%
% $Log: icosahedron162.m,v $
% Revision 1.3 2003/11/28 09:40:12 roberto
% added a single help line
%
% Revision 1.2 2003/03/04 21:46:18 roberto
% added CVS log entry and synchronized all copyright labels
%
[pnt, dhk] = icosahedron;
[pnt, dhk] = refine(pnt, dhk);
[pnt, dhk] = refine(pnt, dhk);
pnt = pnt ./ repmat(sqrt(sum(pnt.^2,2)), 1,3);
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [pnt, dhk] = icosahedron
% ICOSAHEDRON creates an icosahedron
%
% [pnt, dhk] = icosahedron
% creates an icosahedron with 12 vertices and 20 triangles
%
% See also OCTAHEDRON, ICOSAHEDRON42, ICOSAHEDRON162, ICOSAHEDRON642, ICOSAHEDRON2562
% Copyright (C) 2002, Robert Oostenveld
%
% $Log: icosahedron.m,v $
% Revision 1.4 2006/07/26 11:03:38 roboos
% added "see also octahedron"
%
% Revision 1.3 2003/03/11 15:35:20 roberto
% converted all files from DOS to UNIX
%
% Revision 1.2 2003/03/04 21:46:18 roberto
% added CVS log entry and synchronized all copyright labels
%
dhk = [
1 2 3
1 3 4
1 4 5
1 5 6
1 6 2
2 8 3
3 9 4
4 10 5
5 11 6
6 7 2
7 8 2
8 9 3
9 10 4
10 11 5
11 7 6
12 8 7
12 9 8
12 10 9
12 11 10
12 7 11
];
pnt = zeros(12, 3);
rho=0.4*sqrt(5);
phi=2*pi*(0:4)/5;
pnt( 1, :) = [0 0 1]; % top point
pnt(2:6, 1) = rho*cos(phi)';
pnt(2:6, 2) = rho*sin(phi)';
pnt(2:6, 3) = rho/2;
pnt(7:11, 1) = rho*cos(phi - pi/5)';
pnt(7:11, 2) = rho*sin(phi - pi/5)';
pnt(7:11, 3) = -rho/2;
pnt(12, :) = [0 0 -1]; % bottom point
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [pntr, dhkr] = refine(pnt, dhk, method, varargin)
% REFINE a 3D surface that is described by a triangulation
%
% Use as
% [pnt, tri] = refine(pnt, tri)
% [pnt, tri] = refine(pnt, tri, 'updown', numtri)
%
% The default method is to refine the mesh globally by inserting a vertex at
% each edge according to the algorithm described in Banks, 1983.
%
% The alternative 'updown' method refines the mesh a couple of times
% using Banks' algorithm, followed by a downsampling using the REDUCEPATCH
% function.
% The Banks method is a memory efficient implementation which remembers
% the previously inserted vertices. The refinement algorithm executes in
% linear time with the number of triangles.
% Copyright (C) 2002-2005, Robert Oostenveld
%
% $Log: refine.m,v $
% Revision 1.4 2005/05/06 08:54:31 roboos
% added 'updown method, using matlab reducepatch function
%
% Revision 1.3 2003/03/11 15:35:20 roberto
% converted all files from DOS to UNIX
%
% Revision 1.2 2003/03/04 21:46:19 roberto
% added CVS log entry and synchronized all copyright labels
%
if nargin<3
method = 'banks';
end
switch lower(method)
case 'banks'
npnt = size(pnt,1);
ndhk = size(dhk,1);
insert = spalloc(3*npnt,3*npnt,3*ndhk);
dhkr = zeros(4*ndhk,3); % allocate memory for the new triangles
pntr = zeros(npnt+3*ndhk,3); % allocate memory for the maximum number of new vertices
pntr(1:npnt,:) = pnt; % insert the original vertices
current = npnt;
for i=1:ndhk
if ~insert(dhk(i,1),dhk(i,2))
current = current + 1;
pntr(current,:) = (pnt(dhk(i,1),:) + pnt(dhk(i,2),:))/2;
insert(dhk(i,1),dhk(i,2)) = current;
insert(dhk(i,2),dhk(i,1)) = current;
v12 = current;
else
v12 = insert(dhk(i,1),dhk(i,2));
end
if ~insert(dhk(i,2),dhk(i,3))
current = current + 1;
pntr(current,:) = (pnt(dhk(i,2),:) + pnt(dhk(i,3),:))/2;
insert(dhk(i,2),dhk(i,3)) = current;
insert(dhk(i,3),dhk(i,2)) = current;
v23 = current;
else
v23 = insert(dhk(i,2),dhk(i,3));
end
if ~insert(dhk(i,3),dhk(i,1))
current = current + 1;
pntr(current,:) = (pnt(dhk(i,3),:) + pnt(dhk(i,1),:))/2;
insert(dhk(i,3),dhk(i,1)) = current;
insert(dhk(i,1),dhk(i,3)) = current;
v31 = current;
else
v31 = insert(dhk(i,3),dhk(i,1));
end
% add the 4 new triangles with the correct indices
dhkr(4*(i-1)+1, :) = [dhk(i,1) v12 v31];
dhkr(4*(i-1)+2, :) = [dhk(i,2) v23 v12];
dhkr(4*(i-1)+3, :) = [dhk(i,3) v31 v23];
dhkr(4*(i-1)+4, :) = [v12 v23 v31];
end
% remove the space for the vertices that was not used
pntr = pntr(1:current, :);
case 'updown'
ndhk = size(dhk,1);
while ndhk<varargin{1}
% increase the number of triangles by a factor of 4
[pnt, dhk] = refine(pnt, dhk, 'banks');
ndhk = size(dhk,1);
end
% reduce number of triangles using Matlab function
[dhkr, pntr] = reducepatch(dhk, pnt, varargin{1});
otherwise
error(['unsupported method: ' method]);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [hs, hc, contour] = triplot(pnt, tri, val, mode, levels)
% TRIPLOT make 2D or 3D plot of triangulated surface and interpolated values
% The surface can be displayed with linear interpolated values or with
% linear interpolated contours of a potential distribution.
%
% Use as
% triplot(pnt, tri, value)
% triplot(pnt, tri, value, mode)
% triplot(pnt, tri, value, mode, levels)
% This will make a plot of value on the surface described by triangles
% tri with vertices pnt. The matrix tri can be [], in which case a
% it will be computed using a delaunay triangulation.
%
% The visualization mode can be
% 'surface' make interpolated plot of value on surface (default)
% 'faces' plot white triangles only (value can be [])
% 'faces_red' plot red triangles only (value can be [])
% 'faces_blue' plot blue triangles only (value can be [])
% 'faces_skin' plot skin-colored triangles only (value can be [])
% 'face_index' plot index of each triangle (value can be [])
% 'nodes' plot black vertices only (value can be [])
% 'node_index' plot index of each vertex (value can be [])
% 'node_label' plot label of each vertex (value should be cell array)
% 'edges' plot black edges only (value can be [])
% 'contour' make interpolated contour plot of value on surface
% 'contour_bw' make interpolated black-white contour plot
% 'contour_rb' make interpolated contour plot with red-blue
%
% With the optional levels, you can specify the levels at which contours will
% be plotted
%
% See also PATCH, COLORMAP, VIEW (general Matlab commands)
% updated on Mon Jul 23 12:41:44 MET DST 2001
% updated on Fri Jan 31 11:47:28 CET 2003
% Copyright (C) 2001=2006, Robert Oostenveld
%
% $Log: triplot.m,v $
% Revision 1.7 2008/06/24 13:37:51 roboos
% added option faces_blue
% always return handle to objects that were plotted
%
% Revision 1.6 2007/01/03 17:00:35 roboos
% updated documentation, changed layout of code and comments
%
% Revision 1.5 2006/09/19 16:11:35 roboos
% added support for line segments, removed "axis equal" at end
%
% Revision 1.4 2006/05/02 19:15:28 roboos
% added 'faces_red' style
%
% Revision 1.3 2004/06/28 07:51:39 roberto
% improved documentation, added faces_skin
%
% Revision 1.2 2003/03/17 10:37:29 roberto
% improved general help comments and added copyrights
%
% start with empty return values
hs = [];
hc = [];
contour = [];
% everything is added to the current figure
holdflag = ishold;
hold on
% check the input variables
if ~isempty(val)
val = val(:);
end
if nargin<4
mode = 'surface';
end
if isempty(tri) & ~strcmp(mode, 'nodes')
% no triangulation was specified but a triangulation is needed
if size(pnt,2)==2
% make a 2d triangulation of the points using delaunay
tri = delaunay(pnt(:,1), pnt(:,2));
else
% make a 2d triangulation of the projected points using delaunay
prj = elproj(pnt);
tri = delaunay(prj(:,1), prj(:,2));
end
end
if size(tri,2)==2
% lines are specified instead of triangles, convert to triangles
tri(:,3) = tri(:,2);
end
if nargin<3
warning('only displaying triangle edges')
mode='edges';
val = [];
elseif nargin<4
% warning('default displaying surface')
mode='surface';
elseif nargin<5
% determine contour levels
if ~isempty(val) & ~iscell(val)
absmax = max(abs([min(val) max(val)]));
levels = linspace(-absmax,absmax,21);
else
levels = [];
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% compute contours for 2D or 3D triangulation
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if strcmp(mode, 'contour') || strcmp(mode, 'contour_bw') || strcmp(mode, 'contour_rb')
triangle_val = val(tri);
triangle_min = min(triangle_val, [], 2);
triangle_max = max(triangle_val, [], 2);
for cnt_indx=1:length(levels)
cnt = levels(cnt_indx);
use = cnt>=triangle_min & cnt<=triangle_max;
counter = 0;
intersect1 = [];
intersect2 = [];
for tri_indx=find(use)'
pos = pnt(tri(tri_indx,:), :);
v(1) = triangle_val(tri_indx,1);
v(2) = triangle_val(tri_indx,2);
v(3) = triangle_val(tri_indx,3);
la(1) = (cnt-v(1)) / (v(2)-v(1)); % abcissa between vertex 1 and 2
la(2) = (cnt-v(2)) / (v(3)-v(2)); % abcissa between vertex 2 and 3
la(3) = (cnt-v(3)) / (v(1)-v(3)); % abcissa between vertex 1 and 2
abc(1,:) = pos(1,:) + la(1) * (pos(2,:) - pos(1,:));
abc(2,:) = pos(2,:) + la(2) * (pos(3,:) - pos(2,:));
abc(3,:) = pos(3,:) + la(3) * (pos(1,:) - pos(3,:));
counter = counter + 1;
sel = find(la>=0 & la<=1);
intersect1(counter, :) = abc(sel(1),:);
intersect2(counter, :) = abc(sel(2),:);
end
% remember the details for external reference
contour(cnt_indx).level = cnt;
contour(cnt_indx).n = counter;
contour(cnt_indx).intersect1 = intersect1;
contour(cnt_indx).intersect2 = intersect2;
end
% collect all different contourlevels for plotting
intersect1 = [];
intersect2 = [];
cntlevel = [];
for cnt_indx=1:length(levels)
intersect1 = [intersect1; contour(cnt_indx).intersect1];
intersect2 = [intersect2; contour(cnt_indx).intersect2];
cntlevel = [cntlevel; ones(contour(cnt_indx).n,1) * levels(cnt_indx)];
end
X = [intersect1(:,1) intersect2(:,1)]';
Y = [intersect1(:,2) intersect2(:,2)]';
C = [cntlevel(:) cntlevel(:)]';
if size(pnt,2)>2
Z = [intersect1(:,3) intersect2(:,3)]';
else
Z = zeros(2, length(cntlevel));
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% plot the desired detail
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
switch lower(mode)
case 'faces'
% plot the faces of the 2D or 3D triangulation
hs = patch('Vertices', pnt, 'Faces', tri);
set(hs, 'FaceColor', 'white');
set(hs, 'EdgeColor', 'none');
case 'faces_skin'
% plot the faces of the 2D or 3D triangulation
skin = [255 213 119]/255;
brain = [202 100 100]/255;
cortex = [255 213 119]/255;
hs = patch('Vertices', pnt, 'Faces', tri);
set(hs, 'FaceColor', skin);
set(hs, 'EdgeColor', 'none');
lighting gouraud
material shiny
camlight
case 'faces_red'
% plot the faces of the 2D or 3D triangulation
hs = patch('Vertices', pnt, 'Faces', tri);
set(hs, 'FaceColor', [1 0 0]);
set(hs, 'EdgeColor', 'none');
lighting gouraud
material shiny
camlight
case 'faces_blue'
% plot the faces of the 2D or 3D triangulation
hs = patch('Vertices', pnt, 'Faces', tri);
set(hs, 'FaceColor', [0 0 1]);
set(hs, 'EdgeColor', 'none');
lighting gouraud
material shiny
camlight
case 'face_index'
% plot the triangle indices (numbers) at each face
for face_indx=1:size(tri,1)
str = sprintf('%d', face_indx);
tri_x = (pnt(tri(face_indx,1), 1) + pnt(tri(face_indx,2), 1) + pnt(tri(face_indx,3), 1))/3;
tri_y = (pnt(tri(face_indx,1), 2) + pnt(tri(face_indx,2), 2) + pnt(tri(face_indx,3), 2))/3;
tri_z = (pnt(tri(face_indx,1), 3) + pnt(tri(face_indx,2), 3) + pnt(tri(face_indx,3), 3))/3;
h = text(tri_x, tri_y, tri_z, str, 'HorizontalAlignment', 'center', 'VerticalAlignment', 'middle');
hs = [hs; h];
end
case 'edges'
% plot the edges of the 2D or 3D triangulation
hs = patch('Vertices', pnt, 'Faces', tri);
set(hs, 'FaceColor', 'none');
set(hs, 'EdgeColor', 'black');
case 'nodes'
% plot the nodes (vertices) only as points
if size(pnt, 2)==2
hs = plot(pnt(:,1), pnt(:,2), 'k.');
else
hs = plot3(pnt(:,1), pnt(:,2), pnt(:,3), 'k.');
end
case 'nodes_blue'
% plot the nodes (vertices) only as points
if size(pnt, 2)==2
hs = plot(pnt(:,1), pnt(:,2), 'b.', 'MarkerSize', 20);
else
hs = plot3(pnt(:,1), pnt(:,2), pnt(:,3), 'b.', 'MarkerSize', 20);
end
case 'nodes_red'
% plot the nodes (vertices) only as points
if size(pnt, 2)==2
hs = plot(pnt(:,1), pnt(:,2), 'r.', 'MarkerSize', 20);
else
hs = plot3(pnt(:,1), pnt(:,2), pnt(:,3), 'r.', 'MarkerSize', 20);
end
case 'node_index'
% plot the vertex indices (numbers) at each node
for node_indx=1:size(pnt,1)
str = sprintf('%d', node_indx);
if size(pnt, 2)==2
h = text(pnt(node_indx, 1), pnt(node_indx, 2), str, 'HorizontalAlignment', 'center', 'VerticalAlignment', 'middle');
else
h = text(pnt(node_indx, 1), pnt(node_indx, 2), pnt(node_indx, 3), str, 'HorizontalAlignment', 'center', 'VerticalAlignment', 'middle');
end
hs = [hs; h];
end
case 'node_label'
% plot the vertex indices (numbers) at each node
for node_indx=1:size(pnt,1)
str = val{node_indx};
if ~isempty(str)
if size(pnt, 2)==2
h = text(pnt(node_indx, 1), pnt(node_indx, 2), str, 'HorizontalAlignment', 'center', 'VerticalAlignment', 'middle');
else
h = text(pnt(node_indx, 1), pnt(node_indx, 2), pnt(node_indx, 3), str, 'HorizontalAlignment', 'center', 'VerticalAlignment', 'middle');
end
else
h = -1;
end
hs = [hs; h];
end
case 'surface'
% plot a 2D or 3D triangulated surface with linear interpolation
if length(val)==size(pnt,1)
hs = patch('Vertices', pnt, 'Faces', tri, 'FaceVertexCData', val, 'FaceColor', 'interp');
else
hs = patch('Vertices', pnt, 'Faces', tri, 'CData', val, 'FaceColor', 'flat');
end
set(hs, 'EdgeColor', 'none');
case 'contour_bw'
% make black-white contours
hc = [];
for i=1:length(cntlevel)
if cntlevel(i)>0
linestyle = '-';
linewidth = 1;
elseif cntlevel(i)<0
linestyle = '--';
linewidth = 1;
else
linestyle = '-';
linewidth = 2;
end
h1 = patch('XData', X(:,i), 'Ydata', Y(:,i), ...
'ZData', Z(:,i), 'CData', C(:,i), ...
'facecolor','none','edgecolor','black', ...
'linestyle', linestyle, 'linewidth', linewidth, ...
'userdata',cntlevel(i));
hc = [hc; h1];
end
case 'contour_rb'
% make red-blue contours
hc = [];
for i=1:length(cntlevel)
if cntlevel(i)>0
edgecolor = 'red';
elseif cntlevel(i)<0
edgecolor = 'blue';
else
edgecolor = 'black';
end
h1 = patch('XData', X(:,i), 'Ydata', Y(:,i), ...
'ZData', Z(:,i), 'CData', C(:,i), ...
'facecolor','none','edgecolor',edgecolor, ...
'linestyle', '-', 'linewidth', 3, ...
'userdata',cntlevel(i));
hc = [hc; h1];
end
case 'contour'
% make full-color contours
hc = [];
for i=1:length(cntlevel)
h1 = patch('XData', X(:,i), 'Ydata', Y(:,i), ...
'ZData', Z(:,i), 'CData', C(:,i), ...
'facecolor','none','edgecolor','flat',...
'userdata',cntlevel(i));
hc = [hc; h1];
end
end % switch
axis off
axis vis3d
axis equal
if nargout==0
clear contour hc hs
end
if ~holdflag
hold off
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [proj] = elproj(pos, method);
% ELPROJ makes a azimuthal projection of a 3D electrode cloud
% on a plane tangent to the sphere fitted through the electrodes
% the projection is along the z-axis
%
% [proj] = elproj([x, y, z], 'method');
%
% Method should be one of these:
% 'gnomic'
% 'stereographic'
% 'ortographic'
% 'inverse'
% 'polar'
%
% Imagine a plane being placed against (tangent to) a globe. If
% a light source inside the globe projects the graticule onto
% the plane the result would be a planar, or azimuthal, map
% projection. If the imaginary light is inside the globe a Gnomonic
% projection results, if the light is antipodal a Sterographic,
% and if at infinity, an Orthographic.
%
% The default projection is a polar projection (BESA like).
% An inverse projection is the opposite of the default polar projection.
% Copyright (C) 2000-2008, Robert Oostenveld
%
% $Log: elproj.m,v $
% Revision 1.4 2008/05/15 10:54:24 roboos
% updated documentation
%
% Revision 1.3 2007/03/20 10:29:35 roboos
% renamed method 'default' into 'polar'
%
% Revision 1.2 2003/03/17 10:37:28 roberto
% improved general help comments and added copyrights
%
x = pos(:,1);
y = pos(:,2);
if size(pos, 2)==3
z = pos(:,3);
end
if nargin<2
method='polar';
end
if nargin<3
secant=1;
end
if strcmp(method, 'orthographic')
% this method compresses the lowest electrodes very much
% electrodes on the bottom half of the sphere are folded inwards
xp = x;
yp = y;
num = length(find(z<0));
str = sprintf('%d electrodes may be folded inwards in orthographic projection\n', num);
if num
warning(str);
end
proj = [xp yp];
elseif strcmp(method, 'gnomic')
% the lightsource is in the middle of the sphere
% electrodes on the equator are projected at infinity
% electrodes below the equator are not projected at all
rad = mean(sqrt(x.^2 + y.^2 + z.^2));
phi = cart2pol(x, y);
th = atan(sqrt(x.^2 + y.^2) ./ z);
xp = cos(phi) .* tan(th) .* rad;
yp = sin(phi) .* tan(th) .* rad;
num = length(find(th==pi/2 | z<0));
str = sprintf('removing %d electrodes from gnomic projection\n', num);
if num
warning(str);
end
xp(find(th==pi/2 | z<0)) = NaN;
yp(find(th==pi/2 | z<0)) = NaN;
proj = [xp yp];
elseif strcmp(method, 'stereographic')
% the lightsource is antipodal (on the south-pole)
rad = mean(sqrt(x.^2 + y.^2 + z.^2));
z = z + rad;
phi = cart2pol(x, y);
th = atan(sqrt(x.^2 + y.^2) ./ z);
xp = cos(phi) .* tan(th) .* rad * 2;
yp = sin(phi) .* tan(th) .* rad * 2;
num = length(find(th==pi/2 | z<0));
str = sprintf('removing %d electrodes from stereographic projection\n', num);
if num
warning(str);
end
xp(find(th==pi/2 | z<0)) = NaN;
yp(find(th==pi/2 | z<0)) = NaN;
proj = [xp yp];
elseif strcmp(method, 'inverse')
% compute the inverse projection of the default angular projection
[th, r] = cart2pol(x, y);
[xi, yi, zi] = sph2cart(th, pi/2 - r, 1);
proj = [xi, yi, zi];
else
% use default angular projection
[az, el, r] = cart2sph(x, y, z);
[x, y] = pol2cart(az, pi/2 - el);
proj = [x, y];
end
|
github
|
philippboehmsturm/antx-master
|
writeCPersist.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/ctf/writeCPersist.m
| 5,086 |
utf_8
|
0c56dc571aa56100f050678e5fe815ff
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%% Function writeCPersist %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function writeCPersist(filename,Tag)
% Version 1.2 24 April 2007. Removed terminating null characters from charatcer strings
% types 10,11)
% Version 1.1 13 April 2007
% Write a CTF CPersist file. See document CTF MEG File Format, PN900-0066
% Inputs : filename : Name of the output file name including path
% Tag: Structure array containing all of the tags, types, and data.
% 31 Aug 2006: Recognizes type=1,...,17. If other data types are specified,
% writeCPersist will print an error message.
% Delete existing file so the new file has the correct creation data/time.
if nargin==0
fprintf(['writeCPersist: Version 1.2 24 April 2007 Writes a CTF CPersist file.\n'...
'\twriteCPersist(filename,Tag) writes a CPersist file from the contents of\n',...
'\tstructure array Tag. Tag is in the format prepared by readCPersist.\n\n']);
Tag=[];
return
end
if exist(filename)==2
delete(filename);
end
startString='WS1_';
EOFstring='EndOfParameters';
startVal=256.^[3:-1:0]*double(startString)'; % Integer version of startString
fid=fopen(filename,'w','ieee-be');
EOFcount=0; % Make sure that the startString's and EOFstring's balance
count=0;
while count<length(Tag)
count=count+1;
if strcmp(Tag(count).name,startString) % start of Cpersist object
fwrite(fid,startVal,'int32');
EOFcount=EOFcount-1;
continue
end
fwrite(fid,length(Tag(count).name),'int32'); % end of CPersist object
fwrite(fid,Tag(count).name,'char');
if strcmp(Tag(count).name,EOFstring);
EOFcount=EOFcount+1;
continue;
end
fwrite(fid,Tag(count).type,'int32');
if Tag(count).type==1
fwrite(fid,Tag(count).data,'int32');
elseif Tag(count).type==2 % Start embedded CPersist object
elseif Tag(count).type==3 % binary list
fwrite(fid,2*length(Tag(count).data),'int32');
fwrite(fid,Tag(count).data,'int16');
elseif Tag(count).type==4 % double
fwrite(fid,Tag(count).data,'float64');
elseif Tag(count).type==5 % integer
fwrite(fid,Tag(count).data,'int32');
elseif Tag(count).type==6 % short integer
fwrite(fid,Tag(count).data,'int16');
elseif Tag(count).type==7 % unsigned short integer
fwrite(fid,Tag(count).data,'uint16');
elseif Tag(count).type==8 % Boolean byte
fwrite(fid,Tag(count).data,'uint8');
elseif Tag(count).type==9; % CStr32
nChar=min(32,length(Tag(count).data));
fwrite(fid,[double(Tag(count).data(1:nChar)) zeros(1,32-nChar)],'uint8');
elseif Tag(count).type==10; % CString
fwrite(fid,length(Tag(count).data),'int32');
fwrite(fid,double(Tag(count).data),'uint8');
elseif Tag(count).type==11; % Cstring list.
nList=size(Tag(count).data,1);
fwrite(fid,nList,'int32');
for k=1:nList
% Do not force termination of strings with nulls (char(0))
Cstring=[deblank(Tag(count).data(k,:))];
fwrite(fid,length(Cstring),'int32');
fwrite(fid,double(Cstring),'uint8');
end
clear k CString nList;
elseif Tag(count).type==12; % CStr32 list.
nList=size(Tag(count).data,1); %size(data)=[nList 32]
fwrite(fid,nList,'int32');
% Do not force termination of strings with nulls (char(0))
for k=1:nList
strng=deblank(Tag(count).data(k,:));
nChar=min(32,length(strng));
Tag(count).data(k,:)=[strng(1:nChar) char(zeros(1,32-nChar))];
end
fwrite(fid,double(Tag(count).data)','uint8');
clear k strng nChar nList;
elseif Tag(count).type==13; % SensorClass list.
fwrite(fid,length(Tag(count).data),'int32');
fwrite(fid,Tag(count).data,'int32')
elseif Tag(count).type==14 % long integer
fwrite(fid,Tag(count).data,'int32');
elseif Tag(count).type==15 % unsigned longinteger
fwrite(fid,Tag(count).data,'uint32');
elseif Tag(count).type==16 % unsigned integer
fwrite(fid,Tag(count).data,'uint32');
elseif Tag(count).type==17 % Boolean
if ~any(Tag(count).data==[0 1])
fprintf('writeCPersist: tagname=%s type=%d value=%d? (Must =0 or 1)\n',...
tagname,type,Tag(count).data);
Tag(count).data=(Tag(count).data~=0);
fprintf(' Set value=%d.\n',Tag(count).data);
end
fwrite(fid,Tag(count).data,'int32');
else
fprintf('writeCPersist: Tag(%d) name=%s type=%d\n',count,Tag(count).name,Tag(count).type);
fprintf('\t\t UNRECOGNIZED type.\n');
fclose(fid);
break;
end
end % Loop over tags
fclose(fid);
% EOF_count should be zero at the end of the file
if EOFcount~=0;
fprintf('write_CPerist: EOFcount=%d Stop strings do not balance start strings.\n',...
EOFcount);
fprintf(' Start string=%s Stop string=%s\n',startString,EOFstring);
end
return
%%%%%%%% End of writeCPersist %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
github
|
philippboehmsturm/antx-master
|
getCTFBalanceCoefs.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/ctf/getCTFBalanceCoefs.m
| 20,490 |
utf_8
|
2c434fcbdb53fbc50ee3fbda72e98883
|
function [alphaMEG,MEGindex,MEGbalanceindex,alphaGref,Grefindex,Gbalanceindex]=...
getCTFBalanceCoefs(ds,balanceType,unit);
% Reads balance coefficients for SQUID data in phi0's, and converts to coefficients
% for data in physical units.
% Input : ds : (1) ds structure from readCTFds
% balanceType : 'NONE' : No balancing
% 'G1BR' : 1st order balancing
% 'G2BR' : 2nd order balancing
% 'G3BR' : 3rd order balancing
% 'G3AR' : 3rd order balancing + adaptive
% If only MEG balance table is requested, size(balanceType)=[1 5]
% If Gref balance table is requested also, size(balanceType)=[2 4]
% unit: Type of units. Option: 'fT','T','phi0','int'.
% If unit is not entered, of unit=[], the default is unit='fT'.
% Outputs :
% alphaMEG,MEGindex,MEGbalanceindex : MEG balancing coefficients for data in fT or T.
% Suppose data array returned by getTrial2 has size(data)=[npt nchan].
% nMEG = number of MEG channels in the data set.
% MEG channels have sensorTypeIndex==5.
%
% MEGindex = list of MEG channels referred to the channel numbering in
% the complete dataset (i.e. it is not referred to only the list of
% SQUID sensors).
% by looking for sensors with ds.res4.senres.sensorTypeIndex==5
% size(MEGindex)=[1 nMEG]
% MEG data = data(:,MEGindex)
% MEGbalanceindex = list of reference channels for MEG balancing.
% size(MEGbalanceindex)=[1 nRef]
% Reference data for MEG balancing = data(:,MEGbalanceindex)
% alphaMEG = balance coefficients. size(alphaMEG)=[nRef nMEG]
%
% Balancing MEG data :
% - Start with data AFTER converting to physical units.
% (I.e. SQUID data must be in fT or T.)
% - balanced_data(:,MEGindex)=data(:,MEGindex)-data(:,MEGbalanceindex)*alphaMEG
% If user specifies balanceType=[], ' ' or 'none', then getCTFBalanceCoefs returns
% alphaMEG=zeros(0,nMEG), MEGindex=list of MEG sensor channels,
% MEGbalanceindex=[], alphaGref=zeros(0,nGef), Grefindex=list of Gref channels
% and Gbalanceindex=[];
% alphaGref,Grefindex,Gbalanceindex : Reference-gradiometer balancing coeficients.
% These output arrays are optional. If the calling statement includes
% them, then this program extracts a table of balance coefficients for
% the reference gradiometers from the G1BR table in the coefficient files.
% nGref = no. of reference gradiometers channels in the data set
% (sensorTypeIndex=1)
% Grefindex = list of reference channels. size(Grefindex)=[1 nGref]
% Gradient reference data = data(:,Grefindex)
% Gbalanceindex = list of channels for balancing reference
% gradiometers. size(Gbalanceindex)=[1 nGbalcoef]
% Balancing reference data = data(:,Gbalanceindex)
% alphaGref = balance coefficients for ref. grads.
% size(alphaGref)=[nGbalcoef nGref]
%
% Balancing ref. gradiometer data :
% - Use data AFTER converting to physical units. (I.e. data in fT or T.)
% balanced_data(:,Grefindex)=data(:,Grefindex)-data(:,Gbalanceindex)*alphaGref
% Calls function getRawCTFBalanceCoefs (included in this listing).
if nargout==0 & nargin==0
fprintf(['\ngetCTFBalanceCoefs: Version 1.1 17 April 2007 ',...
'Reads balance coefficients from ds.res4.scrr.\n\n',...
'\tMEG balancing : [alphaMEG,MEGindex,MEGbalanceindex]=',...
'getCTFBalanceCoefs(ds,balanceType,unit);\n\n',...
'\tMEG & Gref balancing : [alphaMEG,MEGindex,MEGbalanceindex,',...
'alphaGref,Grefindex,Gbalanceindex]=\n',...
'\t ',...
'getCTFBalanceCoefs(ds,balanceType,unit);\n\n']);
return
end
balanceOptions=strvcat('NONE','G1BR','G2BR','G3BR', 'G3AR');
balanceOptionsEnds = [size(balanceOptions, 1), 2]; % Which options are available for MEGs and Grefs.
physical_options=strvcat('fT','T');
raw_options=strvcat('phi0','int');
unit_options=strvcat(physical_options,raw_options);
default_unit='fT';
% Specify outputs in case of an early return due to an error.
MEGindex=[];
Grefindex=[];
alphaMEG=[];
MEGbalanceindex=[];
alphaGref=[];
Gbalanceindex=[];
% Check that the inputs are sensible.
if nargin<2
fprintf(['\ngetCTFBalanceCoefs: Only %d input arguments? ',...
'Must specify at least ds and balanceType.\n\n'],nargin);
return
elseif ~isstruct(ds) | isempty(ds) | ~ischar(balanceType) | isempty(balanceType)
fprintf('\ngetCTFBalanceCoefs: Wrong argument types or sizes.\n\n');
whos ds balanceType
return
elseif ~isfield(ds,'res4')
fprintf('\ngetCTFBalanceCoefs: Field res4 is missing from structure ds.\n\n');
ds
return
elseif size(balanceType,1)>2
fprintf('\ngetCTFBalanceCoefs: size(balanceType)=[');fprintf(' %d',size(balanceType));...
fprintf('] Must be[1 4] or [2 4].\n\n');
return
end
% Must have 3 or 6 output arguments. Set balanceType(2,:)='NONE' if necessary.
if ~any(nargout==[3 6]);
fprintf(['\ngetCTFBalanceCoefs: Called with %d output arguments. ',...
'Must be 3 or 6.\n\n'],nargout);
return
elseif (nargout==3 & size(balanceType,1)>1) | (nargout==6 & size(balanceType,1)==1)
balanceType=strvcat(deblank(balanceType(1,:)),'NONE');
end
% At this point, size(balanceType,1)=2.
% Check that balanceType has allowed values
for k=1:size(balanceType,1) % k=1:MEGs, k=2:Grefs
if isempty(strmatch(balanceType(k,:),balanceOptions(1:balanceOptionsEnds(k),:)))
fprintf('\ngetCTFBalanceCoefs: balanceType(%d,:)=%s Not an allowed option.\n\n',...
k,balanceType(k,:));
return
end
end
% Check the data units, convert to lower case and flag incorrect unit specification
if ~exist('unit');
unit=default_unit;
elseif isempty(unit);
unit=default_unit;
elseif ~ischar(unit)
fprintf('\ngetCTFBalanceCoefs: Input unit has the wrong type: class(unit)=%s\n\n',...
class(unit));
return
end
unit=lower(unit);
if isempty(strmatch(unit,lower(strvcat(physical_options,raw_options))))
fprintf('\ngetCTFBalanceCoefs: unit=%s. Must be one of ',unit);
for k=1:size(unit_options,1);fprintf(' %s,',deblank(unit_options(k,:)));end;
fprintf('\n\n');
return
end
physical=~isempty(strmatch(unit,lower(physical_options)));
balanceType=upper(deblank(balanceType));
[betaMEG,MEGindex,MEGbalanceindex,betaGref,Grefindex,Gbalanceindex]=...
getRawCTFBalanceCoefs(ds,balanceType);
% No balancing is requested, just return lists of MEGindex and Grefindex.
if isempty(MEGbalanceindex)
alphaMEG=zeros(0,length(MEGindex));
MEGbalanceindex=[]; % force size=[0 0]
end
if isempty(Gbalanceindex)
alphaGref=zeros(0,length(Grefindex));
Gbalanceindex=[]; % force size=[0 0]
end
if isempty(MEGbalanceindex) & isempty(Gbalanceindex)
return
end
% betaMEG and betaGref are the balance coefficients when signals are in phi0's.
% Convert to balance coefficients when signals are in physical units (T or fT).
% invproperGain is introduced to take care of situations where bad channels
% are labelled by setting their gain to zero.
if physical
properGain=zeros(1,ds.res4.no_channels);
invproperGain=zeros(1,ds.res4.no_channels);
for k=1:ds.res4.no_channels
if any(ds.res4.senres(k).sensorTypeIndex==[0 1 5:7]) % SQUIDs only
properGain(k)=ds.res4.senres(k).properGain; % properGain = phi0/T
if properGain(k)~=0
invproperGain(k)=1/properGain(k);
end
end
end
end
if ~isempty(MEGbalanceindex)
if physical
alphaMEG=betaMEG.*(properGain(MEGbalanceindex)'*invproperGain(MEGindex));
else
alphaMEG=betaMEG;
end
end
if ~isempty(Gbalanceindex)
if physical
alphaGref=betaGref.*(properGain(Gbalanceindex)'*invproperGain(Grefindex));
else
alphaGref=betaGref;
end
end
return
%%%%%%%%%%% End of getBalanceCoef %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%% Function getRawCTFBalanceCoefs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [betaMEG,MEGindex,Refindex,betaGref,Grefindex,Gbalanceindex]=...
getRawCTFBalanceCoefs(ds,balanceType);
% getRawCTFBalanceCoefs. Extracts raw-data (i.e. integer data) gradiometer balancing
% coefficients from structure array ds.res4.scrr (ds is produced
% by readCTFds).
% Date : 24 OCt 2006
% Author : Harold Wilson
% Inputs : ds : Structure returned by readCTFds.
% balanceType : 'NONE' : No balancing
% 'G1BR' : 1st order balancing
% 'G2BR' : 2nd order balancing
% 'G3BR' : 3rd order balancing
% 'G3AR' : 3rd order balancing + adaptive
% If only MEG balance table is requested, size(balanceType)=[1 4]
% If Gref balance table is requested also, size(balanceType)=[2 4]
% If balancing 'NONE' is specified, getRawCTFBalanceCoefs returns lists MEGindex and
% Grefindex, and sets Refindex=[], Gbalanceindex=[].
% The reference gradiometers have only G1BR balancing coefficients.
% Outputs :
% betaMEG,MEGindex,Refindex : MEG balancing coefficients.
% Suppose data array returned by getCTFdata has size(data)=[npt nchan].
% nMEG = number of MEG channels in the data set.
% MEG channels have sensorTypeIndex==5.
%
% MEGindex = list of MEG channels in the data set. It is assembled
% by looking for sensors with ds.res4.senres.sensorTypeIndex==5
% size(MEGindex)=[1 nMEG]
% MEG data = data(:,MEGindex)
% Refindex = list of reference channels for MEG balancing.
% size(Refindex)=[1 nRef]
% Reference data = data(:,Refindex)
% betaMEG = balance coefficients. size(betaMEG)=[nRef nMEG]
%
% Balancing MEG data :
% - Start with data BEFORE converting to physical units.
% (I.e. SQUID data must be in phi0's or raw integers.)
% - balanced_data(:,MEGindex)=data(:,MEGindex)-data(:,Refindex)*betaMEG
% If user specifies balanceType=[] or ' ', then getRawCTFBalanceCoefs returns
% betaMEG=zeros(1,nMEG),Refindex=3 and nRef=1;
% betaGref,Grefindex,Gbalanceindex : Reference-gradiometer balancing coeficients.
% These output arrays are optional. If the calling statement includes
% them, then this program extracts a table of balance coefficients for
% the reference gradiometers from the G1BR table in the coefficient files.
% nGref = no. of reference gradiometers channels in the data set
% (sensorTypeIndex=1)
% Grefindex = list of reference channels. size(Grefindex)=[1 nGref]
% Gradient reference data = data(:,Grefindex)
% Gbalanceindex = list of channels for balancing reference
% gradiometers. size(Gbalanceindex)=[1 nGbalcoef]
% Balancing reference data = data(:,Gbalanceindex)
% betaGref = balance coefficients for ref. grads.
% size(betaGref)=[nGbalcoef nGref]
%
% Balancing ref. gradiometer data :
% balanced_data(:,Grefindex)=data(:,Grefindex)-data(:,Gbalanceindex)*betaGref
% No function calls.
missingMEGMessage=0;
missingGrefMessage=0;
balanceOptions=strvcat('NONE','G1BR','G2BR','G3BR', 'G3AR');
balanceOptionsEnds = [size(balanceOptions, 1), 2]; % Which options are available for MEGs and Grefs.
common_mode_only=0;
Brefindex=[]; % Index list of reference magnetometers in the data arrays
Grefindex=[]; % Index list of reference gradiometers in the data arrays
MEGindex=[]; % Index list of MEG sensors in the data arrays
Gbalanceindex=[]; % Index list of sensors used as references to balance the reference
% gradiometers
Refindex=[]; % Index list of sensors used to balance the MEG sensors
betaMEG=[];
betaGref=[];
% Check that the inputs are sensible.
if nargin<2
fprintf(['\ngetRawCTFBalanceCoefs: Only %d input arguments? ',...
'Must specify at least ds and balance.\n\n'],nargin);
return
elseif ~isstruct(ds) | isempty(ds) | ~ischar(balanceType) | isempty(balanceType)
fprintf('\ngetRawCTFBalanceCoefs: Wrong argument types or sizes.\n\n');
whos ds balanceType
return
elseif ~isfield(ds,'res4')
fprintf('\ngetRawCTFBalanceCoefs: Field res4 is missing from structure ds.\n\n');
ds
return
end
% Check that the output list is OK.
if nargout~=3 & nargout~=6
fprintf('\ngetRawCTFBalanceCoefs : Call specifies %d output arguments.\n',nargout);
fprintf('\t\tMust have 3 output arguments (MEG balance coefficients)\n');
fprintf('\t\tor 6 output arguments (reference gradiometer balancing also).\n\n');
return
elseif nargout==3
if size(balanceType,1)>1;balanceType=balanceType(1,:);end
else
if size(balanceType,1)==1;balanceType=strvcat(balanceType,'NONE');end
end
% Check that balanceType has allowed values
for k=1:size(balanceType,1) % k=1:MEGs, k=2:Grefs
if isempty(strmatch(balanceType(k,:),balanceOptions(1:balanceOptionsEnds(k),:)))
fprintf('\ngetRawCTFBalanceCoefs: balance(%d,:)=%s Not an allowed option.\n\n',...
k,balanceType(k,:));
return
end
end
% Make lists of reference magnetometers, reference gradiometers and MEG sensors.
for q=1:length(ds.res4.senres)
if ds.res4.senres(q).sensorTypeIndex==0
Brefindex=[Brefindex q];
elseif ds.res4.senres(q).sensorTypeIndex==1
Grefindex=[Grefindex q];
elseif ds.res4.senres(q).sensorTypeIndex==5 % Allow other MEG sensors?
MEGindex=[MEGindex q];
end
end
nBref=length(Brefindex); % Don't currently use Brefindex or nBref
nGref=length(Grefindex);
nMEG=length(MEGindex);
nGbalcoef=0; % Set to zero until we know the number by examining ds.res4.scrr
if nargout==6 & strcmp(balanceType(2,:),'NONE')
Gbalanceindex=[];
betaGref=zeros(0,nGref);
elseif nargout==6 & ~strcmp(balanceType(2,:),'NONE')
m1=1; % Get coefficients for balancing the reference gradiometers.
mtot=size(ds.res4.scrr,2);
for n=1:nGref
Gname=strtok(ds.res4.chanNames(Grefindex(n),:),['- ',char(0)]);
nGchar=length(Gname);
for m=[m1:mtot 1:(m1-1)]
if strncmp(Gname,char(ds.res4.scrr(m).sensorName),nGchar) & ...
strcmp('G1BR',char(ds.res4.scrr(m).coefType));
if nGbalcoef<=0 % 1st match. Initialize table and get list of references
nGbalcoef=ds.res4.scrr(m).numcoefs;
betaGref=zeros(nGbalcoef,nGref);
% Assemble index array for balancing the reference gradiometers
for q=1:nGbalcoef
Refname=strtok(char(ds.res4.scrr(m).sensor(:,q))',['- ',char(0)]);
pRef=strmatch(Refname,ds.res4.chanNames);
if isempty(pRef)
fprintf(['getRawCTFBalanceCoefs : Sensor %s appears in ',...
'ds.res4.scrr, but not in ds.res4.chanNames\n'],Refname);
return
end
Gbalanceindex=[Gbalanceindex pRef];
end
end % end setup of balancing table for Ref. gradiometers
if ds.res4.scrr(m).numcoefs~=nGbalcoef
fprintf('\ngetRawCTFBalanceCoefs : %s has %d coefficients\n',...
ds.res4.chanNames(Grefindex(1),1:nGchar),nGbalcoef);
fprintf(' %s " %d " ????\n\n',...
ds.res4.chanNames(Grefindex(n),1:nGchar),ds.res4.scrr(m).numcoefs);
betaGref=[]; % Force useless output.
return
end
betaGref(:,n)=reshape(ds.res4.scrr(m).coefs(1:nGbalcoef),nGbalcoef,1);
m1=m+1;
break; % Break out of m-loop. Go to nect n value.
end
if (m==m1-1 & m1>1) | (m==mtot & m1==1)
if missingGrefMessage==0
if strncmp(balanceType(2,:), balanceOptions(5,:), 4)
% Avoid warning for all sensors for adaptive coefficients.
fprintf('\ngetRawCTFBalanceCoefs: Failed to find %s balance coefficients for reference sensors.\n',...
balanceType(2,:));
else
fprintf(['\ngetRawCTFBalanceCoefs: Failed to find %s balance coefficients',...
' for sensor(s)'],balanceType(2,:));
fprintf('\n\t\t\t\t');
end
end
missingGrefMessage=missingGrefMessage+1;
if ~strncmp(balanceType(2,:), balanceOptions(5,:), 4)
if missingGrefMessage==10*round(missingGrefMessage/10)
fprintf('\n\t\t\t\t');
end
fprintf(' %s',Gname);
end
betaGRef(:,n)=zeros(nGbalcoef,1);
return
end
end % End loop over m (searching for scrr(m).sensorName)
end % End loop over n (list of reference gradiometers)
end % End of section getting coefficients to balance the reference gradiometers.
if missingGrefMessage>0;fprintf('\n');end
if strcmp(balanceType(1,:),'NONE')
Refindex=[];
betaMEG=zeros(0,nMEG);
return
end
% Get balance coefficients for the MEG sensors
nRef=0;
% Pointers for search through ds.res4.scrr structure array.
m1=1;
mtot=size(ds.res4.scrr,2);
for n=1:nMEG
MEGname=strtok(ds.res4.chanNames(MEGindex(n),:),['- ',char(0)]);
nChar=length(MEGname);
for m=[m1:mtot 1:(m1-1)]
if strncmp(MEGname,char(ds.res4.scrr(m).sensorName),nChar) & ...
strcmp(balanceType(1,:),char(ds.res4.scrr(m).coefType));
if nRef<=0
nRef=ds.res4.scrr(m).numcoefs;
betaMEG=zeros(nRef,nMEG);
for q=1:nRef % Assemble index array for balancing the MEG sensors
Refname=strtok(char(ds.res4.scrr(m).sensor(:,q))',['- ',char(0)]);
pRef=strmatch(Refname,ds.res4.chanNames);
if isempty(pRef)
fprintf(['\ngetRawCTFBalanceCoefs : Sensor %s appears in ',...
'ds.res4.scrr, but not in ds.res4.chanNames\n\n'],Refname);
return
end
Refindex=[Refindex pRef];
end
end % end setup of balancing table for MEG sensors
if ds.res4.scrr(m).numcoefs~=nRef
fprintf('\ngetRawCTFBalanceCoefs : %s - %s has %d coefficients\n',...
ds.res4.chanNames(MEGindex(1),1:nChar),balanceType,nRef);
fprintf(' %s - %s " %d " ????\n\n',...
ds.res4.chanNames(MEGindex(n),1:nChar),balanceType,...
ds.res4.scrr(m).numcoefs);
betaMEG=[]; % An output that will force an error in the calling program.
return
end
betaMEG(:,n)=reshape(ds.res4.scrr(m).coefs(1:nRef),nRef,1);
m1=m+1;
break;
end
if (m==m1-1 & m1>1) | (m==mtot & m1==1)
if missingMEGMessage==0
if strncmp(balanceType(2,:), balanceOptions(5,:), 4)
% Avoid warning for all sensors for adaptive coefficients.
fprintf('\ngetRawCTFBalanceCoefs: Failed to find %s balance coefficients for sensors.\n',...
balanceType(2,:));
else
fprintf(['\ngetRawCTFBalanceCoefs: Failed to find %s balance coefficients',...
' for sensor(s)'],balanceType(1,:));
fprintf('\n\t\t\t\t');
end
end
missingMEGMessage=missingMEGMessage+1;
if ~strncmp(balanceType(2,:), balanceOptions(5,:), 4)
if missingMEGMessage==10*round(missingMEGMessage/10)
fprintf('\n\t\t\t\t');
end
fprintf(' %s',MEGname);
end
betaMEG(:,n)=zeros(nRef,1);
end
end % End of loop over m (ds.res4.scrr table)
end % End of loop over MEG sensors
if missingMEGMessage>0;fprintf('\n');end
if common_mode_only
if size(betaMEG,1)>3 & nMEG>0
betaMEG=betaMEG(1:3,:);
Refindex=Refindex(1:3);
end
if size(betaGref,1)>3 & nGref>0
betaGref=betaGref(1:3,:);
Gbalanceindex=Gbalanceindex(1:3);
end
end
return
|
github
|
philippboehmsturm/antx-master
|
writeCTFds.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/ctf/writeCTFds.m
| 68,946 |
utf_8
|
96615f4833d69490d5b3e47f6f86c538
|
function ds=writeCTFds(datasetname,ds,data,unit);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% This program creates datasets that can be analyzed by CTF software. %
% %
% Datasets created by this program MUST NOT BE USED FOR CLINICAL APPLICATIONS. %
% %
% Please do not redistribute it without permission from VSM MedTech Ltd. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Author : Harold Wilson
% Version 1.3 5 October 2007 Spelling errors in some variables corrected.
% Version 1.2 24 April 2007 Modified to write both MEG and fMEG .hc files.
% writeCTFds.m Version 1.1 Prepares a CTF-format data set. MATLAB to CTF conversion.
% Adds record of filter changes to hist and newds files.
% Adds no-clinical-use messages.
% Creates multiple meg4 files when the total size of the data array
% >536870910 elements.
% Operation :
% 1. User reads a data set using readCTFds and getTrial2.
% size(data)= [SAMPLES, CHANNELS, TRIALS].
% 2. After working on data in MATLAB, user adjusts ds structure to reflect changes.
% (writeCTFds will adjust the number of channels, channel names and trial structure.)
% 3. This program then creates a new CTF data set.
% datasetname must include the complete path description.
% If a data set with name datasetname already exists, writeCTFds will issue an error message.
% The new directory contains files for each field of structure ds. If the field is
% missing no file is created. If the field is empty, an empty file is created.
% Files default.* are not created by writeCTFds.
% 4. The following fields of structure ds.res4 are modified based on the size of array data :
% no_samples
% no_channels
% no_trials.
% If size(ds.res4.chanNames,1)<no_channels, additional channel names are created
% as required. The additional channels are called MXT%%%. It is assumed that
% there will be <1000 new channels.
% Inputs : datasetname : Output dataset including path. Extension '.ds' is optional.
% ds : Structure produced by readCTFds.
% data : MEG data array. size(data)=[no_samples no_channels no_trials]
% Array data may be single or double.
% unit : Determines the unit of the SQUID and EEG signals:
% If unit is missing or unit==[], the unit is set to 'fT'.
% 'ft' or 'fT' : Convert to fT (MEG), uV (EEG)
% 't' or 'T' : Convert to T (MEG), V (EEG)
% 'phi0' : Convert to phi0 (MEG), uV (EEG)
% 'int': Read plain integers from *.meg4-file
% Outputs : - ds : The ds structure of the output data set.
% - datasetout : the name of the output data set.
% - A data set. The .hz and .hz2 subdirectories are not included.
% Function calls
% Included in this listing:
% - check_senres: Does simple checks on the fields of the senres table.
% - writeHc: Creates the new .hc file
% - checkMrk: Checks structure ds.mrk to see if it is valid marker set.
% - writeEEG: Creates the new .EEG file.
% - writeBadSegments: Creates the new bad.segments file.
% - writeClassFile: Creates the new ClassFile.cls file.
% - writeVirtualChannels: Creates the new VirtualChannels file.
% - updateDescriptors: Adds non-clinical-use and creation software messages to
% infods, res4, newds and hist fields of ds.
% - updateHLC: Adds head-coil movement information to infods.
% - updateDateTime : Resets dattime fields of res4 and infods.
% - updateBandwidth: Resets bandwidth of newds and infods. Adds res4 filter
% description to ds.hist.
% - getArrayField : Extracts one field of a structure array to make it easier to
% manipulate.
% - writeMarkerFile: Creates the new MarkerFile.mrk file.
% - writeCPersist: Creates the new .acq and .infods files.
% Other calls:
% - writeRes4: Writes the new .res4 file.
% Output files are opened with 'w' permission and 'ieee-be' machine format in order
% to be compatible with the Linux acquisition and analysis software. Do not open files
% with 'wt' permission because this will add an extra char(13) byte at the end of each
% line of text.
persistent printWarning bandwidthMessage
delim=filesep;
if nargin==0 & nargout==0 % Print a version number
fprintf(['\twriteCTFds: Version 1.3 5 October 2007 ',...
'Creates v4.1 and v4.2 CTF data sets.\n',...
'\tCall: ds=writeCTFds(datasetname,ds,data,unit);\n',...
'\t\tdatasetname = Name of the new dataset including the path.\n',...
'\t\tds = Structure describing the new dataset (ds.hc must be v1.2 format).\n',...
'\t\tdata = data that will be written to the new dataset .meg4 file.\n',...
'\t\tunit = physical units of the data.\n\n']);
return
end
% Allowed 8-byte headers for res4 and meg4 files.
res4_headers=strvcat(['MEG41RS',char(0)],['MEG42RS',char(0)]);
meg4_headers=strvcat(['MEG41CP',char(0)],['MEG42CP',char(0)]);
maxMEG4Size=2^31; % Maximum MEG$ file in bytes. (Limit set by Linux software)
MAX_COILS=8; % Parameter that determines the size of the ds.res.senres structure.
lenSensorName=32; % Channel names must be 32 characters
printDefaultBandwidthMessage=0; % Print a message about default bandwidth?
default_flp=0.25; % Default is flp=0.25*ds.res4.sample_rate
clinicalUseMessage='NOT FOR CLINICAL USE';
creatorSoftware='writeCTFds'; % Added to .infods file
meg4ChunkSize=2^20; % Write new .meg4 file in chunks of 4*meg4ChunkSize bytes.
DATASET_HZ_UNKNOWN=round(2^31-1); % Peculiar requirement of DataEditor as of 23 Oct. 2006
if ~exist('clinicalUseMessage');
clinicalUseMessage=char([]);
end
% Check inputs
if nargin<3
fprintf(['\nwriteCTFds: Must supply inputs datasetname,ds,data. ',...
'Only %d input arguments are present.\n\n'],nargin);
ds=-1; % Force an error in the calling program.
return
end
% Check input argument unit. Convert unit to lower case.
if exist('unit')~=1
unit='ft'; % default
elseif isempty(unit)
unit='ft'; % default
elseif ischar(unit)
unit=lower(unit);
if ~strcmp(unit,'int') & ~strcmp(unit,'ft') & ~strcmp(unit,'t') & ~strcmp(unit,'phi0')
fprintf(['\nwriteCTFds : unit=%s Not a valid option. Must be ',...
'''fT'', ''T'', ''phi0'' or ''int''\n\n'],unit);
ds=-1; % Force an error in the calling program.
return
end
end
% Check argument type
if ~isstruct(ds) | ~isnumeric(data) | ~ischar(unit) | ~ischar(datasetname)
fprintf('\nwriteCTFds: Some of the inputs are the wrong type.\n');
whos datasetname ds data unit;
ds=-1;
return
elseif ~isfield(ds,'res4') | ~isfield(ds,'meg4')
fprintf('\nwriteCTFds: Fields res4 and meg4 must be present in structure ds.\n\n');
ds % List the fields of structure ds.
ds=-1; % Force an error in the calling program.
return
end
% Refuse to write a data set with balanced reference gradiometers.
balancedGref=0;
for k=1:ds.res4.no_channels
balancedGref=(ds.res4.senres(k).sensorTypeIndex==1 & ds.res4.senres(k).grad_order_no~=0);
end
if balancedGref
fprintf('\nwriteCTFds: ds.res4.senres indicates balanced reference gradiometers.\n\n');
ds=-1; % Force an error in the calling program.
return
end
clear k balancedGref;
% Separate datasetname into a path and the baseName
datasetname=deblank(datasetname);
ksep=max([0 findstr(datasetname,delim)]);
baseName=datasetname((ksep+1):length(datasetname));
path=datasetname(1:ksep); % String path is terminated by the file delimiter (or path=[]).
% Remove the last .ds from baseName.
kdot=max(findstr(baseName,'.ds'));
if kdot==(length(baseName)-2)
baseName=baseName(1:(max(kdot)-1));
else
datasetname=[datasetname,'.ds'];
end
clear ksep kdot;
% Save the name already in structure ds, and change to the new datset name.
if isfield(ds,'baseName')
olddatasetname=[ds.baseName,'.ds'];
if isfield(ds, 'path')
olddatasetname=[ds.path,olddatasetname];
end
else
olddatasetname=' None ';
end
ds.path=path;
ds.baseName=baseName;
% Does the dataset already exist?
if exist(datasetname)==7
fprintf('\nwriteCTFds: Dataset %s already exists. Use a different name.\n\n',...
datasetname);
ds=-1; % Force an error in the calling program.
return
end
if size(ds.res4.chanNames,2)~=lenSensorName
fprintf(['\nwriteCTFds : size(ds.res4.chanNames)=[%d %d] ? Must ',...
'have %d-character channel names.\n\n'],size(ds.res4.chanNames),lenSensorName);
ds=-1;
return
end
% Check that the channel names have a sensor-file identification extensions.
% If it is missing, print a warning message.
% Sensor type indices : SQUIDs (0:7), ADCs (10), DACs(14), Clock (17), HLC (13,28,29)
% See Document CTF MEG File Formats (PN 900-0088), RES4 File Format/
for index=[0:7 10 13 14 17 28 29]
for k=find([ds.res4.senres.sensorTypeIndex]==index);
if isempty(strfind(ds.res4.chanNames(k,:),'-'))
fprintf(['writeCTFds: Channel %3d %s No sensor-file identification.',...
' (''-xxxx'' appended to channel name).\n',...
'\t\tSome CTF software may not work with these channel names.\n'],...
k,deblank(ds.res4.chanNames(k,:)));
break;
end
end
if isempty(strfind(ds.res4.chanNames(k,:),'-'));break;end
end
clear index k chanName;
% Update the data description in the ds.res4 structure.
[nSample, nChan, trials]=size(data);
% Update ds.res4 fields to match the size of array data.
ds.res4.no_trials=trials;
ds.res4.no_channels=nChan;
ds.res4.no_samples=nSample;
ds.res4.epoch_time=nSample*trials/ds.res4.sample_rate;
% Check if channels have been added or removed from array data.
[no_chanNames len_chanNames]=size(ds.res4.chanNames);
if no_chanNames<nChan
% Assume that new channel are at the end of the data set. Add a fake extension.
for kx=1:(nChan-no_chanNames)
ds.res4.chanNames=...
strvcat(ds.res4.chanNames,['MXT' num2str(kx,'%3.3d') '-0001' char(0)]);
end
fprintf('\tAdded %d SQUID channels to the end of ds.res4.chanNames table.\n',...
nChan-no_chanNames);
elseif no_chanNames>nChan
fprintf(['\nlength(chanNames)=%d, but only %d channels of data. ',...
'writeCTFds cannot tell which channel names to remove.\n\n'],no_chanNames,nChan);
ds=-1;
return
end
clear no_chanNames len_chanNames;
% The senres table may have been changed, especially if channels are added or removed.
% Check structure senres, print error messages, and possibly fix the errors.
[ds.res4.senres,status]=check_senres(ds.res4.senres,ds.res4.no_channels);
if status<0;ds=-1;return;end
clear status;
% Check that ds.res4.numcoef is the size of structure array ds.res4.scrr.
if isfield(ds.res4,'scrr')
if ~isequal(size(ds.res4.scrr,2),ds.res4.numcoef)
fprintf('Error in ds.res4: ds.res4.numcoef=%d, but size(ds.res4.scrr)=[',...
ds.res4.numcoef);
fprintf(' %d',size(ds.res4.scrr));fprintf('] ?\n');
return
end
elseif ds.res4.numcoef~=0
fprintf(['Error in ds.res4: ds.res4.numcoef=%d,',...
' but scrr is not a field of ds.res4\n'],ds.res4.numcoef);
return
end
% Before converting data to integers, save HLC channels for motion analysis in function
% make_new_infods. Pass HLCdata to function make_new_infods
if isempty(strmatch('HLC',ds.res4.chanNames))
HLCdata=[];
else
% Make a list of head-coil channels
coil=0;
HLClist=[];
while ~isempty(strmatch(['HLC00',int2str(coil+1)],ds.res4.chanNames))
coil=coil+1;
for k=1:3
HLClist=[HLClist strmatch(['HLC00',int2str(coil),int2str(k)],ds.res4.chanNames)];
end
end
HLCdata=reshape(double(data(:,HLClist,:)),ds.res4.no_samples,3,coil,ds.res4.no_trials);
clear coil k HLClist;
end
% Convert data to integers because CTF data sets are stored as raw numbers and
% not as physical qunatities. The res4 file contains the calibrations for
% converting back to physical units. Array data may be single precision, so
% convert to double before doing any adjustments to the data.
% Already checked that unit is valid.
if strcmp(unit,'int')
data=reshape(data,nSample,nChan*trials);
for k=1:nChan*trials
if strcmp(class(data),'single')
data(:,k)=single(round(double(data(:,k))));
else
data(:,k)=round(double(data(:,k)));
end
end
data=reshape(data,nSample,nChan,trials);
clear k;
else
for chan=1:nChan % Convert EEGs from uV to V, SQUIDs from fT to T
SQUIDtype=any(ds.res4.senres(chan).sensorTypeIndex==[0:7]);
EEGtype=any(ds.res4.senres(chan).sensorTypeIndex==[8 9]);
if EEGtype & (strcmp(unit,'ft') | strtcmp(unit,'phi0'))
alphaG=1e-6;
elseif SQUIDtype & strcmp(unit,'ft')
alphaG=1e-15;
elseif SQUIDtype & strcmp(unit,'phi0')
alphaG=1./(ds.res4.senres(chan).properGain*ds.res4.senres(chan).ioGain);
else
alphaG=1;
end
% Convert from physical units to integers using the gains in the senres table.
for kt=1:trials
buff=round(double(data(:,chan,kt))*(alphaG*...
(ds.res4.senres(chan).properGain*ds.res4.senres(chan).qGain*ds.res4.senres(chan).ioGain)));
if strcmp(class(data),'single')
data(:,chan,kt)=single(buff);
else
data(:,chan,kt)=buff;
end
end
end
clear chan alphaG SQUIDtype EEGtype buff kt;
end
% Create the output dataset
[status,msg]=mkdir(path,[baseName '.ds']);
if status==0 | ~isempty(msg)
fprintf('\nwriteCTFds: Failed to create directory.\n');
fprintf(' [status,msg]=mkdir(%s)\n',datasetname);
fprintf(' returns status=%d, msg=%s',status,msg);fprintf('\n\n');
ds=-1;
return
end
clear msg status;
% Write the data file (meg4 file). Check ds.meg4.header and make sure that
% the output .meg4 file has an acceptable header.
headerMessage=1;
if ~isfield(ds.meg4,'header'); % If ds.meg4.header is missing, add it.
nChar=length(deblank(meg4_headers(1,:)));
ds.meg4.header=[meg4_headers(1,1:min(7,nChar)) char(zeros(1,7-nChar))];
elseif isempty(strmatch(ds.meg4.header(1:7),meg4_headers(:,1:7),'exact'))
ds.meg4.header=meg4_headers(1,1:7);
else
headerMessage=0;
end
if headerMessage;
fprintf('writeCTFds: Set ds.meg4.header=%s\n',ds.meg4.header);
end
clear headerMessage;
if isempty(printWarning)
fprintf(['\nwriteCTFds: The data you are writing have been processed by software not\n',...
'\tmanufactured by VSM MedTech Ltd. and that has not received marketing clearance\n',...
'\tfor clinical applications. These data should not be later employed for clinical\n',...
'\tand/or diagnostic purposes.\n\n']);
printWarning=1;
end
% Write the meg4 file(s). If there are more than maxMEG4Size-8 bytes, then additional meg4
% files will be created.
% Convert data to a 1-D array
ndata=prod(size(data));
data=reshape(data,ndata,1);
ptsPerTrial=nSample*nChan;
maxPtsPerFile=ptsPerTrial*floor((maxMEG4Size-8)/(4*ptsPerTrial));
pt=0; % Last point written to the output file(s).
while pt<ndata
endPt=pt+min(ndata-pt,maxPtsPerFile);
if pt==0
meg4Ext='.meg4';
else
meg4Ext=['.',int2str(floor(pt/maxPtsPerFile)),'_meg4'];
end
fidMeg4=fopen([path,baseName,'.ds',delim,baseName,meg4Ext],'w','ieee-be');
fwrite(fidMeg4,[ds.meg4.header(1:7),char(0)],'uint8');
while pt<endPt
pt1=min(pt+meg4ChunkSize,endPt); % Convert to double in case data is
fwrite(fidMeg4,double(data((pt+1):pt1)),'int32'); % is single and write in short
pt=pt1; % pieces.
end
fclose(fidMeg4);
end
% Update the .meg4 part of structure ds.
ds.meg4.fileSize=4*ndata+8*(1+floor(ndata/maxPtsPerFile));
clear data pt pt1 ndata fidMeg4 ptsPerTrial maxPtsPerFile meg4Ext;
% Add dataset names to .hist
if ~isfield(ds,'hist');ds.hist=char([]);end
ds.hist=[ds.hist char(10) char(10) datestr(now) ' :' char(10) ...
' Read into MATLAB as data set ' olddatasetname char(10) ...
' Rewritten by writeCTFds as data set ' datasetname char(10)];
% If infods doesn't exist or is empty create it.
if ~isfield(ds,'infods');ds.infods=[];end
if isempty(ds.infods)
ds.infods=make_dummy_infods(isfield(ds,'hc'),~isempty(HLCdata),ds.res4.sample_rate);
end
% Update text fields of res4,infods, newds and hist.
ds=updateDescriptors(ds,clinicalUseMessage,creatorSoftware);
% Add HLC data to infods
ds.infods=updateHLC(ds.infods,HLCdata);
% Analyze structure array ds.res4.filters to make text info for .hist file and
% bandwidth parameters for .newds file.
fhp=0; % High-pass cutoff assuming no filters
flp=default_flp*ds.res4.sample_rate; % Assumed lowpass cutoff. SHOULD THIS BE CHANGED?
if isempty(bandwidthMessage) & printDefaultBandwidthMessage
fprintf('writeCTFds: Lowpass filter set to flp=%0.2f*sample_rate\n',default_flp);
bandwidthMessage=1;
end
ds=updateBandwidth(ds,fhp,flp);
% Update date/time fields of infods and res4
ds=updateDateTime(ds);
% Create the .res4 file in the output dataset.
ds.res4=writeRes4([path,baseName,'.ds',delim,baseName,'.res4'],ds.res4,MAX_COILS);
if ds.res4.numcoef<0
fprintf('\nwriteCTFds: writeRes4 returned ds.res4.numcoef=%d (<0??)\n\n',...
ds.res4.numcoef);
% Kill the output dataset.
rmdir([path,baseName,'.ds'],'s');
ds=-1;
return
end
% Create .hist file
histfile=[path,baseName,'.ds',delim,baseName,'.hist'];
fid=fopen(histfile,'w');
fwrite(fid,ds.hist,'uint8');
fclose(fid);
% New .newds file
if isfield(ds,'newds')
fid=fopen([path,baseName,'.ds',delim,baseName,'.newds'],'w');
fwrite(fid,ds.newds,'uint8');
fclose(fid);
end
% New infods file.
if isfield(ds,'infods')
writeCPersist([path,baseName,'.ds',delim,baseName,'.infods'],ds.infods);
end
% new hc file
if isfield(ds,'hc')
ds.hc=writeHc([path,baseName,'.ds',delim,baseName,'.hc'],ds.hc,HLCdata(:,:,1));
end
clear HLCdata;
% MarkerFile.mrk
if checkMrk(ds)
writeMarkerFile([path,baseName,'.ds',delim,'MarkerFile.mrk'],ds.mrk);
end
% .EEG
if isfield(ds,'EEG')
writeEEG([path,baseName,'.ds',delim,baseName,'.EEG'],ds.EEG);
end
% .acq
if isfield(ds,'acq');
% Check that ds.acq has the correct fields
if isfield(ds.acq,'name') & isfield(ds.acq,'type') & isfield(ds.acq,'data')
acqFilename=[path,baseName,'.ds',delim,baseName,'.acq'];
writeCPersist(acqFilename,ds.acq);
end
end
% bad.segments file
if isfield(ds,'badSegments')
writeBadSegments([path,baseName,'.ds',delim,'bad.segments'],ds.badSegments,...
ds.res4.no_trials,ds.res4.no_samples/ds.res4.sample_rate);
end
% BadChannels
if isfield(ds,'BadChannels');
if ischar(ds.BadChannels) & ~isempty(ds.BadChannels)
fid=fopen([path,baseName,'.ds',delim,'BadChannels'],'w','ieee-be');
for k=1:size(ds.BadChannels,1)
fprintf(fid,'%s\n',deblank(ds.BadChannels(k,:)));
end
fclose(fid);
end
end
% ClassFile
if check_cls(ds)
writeClassFile([path,baseName,'.ds',delim,'ClassFile.cls'],ds.TrialClass);
end
% VirtualChannels
if isfield(ds,'Virtual')
writeVirtualChannels([path,baseName,'.ds',delim,'VirtualChannels'],ds.Virtual);
end
% processing.cfg
if isfield(ds,'processing');
if ischar(ds.processing)
fid=fopen([datasetname,delim,'processing.cfg'],'w','ieee-be');
fwrite(fid,ds.processing,'uint8');
fclose(fid);
end
end
% Update the data set path and name
ds.path=path;
ds.baseName=baseName;
return
% *************** End of function writeCTFds ********************************************
% **************************************************************************************
% **************************************************************************************
% *************** Function check_senres **************************
function [senres,status]=check_senres(senres,numChan);
% A user may have augmented the senres table, so check that all the fields have the
% correct size. This will cause errors in programs that try to compute
% sensor response using the geometry in the senres table.
% Does "sanity" checks on the senres table. If there are obviously incorrect entries, it
% tries to fix them, and prints a message. If the senres table does not specify coil
% positions, orientations or areas, set them to zero, but give them the correct array
% size.
newChannelType=4; % Create the fake sensors as MEG magnetometers. This way offsets can be removed.
status=-1;
% Does the senres table have the correct no. of channels?
no_senres=length(senres);
if no_senres<numChan
% Add channels. Assume that they are gradiometers.
ioGain=1;
qGain=2^20;
gain=0.3;
properGain=1e15/(qGain*ioGain*gain); % sensor gain in phi0/fT
for kx=(no_senres+1):numChan
senres(kx)=struct(...
'sensorTypeIndex',newChannelType,'originalRunNum',0,'coilShape',0,...
'properGain',properGain,'qGain',qGain,'ioGain',ioGain,...
'ioOffset',0,'numCoils',1,...
'grad_order_no',0,...
'gain',gain,...
'pos0',zeros(3,1),'ori0',zeros(3,1),...
'area',0.1,'numturns',1,...
'pos',[0 0 21]','ori',zeros(3,1));
end
fprintf(['\tAdded %d SQUID channels to senres table. Nominal gain of each = ',...
'%8.4f fT/step\n'],numChan-no_senres,gain);
clear kx gain qGain ioGain properGain;
elseif no_senres>numChan
% Channels have been removed from the data set, but can't tell which elements of the
% senres table to remove.
fprintf(['length(senres)=%d, but only %d channels of data. writeCTFds can''t',...
' tell which channels to remove from senres table.\n'],no_senres,numChan);
return
end
no_senres=length(senres);
% Previous version of check_senres ensures that several fields had size [1 1].
% Seems unnecessary, so removed it.
for k=1:no_senres
% Check the fields that define pickup loops. Force the field defining the pickup
% loops to have the correct size. It is not clear why the EEG channels and
% the type=13,28,29 HLC channels need numCoils=1, and area>0.
if any(senres(k).sensorTypeIndex==[0:7]) % SQUID channels
correct_numCoils=rem(senres(k).sensorTypeIndex,4)+1;
elseif any(senres(k).sensorTypeIndex==[13 28 29]) % HLC channels
correct_numCoils=1;
elseif any(senres(k).sensorTypeIndex==[8 9]) % EEG channels
correct_numCoils=1;
else
correct_numCoils=0;
end
if senres(k).numCoils~=correct_numCoils & any(senres(k).sensorTypeIndex==[0:7])
fprintf('writeCTFds_test: senres(%d).sensorTypeIndex=%d but numCoils=%d??\n',...
k,senres(k).sensorTypeIndex,senres(k).numCoils);
fprintf(' Set numCoils=%d\n',correct_numCoils);
senres(k).numCoils=correct_numCoils;
end
numCoils=senres(k).numCoils;
if size(senres(k).pos0)~=[3 numCoils];pos0=zeros(3,numCoils);end
if size(senres(k).ori0)~=[3 numCoils];ori0=zeros(3,numCoils);end
if size(senres(k).pos)~=[3 numCoils];pos=zeros(3,numCoils);end
if size(senres(k).ori)~=[3 numCoils];ori=zeros(3,numCoils);end
if size(senres(k).numturns)~=[1 numCoils];numturns=zeros(1,numCoils);end
if size(senres(k).area)~=[1 numCoils];area=zeros(3,numCoils);end
end
status=1;
return
% ************* End of function check_senres*********************************************
% **************************************************************************************
% **************************************************************************************
% ************* function make_dummy_infods*********************************************
function Tag=make_dummy_infods(exist_hc,exist_HLC,sample_rate);
% If the user does not supply ds.infos, this code makes a dummy version. It has all of
% the tags that Acq created in file Richard_SEF_20060606_04.infods.
% ***********************************************************************************
% ***********************************************************************************
DATASET_HZ_UNKNOWN=round(2^31-1); % Peculiar requirement of DataEditor as of 23 Oct. 2006
fprintf('writeCTDds (make_dummy_infods): Creating a dummy infods file with all the tags.\n');
Tag(1)=struct('name','WS1_','type',0,'data',[]);
Tag(length(Tag)+1)=struct('name','_PATIENT_INFO','type',2,'data',[]);
Tag(length(Tag)+1)=struct('name','WS1_','type',0,'data',[]);
Tag(length(Tag)+1)=struct('name','_PATIENT_UID','type',10,...
'data','2.16.124.113000.000000.00000000000000.000000000.00000000.0011');
Tag(length(Tag)+1)=struct('name','_PATIENT_NAME_FIRST','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_PATIENT_NAME_MIDDLE','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_PATIENT_NAME_LAST','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_PATIENT_ID','type',10,'data','x');
Tag(length(Tag)+1)=struct('name','_PATIENT_BIRTHDATE','type',10,'data','19500101000000');
Tag(length(Tag)+1)=struct('name','_PATIENT_SEX','type',5,'data',2);
Tag(length(Tag)+1)=struct('name','_PATIENT_PACS_NAME','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_PATIENT_PACS_UID','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_PATIENT_INSTITUTE','type',10,'data','');
Tag(length(Tag)+1)=struct('name','EndOfParameters','type',-1,'data',[]);
Tag(length(Tag)+1)=struct('name','_PROCEDURE_INFO','type',2,'data',[]);
Tag(length(Tag)+1)=struct('name','WS1_','type',0,'data',[]);
Tag(length(Tag)+1)=struct('name','_PROCEDURE_VERSION','type',5,'data',1);
Tag(length(Tag)+1)=struct('name','_PROCEDURE_UID','type',10,...
'data','2.16.124.113000.000000.00000000000000.000000000.00000000.0041');
Tag(length(Tag)+1)=struct('name','_PROCEDURE_ACCESSIONNUMBER','type',10,'data','0');
Tag(length(Tag)+1)=struct('name','_PROCEDURE_TITLE','type',10,'data','0');
Tag(length(Tag)+1)=struct('name','_PROCEDURE_SITE','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_PROCEDURE_STATUS','type',5,'data',1);
Tag(length(Tag)+1)=struct('name','_PROCEDURE_TYPE','type',5,'data',2); % Research type
Tag(length(Tag)+1)=struct('name','_PROCEDURE_STARTEDDATETIME','type',10,...
'data','20060606164306');
Tag(length(Tag)+1)=struct('name','_PROCEDURE_CLOSEDDATETIME','type',10,...
'data','19000100000000');
Tag(length(Tag)+1)=struct('name','_PROCEDURE_COMMENTS','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_PROCEDURE_LOCATION','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_PROCEDURE_ISINDB','type',5,'data',0);
Tag(length(Tag)+1)=struct('name','EndOfParameters','type',-1,'data',[]);
Tag(length(Tag)+1)=struct('name','_DATASET_INFO','type',2,'data',[]);
Tag(length(Tag)+1)=struct('name','WS1_','type',0,'data',[]);
Tag(length(Tag)+1)=struct('name','_DATASET_VERSION','type',5,'data',2);
Tag(length(Tag)+1)=struct('name','_DATASET_UID','type',10,...
'data','2.16.124.113000.000000.00000000000000.000000000.00000000.0042');
Tag(length(Tag)+1)=struct('name','_DATASET_PATIENTUID','type',10,...
'data','2.16.124.113000.000000.00000000000000.000000000.00000000.0011');
Tag(length(Tag)+1)=struct('name','_DATASET_PROCEDUREUID','type',10,...
'data','2.16.124.113000.000000.00000000000000.000000000.00000000.0041');
Tag(length(Tag)+1)=struct('name','_DATASET_STATUS','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_DATASET_RPFILE','type',10,'data','default.rp');
Tag(length(Tag)+1)=struct('name','_DATASET_PROCSTEPTITLE','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_DATASET_PROCSTEPPROTOCOL','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_DATASET_PROCSTEPDESCRIPTION','type',10,...
'data','');
Tag(length(Tag)+1)=struct('name','_DATASET_COLLECTIONDATETIME','type',10,...
'data','Unknown');
Tag(length(Tag)+1)=struct('name','_DATASET_COLLECTIONSOFTWARE','type',10,...
'data','Acq ');
Tag(length(Tag)+1)=struct('name','_DATASET_CREATORDATETIME','type',10,...
'data',sprintf('%d',floor(clock)));
Tag(length(Tag)+1)=struct('name','_DATASET_CREATORSOFTWARE','type',10,...
'data','Acq ');
Tag(length(Tag)+1)=struct('name','_DATASET_KEYWORDS','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_DATASET_COMMENTS','type',10,...
'data','Dummy infods.');
Tag(length(Tag)+1)=struct('name','_DATASET_OPERATORNAME','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_DATASET_LASTMODIFIEDDATETIME','type',10,...
'data',sprintf('%d',floor(clock)));
if exist_hc
nominalPositions=0; % Measured
else
nominalPositions=1; % Nominal
end
Tag(length(Tag)+1)=struct('name','_DATASET_NOMINALHCPOSITIONS','type',5,...
'data',nominalPositions);
Tag(length(Tag)+1)=struct('name','_DATASET_COEFSFILENAME','type',10,...
'data','ds.res4.scrr');
Tag(length(Tag)+1)=struct('name','_DATASET_SENSORSFILENAME','type',10,...
'data','ds.res4.senres');
%Tag(length(Tag)+1)=struct('name','_DATASET_COEFSFILENAME','type',10,...
% 'data','/opt/ctf-5.1/hardware/M015/M015_1609.coef');
%Tag(length(Tag)+1)=struct('name','_DATASET_SENSORSFILENAME','type',10,...
% 'data','/opt/ctf-5.1/hardware/M015/M015_1609.sens');
Tag(length(Tag)+1)=struct('name','_DATASET_SYSTEM','type',10,'data','DSQ-2010');
Tag(length(Tag)+1)=struct('name','_DATASET_SYSTEMTYPE','type',10,'data','Untitled');
Tag(length(Tag)+1)=struct('name','_DATASET_LOWERBANDWIDTH','type',4,'data',0);
Tag(length(Tag)+1)=struct('name','_DATASET_UPPERBANDWIDTH','type',4,'data',...
round(0.25*sample_rate));
Tag(length(Tag)+1)=struct('name','_DATASET_ISINDB','type',5,'data',0);
if exist_HLC
HZ_MODE=5;
elseif exist_hc
HZ_MODE=1;
else
HZ_MODE=DATASET_HZ_UNKNOWN;
end
Tag(length(Tag)+1)=struct('name','_DATASET_HZ_MODE','type',5,'data',HZ_MODE);
Tag(length(Tag)+1)=struct('name','_DATASET_MOTIONTOLERANCE','type',4,'data',0.005);
Tag(length(Tag)+1)=struct('name','_DATASET_MAXHEADMOTION','type',4,'data',0.005);
Tag(length(Tag)+1)=struct('name','_DATASET_MAXHEADMOTIONTRIAL','type',7,'data',0);
Tag(length(Tag)+1)=struct('name','_DATASET_MAXHEADMOTIONCOIL','type',10,'data','1');
Tag(length(Tag)+1)=struct('name','EndOfParameters','type',-1,'data',[]);
Tag(length(Tag)+1)=struct('name','EndOfParameters','type',-1,'data',[]);
return
% ************* End of function make_dummy_infods*********************************************
% **************************************************************************************
% **************************************************************************************
% ************* Function writeHc*********************************************
function hc=writeHc(hcFileName,hc,HLCdata);
% Modified for v1.2 ds.hc structures. ds.hc.names has the exact, complete names of the
% head coils. The coordinates relative to the subject may be ds.hc.head(MEG) OR
% ds.hc.abdomen (fMEG).
% Creates a .hc file in a CTF dataset
% Inputs: hcFileName : Complete name of .hc file including path, basename and .hc ext.
% hc : structure with nasion, left, right head coil positions in dewar and
% CTF head coordinates.
% HLCdata : head coil locations at the start of 1st trial. unit=m
% coordinates=dewar. Used only if structure hc is empty and it is MEG
% data (not fMEG data).
% Output : hc : hc structure. hc=struct([]) on failure. hc is set to the coil positions
% in array HLCdata if hc=[] on entry.
% Check inputs
if exist('hc')~=1
hc=struct([]);
elseif ~isstruct(hc)
hc=struct([]);
end
hcfields=fieldnames(hc);
if exist('HLCdata')~=1
HLCdata=[];
elseif ~isnumeric(HLCdata) | size(HLCdata,1)~=3 | size(HLCdata,2)<3
HLCdata=[];
end
% Check hc Filename
if exist('hcFileName')~=1;hcFileName=char([]);end
if ~ischar(hcFileName) | isempty(hcFileName)
fprintf('writeCTFds (writeHc): Called writeHc with bad file name.\n');
hcFileName
return
end
% Both hc and HLCdata bad?
if length(hcfields)~=4 & isempty(HLCdata)
fprintf('writeCTFds (writeHc): Called writeHc with bad hc and bad HLCdata.\n');
hc=struct([])
return
elseif length(hcfields)~=4
rstandard=8/sqrt(2)*[1 1 0;-1 1 0;1 -1 0]';
rstandard(3,:)=-27;
rdewar=100*HLCdata(:,1:3);
% Convert from dewar coordinates to CTF head coordinates.
originCTF=0.5*(hc.dewar(:,2)+hc.dewar(:,3));
% Unit vectors for the CTF coordinates
uCTF(:,1)=hc.dewar(:,1)-originCTF;
uCTF(:,3)=cross(uxCTF,hc.dewar(:,2)-hc.dewar(:,3));
uCTF(:,2)=cross(uCTF(:,3),uCTF(:,1));
uCTF=uCTF./(ones(3,1)*sqrt(sum(uCTF.^2,1)));
rCTF=uCTF'*(rdewar-originCTF*ones(1,3))
hc=struct('names',strvcat('nasion','left ear','right ear'),...
'standard',rstandard,'dewar',rdewar,'head',rCTF);
clear originCTF uCTF rstandard rdewar rCTF;
end
% Character strings for generating the .hc text file
% Should never have both 'head' and 'abdomen' fields.
labelword=strvcat('standard','measured','measured');
printField=[strmatch('standard',hcfields) strmatch('dewar',hcfields) ...
strmatch('head',hcfields) strmatch('abdomen',hcfields)];
if ~strmatch('names',hcfields) | length(printField)~=3
fprintf(['writeCTFds (writeHc): Structure hc does not have all of the required fields.\n',...
' No .hc file will appear in the output dataset.\n']);
hc;
hc=struct([]);
return
end
relative=strvcat('dewar','dewar',hcfields{printField(3)});
coilcoord=strvcat('standard','dewar',hcfields{printField(3)});
comp='xyz';
coilname=hc.names;
fid=fopen(hcFileName,'w','ieee-be');
for k=1:size(coilcoord,1)
rcoil=getfield(hc,coilcoord(k,:));
for coil=1:size(hc.names,1)
clName=deblank(hc.names(coil,:));
fwrite(fid,[labelword(k,:) ' ' clName ' coil position relative to ',...
deblank(relative(k,:)) ' (cm):' char(10)],'uint8');
for m=1:3
fwrite(fid,[char(9) comp(m) ' = ' num2str(rcoil(m,coil),'%7.5f') char(10)],'uint8');
end
end
end
fclose(fid);
status=0;
return
% ************* End of function writeHc*********************************************
% **************************************************************************************
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%Function checkMrk %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function MarkerFileOK=checkMrk(ds);
% Examines structure ds to see if a sensible MarkerFile can be created from ds.mrk.
% Output: MarkerFileOK=1 : ds.mrk looks OK
% MarkerFileOK=0 : ds.mrk cannot be a set of valid markers for these data.
MarkerFileOK=isfield(ds,'mrk');
if MarkerFileOK
MarkerFileOK=~isempty(ds.mrk);
end
if MarkerFileOK
% Are the markers appropriate?
minMarkerTrial=[];
minMarkerTime=[];
maxMarkerTrial=[];
maxMarkerTime=[];
for k=1:length(ds.mrk)
maxMarkerTrial=max([maxMarkerTrial max(ds.mrk(k).trial)]);
maxMarkerTime=max([maxMarkerTime max(ds.mrk(k).time)]);
minMarkerTrial=min([minMarkerTrial min(ds.mrk(k).trial)]);
minMarkerTime=min([minMarkerTime min(ds.mrk(k).time)]);
end
if isempty(maxMarkerTrial) | isempty(maxMarkerTime)
MarkerFileOK=0; % Do not create MarkerFile.mrk if all of the marker classes are empty.
else
MarkerFileOK=(maxMarkerTrial<=ds.res4.no_trials & minMarkerTrial>=1 & ...
maxMarkerTime<=(ds.res4.no_samples/ds.res4.sample_rate) & ...
minMarkerTime>=(-ds.res4.preTrigPts/ds.res4.sample_rate));
if ~MarkerFileOK
fprintf(['\nwriteCTFds (checkMrk): ds.mrk cannot possibly be a set of markers ',...
'for array(data).\n']);
fprintf([' minMarkerTrial=%d (must be >=1) ',...
'maxMarkerTrial=%d (must be <=%d)\n'],...
minMarkerTrial,maxMarkerTrial,ds.res4.no_trials);
fprintf([' minMarkerTime=%7.4f (must be >=%7.4f) ',...
'maxMarkerTrial=%7.4f (must be <=%7.4f )\n'],...
minMarkerTime,-ds.res4.preTrigPts/ds.res4.sample_rate,...
maxMarkerTime,ds.res4.no_samples/ds.res4.sample_rate);
fprintf(' MarkerFile.mrk will not be created.\n\n');
end
end
end
return
%%%%%%%%%%%%%% end of checkMrk %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%% Function writeEEG %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function writeEEG(eegFileName,EEG);
% Reads the EEG file of a dtaset and stores the infoemation in strucure array EEG.
% EEG(k).chanName = channel name in the dataset (EEGmmm where mmm=channel number)
% EEG(k).name = channel name given by the user (e.g. Fp4)
% EEG(k).pos = electrode position in cm in CTF head coordinates
% Check inputs
if exist('eegFileName')~=1;eegFileName=char([]);end
if ~ischar(eegFileName) | isempty(eegFileName)
fprintf('writeCTFds (writeEEG): Called writeEEG with bad file name.\n');
eegFileName
EEG=struct([]);
end
if exist('EEG')~=1
EEG=struct([]);
elseif ~isstruct(EEG)
EEG=struct([]);
end
if isempty(EEG);return;end
fid=fopen(eegFileName,'w','ieee-be');
if fid<0
fprintf('writeCTFds (writeEEG): Could not open file %s\n',eegFileName);
return
end
nEEG=length(EEG);
for k=1:nEEG
fprintf(fid,'%d\t%s\t%7.5f\t%7.5f\t%7.5f\n',EEG(k).chanNum,EEG(k).name,EEG(k).pos);
end
fclose(fid);
return
%%%%%%%%% End of writeEEG %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%% Function writeBadSegments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function writeBadSegments(badSegmentsFile,badSegments,nTrial,tTrial);
% Creates a bad.segements file in a CTF data set from the information in structure
% badSegments which is created by read_badSegments, or by the user.
% If structure badSegments is empty, then the file is not created.
% badSegments structure:
% badSegments.trial = List of trial numbers
% badSegments.StartTime = List of bad segment start times (relative to trial).
% badSegments.EndTime = List of bad segment end times.
% Check badSegmentsFile
if exist('badSegmentsFile')~=1;badSegmentsFile=char([]);end
if isempty(badSegmentsFile) | ~ischar(badSegmentsFile)
fprintf('writeCTFds(writeBadSegments): Bad file name.\n');
badSegmentsFile
return
end
% Check that structure badSegments is defined correctly
if exist('badSegments')~=1 | exist('nTrial')~=1
return
elseif ~isstruct(badSegments) | isempty(badSegments)
return
elseif ~isfield(badSegments,'trial') | ~isfield(badSegments,'StartTime') | ...
~isfield(badSegments,'EndTime')
return
elseif isempty(badSegments.trial) | isempty(badSegments.StartTime) | ...
isempty(badSegments.EndTime)
return
elseif ~isequal(size(badSegments.trial),size(badSegments.StartTime),...
size(badSegments.EndTime))
fprintf(['\nwriteCTFds (writeBadSegments): ',...
'The fields of structure badSegments do not all have the same size.\n']);
return
elseif any(badSegments.trial>nTrial) | any(badSegments.trial<1) | ...
any(badSegments.EndTime>tTrial)
fprintf(['\nwriteCTFds (writeBadSegments): ds.badSegments cannot possibly describe ',...
'bad segments for these data.\n',...
'\tmin(badSegments.trial)=%d max(badSegments.trial)=%d ',...
'max(badSegments.EndTime)=%0.4f s\n\t\tDataset: nTrial=%d tTrial=%0.4f s\n'],...
min(badSegments.trial),max(badSegments.trial),max(badSegments.EndTime),...
nTrial,tTrial);
fprintf('\t\tbad.segments file will not be created.\n\n');
return
end
% Convert all fields to simple vectors
nSeg=prod(size(badSegments.trial));
trial=reshape(badSegments.trial,1,nSeg);
StartTime=reshape(badSegments.StartTime,1,nSeg);
EndTime=reshape(badSegments.EndTime,1,nSeg);
fid=fopen(badSegmentsFile,'w','ieee-be');
if fid<0
fprintf('writeCTFds (writeBadSegments): Could not open file %s\n',badSegmentsFile);
return
end
% Extra tabs are inserted to reproduce the format of bad.segments files produced by
% DataEditor (5.3.0-experimental-linux-20060918).
fprintf(fid,'%0.6g\t\t%0.6g\t\t%0.6g\t\t\n',[trial;StartTime;EndTime]);
fclose(fid);
return
%%%%%%%%% End of writeBadSegments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%Function check_cls %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ClassFileOK=check_cls(ds);
% Examines structure ds to see if a sensible ClassFile can be created from ds.TrialClass.
ClassFileOK=isfield(ds,'TrialClass');
if ClassFileOK
ClassFileOK=~isempty(ds.TrialClass);
end
if ClassFileOK
% Are the class trials appropriate?
minClassTrial=[];
maxClassTrial=[];
for k=1:length(ds.TrialClass)
maxClassTrial=max([maxClassTrial max(ds.TrialClass(k).trial)]);
minClassTrial=min([minClassTrial min(ds.TrialClass(k).trial)]);
end
% Create ClassFile.cls even when the trail classes are empty.
if ~isempty(maxClassTrial)
ClassFileOK=(maxClassTrial<=ds.res4.no_trials & minClassTrial>=1);
if ~ClassFileOK
fprintf(['\nwriteCTFds (check_cls): ds.TrialClass cannot possibly be a set of ',...
'trial classes for array(data).\n minClassTrial=%d (must be >=1) ',...
'maxClassTrial=%d (must be <=%d)\n'],...
minClassTrial,maxClassTrial,ds.res4.no_trials);
fprintf(' ClassFile.cls will not be created.\n');
end
end
end
return
%%%%%%%%%%%%%% end of check_cls %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%% Function writeClassFile %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function writeClassFile(ClassFile,TrialClass);
% Write the ClassFile of a CTF data set.
% The CLassFile allows a user to store a list of trial classifications in a data set.
% The ClassFile format is defined in document CTF MEG File Formats, PN900-0088.
% This format is rigid.
% Inputs :
% ClassFile : marker file including the full path and extension .mrk.
% TrialClass : Structure creted by read_ClassFile.
% Output : ClassFile.cls.
% Check input TrialClass.
if exist('TrialClass')~=1;TrialClass=[];end
if isempty(TrialClass) | ~isstruct(TrialClass)
fprintf('writeCTFds (writeClassFile): TrialClass is empty or is not a structure.\n');
TrialClass
return
end
% Check ClassFile
if exist('ClassFile')~=1;ClassFile=char([]);end
if isempty(ClassFile) | ~ischar(ClassFile)
fprintf('writeCTFds (writeClassFile): Bad file name.\n');
ClassFile
end
fid=fopen(ClassFile,'w','ieee-be');
if fid<0
fprintf('writeCTFds (writeClassFile): Could not open file %s\n',ClassFile);
return
end
nClass=length(TrialClass);
% Generate datasetname from ClassFIle.
ksep=max([0 strfind(ClassFile,filesep)]);
datasetname=ClassFile(1:ksep-1);
if isempty(datasetname);datasetname=cd;end
fprintf(fid,'PATH OF DATASET:\n%s\n\n\n',datasetname);
fprintf(fid,'NUMBER OF CLASSES:\n%d\n\n\n',nClass);
for k=1:nClass
if k==1 % Add sign character to make output match the output of Acq.
sgn=char([]); % There should be no real significance to this.
else % Why does DataEditor places the + sign only on ClassID 2,3,...?
sgn='+';
end
No_of_Trials=prod(size(TrialClass(k).trial));
fprintf(fid,'CLASSGROUPID:\n%s%d\nNAME:\n%s\nCOMMENT:\n%s\n',...
sgn,TrialClass(k).ClassGroupId,TrialClass(k).Name,TrialClass(k).Comment);
fprintf(fid,'COLOR:\n%s\nEDITABLE:\n%s\nCLASSID:\n%s%d\nNUMBER OF TRIALS:\n%d\n',...
TrialClass(k).Color,TrialClass(k).Editable,sgn,TrialClass(k).ClassId,No_of_Trials);
fprintf(fid,'LIST OF TRIALS:\nTRIAL NUMBER\n');
% Subtract one so trial numbering starts at 0 in ClassFile.cls
fprintf(fid,'%20d\n',reshape(TrialClass(k).trial,1,No_of_Trials)-1);
fprintf(fid,'\n\n');
end
fclose(fid);
return
%%%%%%%%%%%%%% end of writeClassFile %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%% Function writeVirtualChannels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function writeVirtualChannels(VirtualChannelsFile,Virtual);
% Writes a VirtualChannels file using the information in structure Virtual.
% S\tructure Virtual is prepared by read_VirtualChannels
% Check VirtualChannelsFile
if exist('VirtualChannelsFile')~=1;VirtualChannelsFile=char([]);end
if isempty(VirtualChannelsFile) | ~ischar(VirtualChannelsFile)
fprintf('write_VirtualChannelsFile: Bad file name.\n');
VirtualChannelsFile
return
end
% Check structure array Virtual
if exist('Virtual')~=1
fprintf('writeVirtualChannels: Must specify structure Virtual.\n');
return
elseif isempty(Virtual) | ~isstruct(Virtual)
return
elseif ~isfield(Virtual,'Name') | ~isfield(Virtual,'wt');
return
elseif isempty(Virtual(1).Name)
return
end
fid=fopen(VirtualChannelsFile,'w','ieee-be');
if fid<0
fprintf('writeCTFds (writeVirtualChannels): Could not open file %s\n',VirtualChannelsFile);
return
end
fprintf(fid,'//Virtual channel configuration\n\n');
for k=1:length(Virtual)
fprintf(fid,'VirtualChannel\n{\n\tName:\t%s\n\tUnit:\t%s\n',...
Virtual(k).Name,Virtual(k).Unit);
for q=1:size(Virtual(k).wt)
% Floating format chosen to match VirtualChanels file creatd by
% DataEditor (5.3.0-experimental-linux-20060918).
fprintf(fid,'\tRef:\t%s,%0.6g\n',deblank(Virtual(k).chan(q,:)),Virtual(k).wt(q));
end
fprintf(fid,'}\n\n');
end
fclose(fid);
return
%%%%%%%%%%%%%% end of writeVirtualChannels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%% Function updateDescriptors %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ds=updateDescriptors(ds,comment,creatorSoftware,HLCcntrl);
% Makes sure that certain tags are in structure infods, and makes sure that information
% is transfered to infods and newds from res4. Updates several fields of res4 with
% clinical use message (=comment) and name of creator program.
% Inputs: ds : ds structure produced by readCTFds.
% comment : Character string that is added to infods tags listed in addCommentTag
% and res4 fields listed in addCommentField
% creatorSoftware : Character string indicating that the data set was
% created by writeCTFds. Added to infods tags listed in addCreatorTag and
% appName field of res4.
% HLCcntrl: If ds.infods is missing or empty, HLCcntrl determines the
% _DATA_HZ_MODE tage of infods. if noit present or empty, HLCcntrl=0.
% Creates a dummy infods structure if necessary using function make_dummy_infods.
% Changes infods and newds to match information in
% ds.res4.nf_run_title
% ds.res4.collect_descriptor
% ds.res4.nf_subject_id
% ds.res4.nf_operator
% Adds comment (clinical use message) and creator software name to infods, newds and hist files.
if ~isfield(ds,'infods');ds.infods=[];end
% infods tags that will display the comment.
addCommentTag=strvcat('_PATIENT_ID','_PATIENT_INSTITUTE','_PROCEDURE_COMMENTS',...
'_DATASET_COMMENTS','_DATASET_STATUS','_DATASET_PROCSTEPTITLE');
% res4 text fields that will display the comment
addCommentField=strvcat('appName','dataOrigin','dataDescription',...
'nf_run_title','nf_subject_id','run_description');
% res4 text string lengths (from document "CTF MEG File Formats", PN900-0088)
addCommentLength=[256 256 256 256 32 -1]'; % -1 indicates variable length
% infods tags that will display the creator software.
addCreatorTag=strvcat('_PROCEDURE_COMMENTS','_DATASET_STATUS',...
'_DATASET_COLLECTIONSOFTWARE','_DATASET_CREATORSOFTWARE');
% res4 text fields that will display the creator software.
addCreatorField=strvcat('appName','run_description');
addCreatorLength=[256 -1]';
% List of infods tags that will be set to ds.res4.fields (not necessarily fields listed in
% addCommentField or addCreatorField
addRes4Tag=strvcat('_PATIENT_ID','_DATASET_PROCSTEPTITLE',...
'_DATASET_PROCSTEPDESCRIPTION','_DATASET_OPERATORNAME');
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Add the Tags to infods. In most cases they will already be there, but just to be sure.
addTag=strvcat(addRes4Tag,addCommentTag,addCreatorTag);
tagClass=strvcat('_PATIENT','_PROCEDURE','_DATASET');
% List of all the tag names as a character array
tagName=getArrayField(ds.infods,'name')';
if length(ds.infods)==1;tagName=tagName';end
tagType=getArrayField(ds.infods,'type');
tagPtr=1; % If a class is missing, inject the class starting at tagPtr+1.
for k=1:size(tagClass,1)
addIndex=strmatch(deblank(tagClass(k,:)),addTag)';
% Are there any tags to be added in this class?
if isempty(addIndex);continue;end
% List of infods tags in the tagClass, but excluding the CPerist type (which marks the
% start of a class.
infodsIndex=strmatch(deblank(tagClass(k,:)),tagName);
if isempty(infodsIndex) % Create a new class of tags.
if strcmp(deblank(tagName(tagPtr+1,:)),'EndOfParameters') & k>1;
tagPtr=tagPtr+1;
end
nTag=length(ds.infods);
tagName((tagPtr+4):(nTag+3),:)=tagName((tagPtr+1):nTag,:);
ds.infods((tagPtr+4):(nTag+3))=ds.infods((tagPtr+1):nTag);
ds.infods(tagPtr+1)=struct('name',[deblank(tagClass(k,:)),'_INFO'],'type',2,'data',[]);
ds.infods(tagPtr+2)=struct('name','WS1_','type',0,'data',[]);
ds.infods(tagPtr+3)=struct('name','EndOfParameters','type',-1,'data',[]);
tagName=strvcat(tagName(1:tagPtr,:),...
strvcat([deblank(tagClass(k,:)),'_INFO'],'WS1_','EndOfParameters'),...
tagName(tagPtr+1:nTag,:));
nTag=nTag+3;
tagPtr=tagPtr+2;
else
if ds.infods(max(infodsIndex)).type==2
tagPtr=max(infodsIndex)+1; % Class consists of no tags beyond the CPersist definition
else
tagPtr=max(infodsIndex); % Class contains at least one real tag.
end
clear infodsIndex;
end
for q=addIndex
if isempty(strmatch(deblank(addTag(q,:)),tagName))
tagName=strvcat(tagName(1:tagPtr,:),deblank(addTag(q,:)),tagName(tagPtr+1:nTag,:));
ds.infods((tagPtr+2):(nTag+1))=ds.infods((tagPtr+1):nTag);
ds.infods(tagPtr+1)=struct('name',deblank(addTag(q,:)),'type',10,'data',char([]));
tagPtr=tagPtr+1;
nTag=nTag+1;
end
end
end
clear k q nTag tagPtr infodsIndex addIndex;
% All of the tags in addTag have been added to ds.infods.
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if exist('creatorSoftware')~=1;
creatorSoftware=char([]);
elseif ~ischar(creatorSoftware)
creatorSoftware=char([]);
else
creatorSoftware=deblank(creatorSoftware);
end
if exist('comment')~=1;
comment=char([]);
elseif ~ischar(comment)
comment=char([]);
else
comment=deblank(comment);
end
tagName=getArrayField(ds.infods,'name')';
% Update the res4 fields : add creator message.
% Don't check field length, but truncate later.
for q=1:size(addCreatorField,1);
strng=deblank(getfield(ds.res4,deblank(addCreatorField(q,:))));
if isempty(strfind(strng,creatorSoftware))
newStrng=creatorSoftware;
if ~isempty(strng);newStrng=[strng ' ' newStrng];end
ds.res4=setfield(ds.res4,deblank(addCreatorField(q,:)),newStrng);
end
end
clear q strng nChar strng0 ns;
% Update the res4 fields : add comment (= clinical use message)
% Don't check field length, but truncate later.
for q=1:size(addCommentField,1);
strng=deblank(getfield(ds.res4,deblank(addCommentField(q,:))));
if isempty(strfind(strng,comment))
newStrng=comment;
if ~isempty(strng);newStrng=[strng ' ' newStrng];end
ds.res4=setfield(ds.res4,deblank(addCommentField(q,:)),newStrng);
end
end
clear strng newStrng q;
% Update res4.run_description
ds.res4.run_description=[ds.res4.run_description,char(0)];
ds.res4.rdlen=length(ds.res4.run_description);
% Update infods entries from .res4 fields
ds.infods(strmatch('_PATIENT_ID',tagName)).data=deblank(ds.res4.nf_subject_id);
ds.infods(strmatch('_DATASET_PROCSTEPTITLE',tagName)).data=deblank(ds.res4.nf_run_title);
ds.infods(strmatch('_DATASET_PROCSTEPDESCRIPTION',tagName)).data=...
deblank(ds.res4.nf_collect_descriptor);
ds.infods(strmatch('_DATASET_OPERATORNAME',tagName)).data=deblank(ds.res4.nf_operator);
% Truncate the .res4. fields. Leave room for a final char(0).
for q=1:size(addCreatorField,1);
strng=deblank(getfield(ds.res4,deblank(addCreatorField(q,:))));
if length(strng)>addCreatorLength(q)-1 & addCreatorLength(q)>0
ds.res4=setfield(ds.res4,deblank(addCreatorField(q,:)),...
strng(length(strng)+[-addCreatorLength(q)+2:0]));
end
end
for q=1:size(addCommentField,1);
strng=deblank(getfield(ds.res4,deblank(addCommentField(q,:))));
if length(strng)>addCommentLength(q)-1 & addCommentLength(q)>0
ds.res4=setfield(ds.res4,deblank(addCommentField(q,:)),...
strng(length(strng)+[-addCommentLength(q)+2:0]));
end
end
clear q strng;
% Add creator software to infods tags. Have already cheked that the tags are there.
for q=1:size(addCreatorTag,1)
if isempty(strmatch(deblank(addCreatorTag(q,:)),addRes4Tag))
k=strmatch(deblank(addCreatorTag(q,:)),tagName);
if length(k)==1
if isempty(strfind(ds.infods(k).data,creatorSoftware))
newStrng=creatorSoftware;
if ~isempty(deblank(ds.infods(k).data));
newStrng=[deblank(ds.infods(k).data) ' ' newStrng];
end
ds.infods(k).data=newStrng;
end
else
fprintf('writeCTFds: Tag %s appears %d times in ds.infods ??\n',...
deblank(addCreatorTag(q,:)),length(k));
end
end
end
clear q k;
% Add comment (clinical use statement) to ds.infods
for q=1:size(addCommentTag,1)
if isempty(strmatch(deblank(addCommentTag(q,:)),addRes4Tag))
k=strmatch(deblank(addCommentTag(q,:)),tagName);
if length(k)==1
if isempty(strfind(ds.infods(k).data,comment))
newStrng=comment;
if ~isempty(deblank(ds.infods(k).data));
newStrng=[deblank(ds.infods(k).data) ' ' newStrng];
end
ds.infods(k).data=newStrng;
end
else
fprintf(['writeCTFds (updateDescriptors): Tag %s appears %d times in ',...
'ds.infods ??\n'],deblank(addCommentTag(q,:)),length(k));
end
end
end
clear q k;
% Add the creator and comment information to the newds file
if isfield(ds,'newds');
nChar=length(ds.newds);
% Keyword positions
aNpos=max(strfind(ds.newds,[char(9) 'appName:' char(9)]));
if isempty(aNpos)
fprintf(['writeCTFds (update_decsriptors): Keyword ''appName'' ',...
'does not appear in ds.newds.\n',...
' set ds.newds=[].\n']);
ds.newds=char([]);
else
eol=max([11 min(strfind(ds.newds(aNpos+1:length(ds.newds)),char(10)))]);
ds.newds=[ds.newds(1:(aNpos+eol-1)) ' ' creatorSoftware ' ' comment ...
ds.newds((aNpos+eol):length(ds.newds))];
end
clear nChar aNpos eol;
end
% Add clinical use message to hist file.
if isfield(ds,'hist') & ~isempty(comment)
ds.hist=[ds.hist char(10) comment char(10)];
end
return
%%%%%%%%%%%%%% End of updateDescriptors %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%% Function updateHLC %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [infods,status]=updateHLC(infods,HLCdata);
% Adds notes and continuous-head-localization tags to .infods file
% Inputs : infods : Structure of tags to be written to output infods file.
% HLCdata : 0 or [] or not defined - There are no HLC channels
% (head-coil position) in the data. Just pass the existing tags to
% the output dataset.
% HLCdata : real array : size(HLCdata)=[samplesPerTrial 3 Ncoil nTrial]
% Calculate the head motion tags.
% Outputs : status : 0: Everything looks OK
% 1: Couldn't find _DATASET tags.
% <0: There is a problem with the new infods file.
% Calls:
% - getArrayField: Extracts field names from structure array S.
% Defaults for the head localization tags.
% Might do this better with a structure.
HZ_MODE_UNKNOWN=2^31-1; % Bug in DataEditor and acquisition software, Oct. 2006
% Should be -1.
% New dataset tags for HLC specification.
addTag=strvcat('_DATASET_HZ_MODE',...
'_DATASET_MOTIONTOLERANCE',...
'_DATASET_MAXHEADMOTION',...
'_DATASET_MAXHEADMOTIONTRIAL',...
'_DATASET_MAXHEADMOTIONCOIL');
addTagType=[5 4 4 7 10]';
% Check HLCdata array. HLCdata=[] indicates no continuous head localization.
if ~exist('HLCdata')==1
HLCdata=[];
elseif ~isempty(HLCdata)
[samplesPerTrial nDim Ncoil nTrial]=size(HLCdata);
if nDim~=3;
fprintf('writeCTFds (updateHLC): size(HLCdata)=[');fprintf(' %d',size(HLCdata));
fprintf(']\n');
fprintf(' nDim=%d?? Setting HLCdata=[].\n',nDim);
HLCdata=[];
end
end
% Assume that all the tag names are different. There is no checking when a tag listed in
% addTag matches more than one entry in array name.
name=getArrayField(infods,'name')'; %size(name)=[nTag lengthTag]
DATASET_tags=strmatch('_DATASET',name)'; % size(DATASET_tags)=[1 nTag]
if isempty(DATASET_tags)
status=1; % No _DATASET tags. Don't add anything.
else
status=0;
if isempty(HLCdata)
TagValue(1)=HZ_MODE_UNKNOWN;
TextTagValue=char(0);
addTag=addTag(1,:); % Remove the other HLC tags
addTagType=addTagType(1);
else % ~isempty(HLCdata)
% Remove HLC offsets.
HLCoffset=squeeze(HLCdata(1,:,:,1));
for q=1:Ncoil
for k=1:3
HLCdata(:,k,q,:)=HLCdata(:,k,q,:)-HLCoffset(k,q);
end
end
% Calculate motions as displacement from the start of the dataset.
absMotion=squeeze(sqrt(sum(HLCdata.^2,2))); %size(absMotion)=[samplesPerTrial Ncoil nTrial]
maxCoilMotion=squeeze(max(absMotion,[],1)); % size(maxCoilMovement)=[Ncoil nTrial]
maxHeadMotion=max(max(maxCoilMotion));
[mx maxHeadMotionCoil]=max(max(maxCoilMotion,[],2));
[mx maxHeadMotionTrial]=max(max(maxCoilMotion,[],1));
% Create a list of head motion tag values
TagValue(1)=5; % Indicates continuous head localization
TagValue(2)=max(2*maxHeadMotion,0.02); % _DATASET_MOTIONTOLERANCE
TagValue(3)=maxHeadMotion; % _DATASET_MAXHEADMOTION
% Subtract 1 from the trial so trial numbering starts at 0.
TagValue(4)=maxHeadMotionTrial-1; % _DATASET_MAXHEADMOTIONTRIAL
TextTagValue=char(zeros(4,1)); % Placeholder since tags1:4 are numerical
% _MAXHEADMOTIONCOIL value
TextTagValue=strvcat(TextTagValue,sprintf('%d',maxHeadMotionCoil));
TagValue=[TagValue 0]; % Placeholder only since the 5th tag is a text string.
end
% Add or insert tags.
for q=1:size(addTag,1)
nTag=length(infods);
tagName=deblank(addTag(q,:));
TagNo=strmatch(tagName,name,'exact')';
if isempty(TagNo) % Insert a tag at the end of the _DATASET tags.
TagNo=max(DATASET_tags)+1;
infods((TagNo+1):(nTag+1))=infods(TagNo:nTag);
name=strvcat(name(1:TagNo-1,:),tagName,name(TagNo:nTag,:));
DATASET_tags=[DATASET_tags TagNo];
end
if addTagType(q)~=10
infods(TagNo)=struct('name',tagName,'type',addTagType(q),'data',TagValue(q));
else
infods(TagNo)=struct('name',tagName,'type',addTagType(q),...
'data',deblank(TextTagValue(q,:)));
end
end % End loop over head position and head motion tags.
clear q TagNo TextTagValue TagValue;
end % End section add _DATASET tags
return
%%%%%%%%%%%%%% End of updateHLC %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%% Function updateBandwidth %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ds=updateBandwidth(ds,fhp,flp);
% Updates the bandwidth fields of infods and newds.
% 3 possible dources of bandwidth:
% 1. fhp,flp inputs (default)
% 2. newds fiels
% 3. res4.filter
% 4. infods field
% Almost always, fhp,flp will have the default values, but it could be defined in the
% fields of ds, so check. Result: lots of code to achieve a simple result.
% read fhp,flp from newds (if it exists)
if isfield(ds,'newds')
BWpos=max(strfind(ds.newds,[char(9) 'bandwidth:' char(9)])); % Keyword position
if isempty(BWpos)
fprintf(['writeCTFds (updateBandwidth): Keyword ''bandwidth:''',...
'does not appear in ds.newds.\n',...
' Field newds removed from structure ds.\n']);
ds=rmfield(ds,'newds');
else
% Get the bandwidth parameters from ds.newds.
eol=max([13 min(strfind(ds.newds(BWpos+1:length(ds.newds)),char(10)))]);
buff=sscanf(ds.newds((BWpos+13):(BWpos+eol)),'%f%c%f');
fhp=max(fhp,buff(1));
flp=min(flp,buff(3));
end
clear eol buff BWpos;
end
% Get fhp, flp from res4.
if ~isempty(ds.res4.filters)
for kq=1:ds.res4.num_filters
freq=ds.res4.filters(kq).freq;
if ds.res4.filters(kq).fType==1;
flp=min(flp,freq);
elseif ds.res4.filters(kq).fType==2;
fhp=max(fhp,freq);
end
end
clear kq freq;
end
% Get fhp, flp from ds.infods
if isfield(ds,'infods')
name=getArrayField(ds.infods,'name')';
TagNo=strmatch('_DATASET_LOWERBANDWIDTH',name,'exact');
if ~isempty(TagNo);fhp=max(fhp,ds.infods(TagNo).data);end
TagNo=strmatch('_DATASET_UPPERBANDWIDTH',name,'exact');
if ~isempty(TagNo);flp=min(flp,ds.infods(TagNo).data);end
end
% Now have fhp,flp. Update hist. Add all the res4 filters.
if ~isempty(ds.res4.filters)
if ~isfield(ds,'hist');hist=char([]);end
ds.hist=[ds.hist 'Filters specified in res4 file :' char(10)];
for kq=1:ds.res4.num_filters
freq=ds.res4.filters(kq).freq;
if ds.res4.filters(kq).fType==1;
ds.hist=[ds.hist ...
num2str(kq,'%8d') ' Lowpass ' num2str(freq,'%6.2f') ' Hz' char(10)];
elseif ds.res4.filters(kq).fType==2;
ds.hist=[ds.hist ...
num2str(kq,'%8d') ' Highpass ' num2str(freq,'%6.2f') ' Hz' char(10)];
elseif ds.res4.filters(kq).fType==3;
ds.hist=[ds.hist num2str(kq,'%8d') ' Notch ' num2str(freq,'%6.2f') ...
' Hz width=' num2str(ds.res4.filters(kq).Param,'%6.2f') ' Hz' char(10)];
else
ds.hist=[ds.hist ' fType=',num2str(ds.res4.filters(kq).fType,'%d') char(10)];
end
end
ds.hist=[ds.hist ,...
'Bandwidth: ',num2str(fhp,'%0.3g'),' - ',num2str(flp,'%0.3g'),' Hz',char(10)];
clear kq freq;
end
% Update newds bandwidth
if isfield(ds,'newds')
BWpos=max(strfind(ds.newds,[char(9) 'bandwidth:' char(9)]));
eol=max([12 min(strfind(ds.newds(BWpos+1:length(ds.newds)),char(10)))]);
ds.newds=[ds.newds(1:BWpos+11) num2str(fhp,'%0.6f') ', ' num2str(flp,'%0.6f') ...
ds.newds((BWpos+eol):length(ds.newds))];
clear BWpos eol;
end
% Update infods bandwidth tags. Lots of coding becasue it's possible that infods does
% not already have bandwidth tags.
name=getArrayField(ds.infods,'name')';
DATASET_tags=strmatch('_DATASET_',name);
if ~isempty(DATASET_tags)
addTag=strvcat('_DATASET_LOWERBANDWIDTH','_DATASET_UPPERBANDWIDTH');
TagValue=[fhp flp];
% Add or update tags.
for q=1:size(addTag,1)
nTag=length(ds.infods);
TagNo=strmatch(deblank(addTag(q,:)),name,'exact')';
if isempty(TagNo) % Insert a tag at the end of the _DATASET tags.
TagNo=max(DATASET_tags)+1;
ds.infods((TagNo+1):(nTag+1))=ds.infods(TagNo:nTag);
ds.infods(TagNo)=struct('name',deblank(addTag(q,:)),'type',4,'data',TagValue(q));
name=strvcat(name(1:TagNo-1,:),deblank(addTag(q,:)),name(TagNo:nTag,:));
DATASET_tags=[DATASET_tags TagNo];
else
ds.infods(TagNo).data=TagValue(q); % Tag exists. Just update the value.
end
end % End loop over head position and head motion tags.
clear q nTag DATASET_tags;
else
fprintf(['writeCTFds (updateBandwidth): Found no _DATASET tags in infods.\n'...
'\t\t\tDid not add bandwidth tags.\n']);
end
return
%%%%%%%%%%%%%% End of updateBandwidth %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%% Function updateDateTime %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ds=updateDateTime(ds);
% Update the dat/time fields of res4 and and infods
datetime=floor(clock);
if isfield(ds,'infods');
name=getArrayField(ds.infods,'name')';
DATASET_tags=strmatch('_DATASET_',name);
if ~isempty(DATASET_tags)
addTag=strvcat('_DATASET_CREATORDATETIME','_DATASET_LASTMODIFIEDDATETIME');
tagData=sprintf('%d%2.2d%2.2d%2.2d%2.2d%2.2d',datetime);
tagType=10;
for q=1:size(addTag,1)
nTag=length(ds.infods);
TagNo=strmatch(deblank(addTag(q,:)),name,'exact')';
if isempty(TagNo) % Insert a tag at the end of the _DATASET tags.
TagNo=max(DATASET_tags)+1;
ds.infods((TagNo+1):(nTag+1))=ds.infods(TagNo:nTag);
name=strvcat(name(1:TagNo-1,:),deblank(addTag(q,:)),name(TagNo:nTag,:));
DATASET_tags=[DATASET_tags TagNo];
end
ds.infods(TagNo)=struct('name',deblank(addTag(q,:)),'type',tagType,'data',tagData);
end
clear nTag TagNo name DATASET_tags addTag tagData tagType;
else
fprintf('writeCTFds (updateDateTime): Cannot find any _DATASET tags in ds.infods.\n');
end % End loop over head position and head motion tags.
else
fprintf('writeCTFds (updateDateTime): Cannot find ds.infods.\n');
end
ds.res4.data_date=sprintf('%4d/%2.2d/%2.2d',datetime(1:3));
ds.res4.data_time=sprintf('%2.2d:%2.2d:%2.2d',datetime(4:6));
return
%%%%%%%%%%%%%% End of updateDateTime %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%% Function getArrayField %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function x=getArrayField(S,yfield)
% Extracts one field of a structure array.
% Inputs: S : structure array.
% yfield: name of field of S (string)
% Output: x. x(:,n)=S(n).yfield; size(x)=[size(yfield) length(S)]
% Field sizes: Two options:
% 1. size(S(n).yfield) is the same for all n. Any size allowed.
% 2. S(n).yfield is a 2-D array for all structure elements S(n).
% Then yfield of different array elements S(n) can have different sizes.
% The array returned will be large enough to accomodate all of the data.
sizeS=size(S);
nS=prod(sizeS);
S=reshape(S,1,nS);
% Determine which array-size option to use.
sizey=size(getfield(S,{1},yfield));
option1=1;
option2=(length(sizey)==2);
for n=2:nS
sizeyn=size(getfield(S,{n},yfield));
option1=option1 & isequal(sizey,sizeyn);
option2=option2 & length(sizeyn)==2;
if option2
sizey=max([sizey;sizeyn],[],1);
end
end
if option1 % All fields have the same size
nY=prod(sizey);
if isnumeric(getfield(S,{1},yfield))
x=zeros(nY,nS);
elseif ischar(getfield(S,{1},yfield))
x=char(zeros(nY,nS));
end
for n=1:nS
x(:,n)=reshape(getfield(S,{n},yfield),nY,1);
end
x=reshape(x,[sizey nS]);
elseif option2 % All fields have only two dimensions
if isnumeric(getfield(S,{1},yfield))
x=zeros([sizey nS]);
elseif ischar(getfield(S,{1},yfield))
x=char(zeros([sizey nS]));
end
for n=1:nS
y=getfield(S,{n},yfield);
sizeyn=size(y);
x(1:sizeyn(1),1:sizeyn(2),n)=y;
end
else
fprintf(['getArrayField: Field %s of the structure array has >2 dimensions ',...
'and not all field have the same size.\n'],yfield);
x=[];
end
x=squeeze(x);
return
%%%%%%%% End of getArrayField %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
github
|
philippboehmsturm/antx-master
|
writeRes4.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/ctf/writeRes4.m
| 8,560 |
utf_8
|
416bc2b62624835c63140e54415d2f49
|
function res4=writeRes4(res4File,res4,MAX_COILS);
% Write the new .res4 file. Use ieee-be (big endian) format
% Character-string output is done using function writeCTFstring which
% checks that strings are the correct length for the .res4 file format.
% Function calls: - writeCTFstring (included in this listing).
fid_res4=fopen(res4File,'w','ieee-be');
if fid_res4<0
fprintf('writeCTFds (writeRes4): Could not open file %s\n',res4File);
return
end
fwrite(fid_res4,[res4.header(1:7),char(0)],'uint8'); % 8-byte header
% meg41GeneralResRec
res4.appName=writeCTFstring(res4.appName,-256,fid_res4);
res4.dataOrigin=writeCTFstring(res4.dataOrigin,-256,fid_res4);
res4.dataDescription=writeCTFstring(res4.dataDescription,-256,fid_res4);
fwrite(fid_res4,res4.no_trials_avgd,'int16');
res4.data_time=writeCTFstring(res4.data_time,255,fid_res4);
res4.data_date=writeCTFstring(res4.data_date,255,fid_res4);
% new_general_setup_rec_ext part of meg41GeneralResRec
fwrite(fid_res4,res4.no_samples,'int32'); % 4
fwrite(fid_res4,[res4.no_channels 0],'int16'); % 2*2
fwrite(fid_res4,res4.sample_rate,'double'); % 8
fwrite(fid_res4,res4.epoch_time,'double'); % 8
fwrite(fid_res4,[res4.no_trials 0],'int16'); % 2*2
fwrite(fid_res4,res4.preTrigPts,'int32'); % 4
fwrite(fid_res4,res4.no_trials_done,'int16'); % 2
fwrite(fid_res4,res4.no_trials_display,'int16'); % 2
fwrite(fid_res4,res4.save_trials,'int32'); % 4 CTFBoolean
% meg41TriggerData part of new_general_setup_rec_ext 10 bytes total
fwrite(fid_res4,res4.primaryTrigger,'int32'); % 4
fwrite(fid_res4,res4.triggerPolarityMask,'int32'); % 4
fwrite(fid_res4,[0 0],'uint8'); % 2 bytes
% end of meg41TriggerData part of new_general_setup_rec_ext
fwrite(fid_res4,[0 0],'uint8'); % 2 bytes padding
fwrite(fid_res4,[res4.trigger_mode 0],'int16'); % 2*2
fwrite(fid_res4,res4.accept_reject_Flag,'int32'); % 4 CTFBoolean
fwrite(fid_res4,[res4.run_time_display 0],'int16');% 2*2
fwrite(fid_res4,res4.zero_Head_Flag,'int32'); % 4 CTFBoolean
fwrite(fid_res4,res4.artifact_mode,'int32'); % 4 CTFBoolean
% end of new_general_setup_rec_ext part of meg41GeneralResRec
% meg4FileSetup part of meg41GeneralResRec
res4.nf_run_name=writeCTFstring(res4.nf_run_name,32,fid_res4);
res4.nf_run_title=writeCTFstring(res4.nf_run_title,-256,fid_res4);
res4.nf_instruments=writeCTFstring(res4.nf_instruments,32,fid_res4);
res4.nf_collect_descriptor=writeCTFstring(res4.nf_collect_descriptor,32,fid_res4);
res4.nf_subject_id=writeCTFstring(res4.nf_subject_id,-32,fid_res4);
res4.nf_operator=writeCTFstring(res4.nf_operator,32,fid_res4);
res4.nf_sensorFileName=writeCTFstring(res4.nf_sensorFileName,56,fid_res4);
res4.rdlen=length(res4.run_description); % Run_description may have been changed.
fwrite(fid_res4,[0 res4.rdlen 0],'int32'); % 12-byte structure of the .res4 file.
res4.run_description=writeCTFstring(res4.run_description,res4.rdlen,fid_res4);
% end of meg4FileSetup part of meg41GeneralResRec
% filter descriptions
fwrite(fid_res4,res4.num_filters,'int16');
for kfilt=1:res4.num_filters
fwrite(fid_res4,res4.filters(kfilt).freq,'double');
fwrite(fid_res4,res4.filters(kfilt).fClass,'int32');
fwrite(fid_res4,res4.filters(kfilt).fType,'int32');
fwrite(fid_res4,res4.filters(kfilt).numParam,'int16');
for kparm=1:res4.filters(kfilt).numParam
fwrite(fid_res4,res4.filters(kfilt).Param(kparm),'double');
end
end
% Write channel names. Must have size(res4.chanNames)=[nChan 32]
[no_chanNames len_chanNames]=size(res4.chanNames);
for kchan=1:res4.no_channels
res4.chanNames(kchan,:)=writeCTFstring(res4.chanNames(kchan,:),len_chanNames,fid_res4);
end
% Write sensor resource table
for kchan=1:res4.no_channels
fwrite(fid_res4,res4.senres(kchan).sensorTypeIndex,'int16');
fwrite(fid_res4,res4.senres(kchan).originalRunNum,'int16');
fwrite(fid_res4,res4.senres(kchan).coilShape,'int32');
fwrite(fid_res4,res4.senres(kchan).properGain,'double');
fwrite(fid_res4,res4.senres(kchan).qGain,'double');
fwrite(fid_res4,res4.senres(kchan).ioGain,'double');
fwrite(fid_res4,res4.senres(kchan).ioOffset,'double');
fwrite(fid_res4,res4.senres(kchan).numCoils,'int16');
numCoils=res4.senres(kchan).numCoils;
fwrite(fid_res4,res4.senres(kchan).grad_order_no,'int16');
fwrite(fid_res4,0,'int32'); % Padding to 8-byte boundary
% coilTbl
for qx=1:numCoils
fwrite(fid_res4,[res4.senres(kchan).pos0(:,qx)' 0],'double');
fwrite(fid_res4,[res4.senres(kchan).ori0(:,qx)' 0],'double');
fwrite(fid_res4,[res4.senres(kchan).numturns(qx) 0 0 0],'int16');
fwrite(fid_res4,res4.senres(kchan).area(qx),'double');
end
if numCoils<MAX_COILS
fwrite(fid_res4,zeros(10*(MAX_COILS-numCoils),1),'double');
end
%HdcoilTbl
for qx=1:numCoils
fwrite(fid_res4,[res4.senres(kchan).pos(:,qx)' 0],'double');
fwrite(fid_res4,[res4.senres(kchan).ori(:,qx)' 0],'double');
fwrite(fid_res4,[res4.senres(kchan).numturns(qx) 0 0 0],'int16');
fwrite(fid_res4,res4.senres(kchan).area(qx),'double');
end
if numCoils<MAX_COILS
fwrite(fid_res4,zeros(10*(MAX_COILS-numCoils),1),'double');
end
end
% End writing sensor resource table
% Write the table of balance coefficients.
if res4.numcoef<=0
fwrite(fid_res4,res4.numcoef,'int16'); % Number of coefficient records
elseif res4.numcoef>0
scrx_out=[];
for kx=1:res4.numcoef
sName=strtok(char(res4.scrr(kx).sensorName),['- ',char(0)]);
if ~isempty(strmatch(sName,res4.chanNames))
scrx_out=[scrx_out kx];
end
end
% Remove the extra coefficient records
res4.scrr=res4.scrr(scrx_out);
res4.numcoef=size(res4.scrr,2);
fwrite(fid_res4,res4.numcoef,'int16'); % Number of coefficient records
% Convert res4.scrr to double before writing to output file. In MATLAB 5.3.1,
% when the 'ieee-be' option is applied, fwrite cannot write anything except
% doubles and character strings, even if fwrite does allow you to specify short
% integer formats in the output file.
for nx=1:res4.numcoef
fwrite(fid_res4,double(res4.scrr(nx).sensorName),'uint8');
fwrite(fid_res4,[double(res4.scrr(nx).coefType) 0 0 0 0],'uint8');
fwrite(fid_res4,double(res4.scrr(nx).numcoefs),'int16');
fwrite(fid_res4,double(res4.scrr(nx).sensor),'uint8');
fwrite(fid_res4,res4.scrr(nx).coefs,'double');
end
end
fclose(fid_res4);
return
% *************************************************************************************
%*************** Function writeCTFstring ************************************************
function strng=writeCTFstring(instrng,strlen,fid)
% Writes a character string to output unit fid. Append nulls to get the correct length.
% instrng : Character string. size(instrng)=[nLine nPerLine]. strng is reformulated as a
% long string of size [1 nChar]. Multiple lines are allowed so the user can
% easily append text. If necessary, characters are removed from
% instrng(1:nLine-1,:) so all of strng(nLine,:) can be accomodated.
% strlen: Number of characters to write. strlen<0 means remove leading characters.
% If abs(strlen)>length(strng) pad with nulls (char(0))
% If 0<strlen<length(strng), truncate strng and terminate with a null.
% If -length(string)<strlen<0, remove leading characters and terminate with a null.
% Form a single long string
nLine=size(instrng,1);
strng=deblank(instrng(1,:));
if nLine>1
% Concatenate lines 1:nLine-1
for k=2:nLine-1
if length(strng)>0
if ~strcmp(strng(length(strng)),'.') & ~strcmp(strng(length(strng)),',')
strng=[strng '.']; % Force a period at the end of the string.
end
end
strng=[strng ' ' deblank(instrng(k,:))];
end
if length(strng)>0
if ~strcmp(strng(length(strng)),'.') % Force a period at the end of the string.
strng=[strng '.'];
end
end
% Add all of the last line.
nChar=length(strng);
nLast=length(deblank(instrng(nLine,:)));
strng=[strng(1:min(nChar,abs(strlen)-nLast-4)) ' ' deblank(instrng(nLine,:))];
end
if length(strng)<abs(strlen)
strng=[strng char(zeros(1,abs(strlen)-length(strng)))];
elseif length(strng)>=strlen & strlen>0
strng=[strng(1:strlen-1) char(0)];
else
strng=[strng(nLast+[strlen+2:0]) char(0)];
end
fwrite(fid,strng,'char');
return
% ************* End of function writeCTFstring ***************************************
% ************************************************************************************
|
github
|
philippboehmsturm/antx-master
|
addCTFtrial.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/ctf/addCTFtrial.m
| 51,483 |
utf_8
|
b59730fdb231f07741e7e87dea9e6c1c
|
function cntrl=addCTFtrial(datasetname,data,unit,mrk,cls,badSegments);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% This program creates datasets that can be analyzed by CTF software. %
% %
% Datasets created by this program MUST NOT BE USED FOR CLINICAL APPLICATIONS. %
% %
% Please do not redistribute it without permission from VSM MedTech Ltd. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% addCTFtrial.m Version 1.1 Adds trial(s) to a a CTF-format data set previously
% created from MATLAB by writeCTFds.m. The purpose of addCTFtrial is to allow
% users to write CTF data sets that are too large for the computer's memory.
% Date : 18 April 2007
% Author : Harold Wilson
% Operation :
% 1. Use writeCTFds to create a dataset (name = DATASET) consisting of one or
% more trials. size(data)= [SAMPLES, CHANNELS, TRIALS].
% 2. Later, a trial is to be added to DATASET. This program adds the new information
% to the .res4, .mrk, .cls and badSegements files and appends the new data to the
% existing .meg4 file.
% Inputs : datasetname : Dataset including path. Extension '.ds' is optional.
% data : MEG data array. size(data)=[no_samples no_channels no_trials_added]
% Array data may be single or double.
% unit : Determines the unit of the SQUID and EEG signals:
% If unit is missing or unit==[], the unit is set to 'fT'.
% 'ft' or 'fT' : Convert to fT (MEG), uV (EEG)
% 't' or 'T' : Convert to T (MEG), V (EEG)
% 'phi0' : Convert to phi0 (MEG), uV (EEG)
% 'int': Read plain integers from *.meg4-file
% mrk,cls,badSegments : Structures describing the markers, trial classes and bad
% segments of the new trials. Trial numbering refers to the new trials
% being added to the dataset, starting at trial=1. Markers are updated
% only when there is already as .mrk file in the dataset.
% Outputs : - Dataset with trial(s) added.
% - cntrl : 0 - failure. The dataset is not modified.
% 1 - success. The new data is added to the dataset
% Function calls
% Included in this listing:
% - combineMarkers: Combines marker specifications in structures ds.mrk and mrk.
% - combineClasses: Combines trial class specifications in structures
% ds.TrialClass and cls.
% - writeBadSegments: Creates the new bad.segments file.
% - writeClassFile: Creates the new ClassFile.cls file.
% - updateCreatorSoftware: Adds non-clinical-use and creation software messages to
% infods, res4, newds and hist fields of ds.
% - updateHLC: Adds head-coil movement information from the trials being added to an
% existing ds.infods.
% - getArrayField : Extracts one field of a structure array to make it easier to
% manipulate.
% Not included in this listing:
% - writeRes4: Writes the new .res4 file.
% - writeMarkerFile: Creates the new MarkerFile.mrk file.
% - writeCPersist: Creates the new .acq and .infods files.
% Output files are opened with 'w' permission and 'ieee-be' machine format in order
% to be compatible with the Linux acquisition and analysis software. Do not open files
% with 'wt' permission because this will add an extra byte (char(13)) at the end of each
% line of text.
%persistent printWarning % No clinical-use warning with addCTFtrial.
%printWarning=1;
delim=filesep;
if nargin==0 & nargout==0 % Print a version number
fprintf(['\taddCTFtrial: Version 1.1 18 April 2007 ',...
'Adds trials to v4.1 and v4.2 CTF data sets.\n',...
'\tCall: cntrl=addCTFtrial(datasetname,data,unit,mrk,cls,badSegments);\n',...
'\t\tdatasetname = Name of existing dataset including the path.\n',...
'\t\tdata = Data that will be written to the new dataset .meg4 file.\n',...
'\t\tunit = Physical units of the data.\n',...
'\t\tmrk,cls,badSegments = descriptions of markers, trial classes and',...
' bad segments of data.\n\n']);
return
end
% Indicate failure on an early return.
cntrl=0;
% Allowed 8-byte headers for res4 and meg4 files.
res4_headers=strvcat(['MEG41RS',char(0)],['MEG42RS',char(0)]);
meg4_headers=strvcat(['MEG41CP',char(0)],['MEG42CP',char(0)]);
MAX_COILS=8; % Parameter that determines the size of the ds.res4.senres structure.
maxMEG4Size=2^31; % Maximum MEG$ file in bytes. (Limit set by Linux software)
% addCTFds will add trials to datasets only if they were created by writeCTFds.
originalCreatorSoftware='writeCTFds';
creatorSoftware='addCTFtrial'; % Added to .infods file
meg4ChunkSize=2^20; % Write new .meg4 file in chunks of 4*meg4ChunkSize bytes.
clinical_use_message='NOT FOR CLINICAL USE';
if ~exist('clinical_use_message');
clinical_use_message=char([]);
end
% Check number of inputs
if nargin<2
fprintf(['addCTFtrial: Must supply inputs datasetname,data. ',...
'Only %d input arguments are present.\n'],nargin);
return
end
% Check input argument unit. Convert unit to lower case.
if exist('unit')~=1
unit='ft'; % default
elseif isempty(unit)
unit='ft'; % default
elseif ischar(unit)
unit=lower(unit);
if ~strcmp(unit,'int') & ~strcmp(unit,'ft') & ~strcmp(unit,'t') & ~strcmp(unit,'phi0')
fprintf(['addCTFtrial : unit=%s Not a valid option. Must be ',...
'''fT'', ''T'', ''phi0'' or ''int''\n'],unit);
ds=-1; % Force an error in the calling program.
return
end
end
% Check argument type
if ~isnumeric(data)
fprintf('\naddCTFtrial: Input data is not numeric.\n');
return
elseif ~ischar(unit)
fprintf('\naddCTFtrial: Input unit is not char.\n');
return
elseif~ischar(datasetname)
fprintf('\naddCTFtrial: Input datasetname is not char.\n');
return
end
if exist('mrk')==1
if ~isstruct(mrk)
fprintf('\naddCTFtrial: Input mrk is not a structure.\n\n');
return
end
else
mrk=struct([]);
end
if exist('cls')==1
if ~isstruct(cls)
fprintf('\naddCTFtrial: Input cls is not a structure.\n\n');
return
end
else
cls=struct([]);
end
if exist('badSegments')==1
if ~isstruct(badSegments)
fprintf('\naddCTFtrial: Input badSegments is not a structure.\n\n');
return
end
else
badSegments=struct([]);
end
% Does the dataset exist?
if exist(datasetname)~=7
fprintf('addCTFtrial: Dataset %s does not exist.\n',datasetname);
return
end
% Separate datasetname into a path and the baseName
datasetname=deblank(datasetname);
ksep=max([0 findstr(datasetname,delim)]);
baseName=datasetname((ksep+1):length(datasetname));
path=datasetname(1:ksep); % String path is terminated by the file delimiter (or path=[]).
% Remove the last .ds from baseName.
kdot=max(findstr(baseName,'.ds'));
if kdot==(length(baseName)-2)
baseName=baseName(1:(max(kdot)-1));
else
datasetname=[datasetname,'.ds'];
end
clear ksep kdot;
% Get the ds structure of the dataset
ds=readCTFds(datasetname);
% Update text fields of res4,infods, newds.
ds=updateCreatorSoftware(ds,creatorSoftware,originalCreatorSoftware);
if isempty(ds);return;end
nSample=ds.res4.no_samples;
fSample=ds.res4.sample_rate;
nChan=ds.res4.no_channels;
% Check that the new data and the existing data have the same number of channels
% and points per trial.
if size(data,1)~=nSample | size(data,2)~=nChan | size(data,3)==0
fprintf(['addCTFtrial: size(data)=[%d %d %d], but existing data has no_samples=%d,',...
' no_channels=%d\n'],[size(data,1) size(data,2) size(data,3)],...
nSample,nChan);
return
end
% Update ds.res4 fields to match the size of array data.
nTrialNew=size(data,3);
nTrialOld=ds.res4.no_trials;
ds.res4.no_trials=nTrialOld+nTrialNew;
ds.res4.epoch_time=nSample*ds.res4.no_trials/fSample;
% Before converting data to integers, save the HLC channels for motion analysis in function
% function updateHLC.
if isempty(strmatch('HLC',ds.res4.chanNames))
HLCdata=[];
else
% Make a list of head-coil channels
coil=0;
HLClist=[];
while ~isempty(strmatch(['HLC00',int2str(coil+1)],ds.res4.chanNames))
coil=coil+1;
for k=1:3
HLClist=[HLClist strmatch(['HLC00',int2str(coil),int2str(k)],ds.res4.chanNames)];
end
end
HLCdata=reshape(double(data(:,HLClist,:)),nSample,3,coil,nTrialNew);
clear coil k HLClist;
end
% Convert data to integers because CTF data sets are stored as raw numbers and
% not as physical qunatities. The res4 file contains the calibrations for
% converting back to physical units. Array data may be single precision, so
% convert to double before doing any adjustments to the data.
% Already checked that unit is valid.
if strcmp(unit,'int')
data=reshape(data,nSample,nChan*nTrialNew);
for k=1:nChan*nTrialNew
if strcmp(class(data),'single')
data(:,k)=single(round(double(data(:,k))));
else
data(:,k)=round(double(data(:,k)));
end
end
data=reshape(data,nSample,nChan,nTrialNew);
clear k;
else
for chan=1:nChan % Convert EEGs from uV to V, SQUIDs from fT to T
SQUIDtype=any(ds.res4.senres(chan).sensorTypeIndex==[0:7]);
EEGtype=any(ds.res4.senres(chan).sensorTypeIndex==[8 9]);
if EEGtype & (strcmp(unit,'ft') | strtcmp(unit,'phi0'))
alphaG=1e-6;
elseif SQUIDtype & strcmp(unit,'ft')
alphaG=1e-15;
elseif SQUIDtype & strcmp(unit,'phi0')
alphaG=1./(ds.res4.senres(chan).properGain*ds.res4.senres(chan).ioGain);
else
alphaG=1;
end
% Convert from physical units to integers using the gains in the senres table.
for kt=1:nTrialNew
buff=round(double(data(:,chan,kt))*(alphaG*...
(ds.res4.senres(chan).properGain*ds.res4.senres(chan).qGain*ds.res4.senres(chan).ioGain)));
if strcmp(class(data),'single')
data(:,chan,kt)=single(buff);
else
data(:,chan,kt)=buff;
end
end
end
clear chan alphaG SQUIDtype EEGtype buff kt;
end
% Check the meg4 file header.
fidMeg4=fopen([path,baseName,'.ds\',baseName,'.meg4'],'r','ieee-be');
fileHeader=fread(fidMeg4,8,'char')';
fclose(fidMeg4);
if isempty(strmatch(fileHeader(1:7),meg4_headers(:,1:7),'exact'))
ds.meg4.header=meg4_headers(1,1:7);
fprintf('addCTFtrial: meg4 header=%s ?\n',fileHeader);
return
end
% Create the .res4 file in the output dataset.
ds.res4=writeRes4([path,baseName,'.ds\',baseName,'.res4'],ds.res4,MAX_COILS);
if ds.res4.numcoef<0
fprintf('addCTFtrial: writeRes4 returned ds.res4.numcoef=%d (<0??)\n',ds.res4.numcoef);
fprintf(' Deleting dataset %s\n',baseName);
rmdir([path,baseName,'.ds'],'s');
return
end
% Add trial(s) to the existing meg4 file. Complicated coding in case the use requests
% writing several trials, which fill up one meg4 file and start the next one.
ptsPerTrial=nSample*nChan;
data=reshape(data,ptsPerTrial,nTrialNew);
maxTrialPerFile=floor((maxMEG4Size-8)/(4*ptsPerTrial));
maxPtsPerFile=ptsPerTrial*maxTrialPerFile;
nExt=-1;
trial=0;
pt=0;
while trial<nTrialNew
nExt=nExt+1;
if nExt==0
meg4Ext='.meg4';
else
meg4Ext=['.',int2str(nExt),'_meg4'];
end
meg4File=[path,baseName,'.ds\',baseName,meg4Ext];
D=dir(meg4File);
if isempty(D)
% Create the next meg4 file and write the header.
fidMeg4=fopen(meg4File,'w','ieee-be');
fwrite(fidMeg4,[ds.meg4.header(1:7),char(0)],'uint8');
fclose(fidMeg4);
D=struct('bytes',8);
end
nWrite=min(nTrialNew-trial,floor((maxMEG4Size-D.bytes)/(4*ptsPerTrial)));
%fprintf('nExt=%d meg4File=%s\n\t\tsize=%d bytes nWrite=%d\n',nExt,meg4File,D.bytes,nWrite);
if nWrite>0
fidMeg4=fopen(meg4File,'a','ieee-be');
endPt=pt+nWrite*ptsPerTrial;
while pt<endPt
pt1=min(pt+meg4ChunkSize,endPt); % Convert to double in case data is
fwrite(fidMeg4,double(data(pt+1:pt1)),'int32'); % single. This may cause memory
pt=pt1; % problems so write in short pieces.
end
fclose(fidMeg4);
trial=trial+nWrite;
end
end
clear trial pt meg4Ext meg4File D fidMeg4 nWrite endPt pt1;
% Set variable cntrl to indicate that the meg4 and res4 files have been updated.
cntrl=1;
% Update the .meg4 part of structure ds.
ds.meg4.fileSize=8*(nExt+1);
clear data pt pt1 ndata fidMeg4;
% Add dataset names to .hist, and write new .hist file.
if ~isfield(ds,'hist');
ds.hist=char([]);
else
q0=max(strfind(ds.hist,originalCreatorSoftware));
if ~isempty(q0) & isempty(strfind(ds.hist(q0:length(ds.hist)),creatorSoftware))
ds.hist=[ds.hist(1:q0+length(originalCreatorSoftware)-1) ', ' creatorSoftware ...
ds.hist(q0+length(originalCreatorSoftware):length(ds.hist))];
end
% Create .hist file
histfile=[path,baseName,'.ds\',baseName,'.hist'];
fid=fopen(histfile,'w');
fwrite(fid,ds.hist,'char');
fclose(fid);
end
% Add HLC data and write new infods file.
if isfield(ds,'infods')
ds.infods=updateHLC(ds.infods,HLCdata);
writeCPersist([path,baseName,'.ds',delim,baseName,'.infods'],ds.infods);
end
clear HLCdata;
% New .newds file.
if isfield(ds,'newds')
fid=fopen([path,baseName,'.ds\',baseName,'.newds'],'w');
fwrite(fid,ds.newds,'char');
fclose(fid);
end
% Add markers, and create new MarkerFile.mrk
if isfield(ds,'mrk')
mrk=combineMarkers(ds.mrk,nTrialOld,mrk,nTrialNew,ds.res4);
if ~isempty(mrk)
writeMarkerFile([path,baseName,'.ds',delim,'MarkerFile.mrk'],mrk);
end
elseif ~isempty(mrk)
fprintf(['addCTFtrial: Existing dataset has no MarkerFile, but structure mrk is',...
' specified in call to addCTFtrial.\n',...
' MarkerFile.mrk not created.\n']);
end
% bad.segments file
if isfield(ds,'badSegments') & ~isempty(badSegments)
ds.badSegments.trial=[ds.badSegments.trial badSegments.trial+nTrialOld];
ds.badSegments.StartTime=[ds.badSegments.StartTime badSegments.StartTime];
ds.badSegments.EndTime=[ds.badSegments.EndTime badSegments.EndTime];
writeBadSegments([path,baseName,'.ds',delim,'bad.segments'],ds.badSegments,...
ds.res4.no_trials,nSample/fSample);
end
% ClassFile. Add trial classes, and create new ClassFile.cls
if ~isempty(cls)
if isfield(ds,'TrialClass')
cls=combineClasses(ds.TrialClass,nTrialOld,cls,nTrialNew);
if ~isempty(cls)
writeClassFile([path,baseName,'.ds',delim,'ClassFile.cls'],cls);
end
else
fprintf(['addCTFtrial: Existing dataset has no ClassFile, but structure cls is',...
' specified in call to addCTFtrial.\n',...
' ClassFile.cls not created.\n']);
end
end
return
% *************** End of function addCTFtrial ********************************************
% **************************************************************************************
% **************************************************************************************
% ************* function make_dummy_infods*********************************************
function Tag=make_dummy_infods(exist_hc,exist_HLC,sample_rate);
% If the user does not supply ds.infos, this code makes a dummy version. It has all of
% the tags that Acq created in file Richard_SEF_20060606_04.infods.
% ***********************************************************************************
% ***********************************************************************************
DATASET_HZ_UNKNOWN=round(2^31-1); % Peculiar requirement of DataEditor as of 23 Oct. 2006
fprintf('writeCTDds (make_dummy_infods): Creating a dummy infods file with all the tags.\n');
Tag(1)=struct('name','WS1_','type',0,'data',[]);
Tag(length(Tag)+1)=struct('name','_PATIENT_INFO','type',2,'data',[]);
Tag(length(Tag)+1)=struct('name','WS1_','type',0,'data',[]);
Tag(length(Tag)+1)=struct('name','_PATIENT_UID','type',10,...
'data','2.16.124.113000.000000.00000000000000.000000000.00000000.0011');
Tag(length(Tag)+1)=struct('name','_PATIENT_NAME_FIRST','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_PATIENT_NAME_MIDDLE','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_PATIENT_NAME_LAST','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_PATIENT_ID','type',10,'data','x');
Tag(length(Tag)+1)=struct('name','_PATIENT_BIRTHDATE','type',10,'data','19500101000000');
Tag(length(Tag)+1)=struct('name','_PATIENT_SEX','type',5,'data',2);
Tag(length(Tag)+1)=struct('name','_PATIENT_PACS_NAME','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_PATIENT_PACS_UID','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_PATIENT_INSTITUTE','type',10,'data','');
Tag(length(Tag)+1)=struct('name','EndOfParameters','type',-1,'data',[]);
Tag(length(Tag)+1)=struct('name','_PROCEDURE_INFO','type',2,'data',[]);
Tag(length(Tag)+1)=struct('name','WS1_','type',0,'data',[]);
Tag(length(Tag)+1)=struct('name','_PROCEDURE_VERSION','type',5,'data',1);
Tag(length(Tag)+1)=struct('name','_PROCEDURE_UID','type',10,...
'data','2.16.124.113000.000000.00000000000000.000000000.00000000.0041');
Tag(length(Tag)+1)=struct('name','_PROCEDURE_ACCESSIONNUMBER','type',10,'data','0');
Tag(length(Tag)+1)=struct('name','_PROCEDURE_TITLE','type',10,'data','0');
Tag(length(Tag)+1)=struct('name','_PROCEDURE_SITE','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_PROCEDURE_STATUS','type',5,'data',1);
Tag(length(Tag)+1)=struct('name','_PROCEDURE_TYPE','type',5,'data',2); % Research type
Tag(length(Tag)+1)=struct('name','_PROCEDURE_STARTEDDATETIME','type',10,...
'data','20060606164306');
Tag(length(Tag)+1)=struct('name','_PROCEDURE_CLOSEDDATETIME','type',10,...
'data','19000100000000');
Tag(length(Tag)+1)=struct('name','_PROCEDURE_COMMENTS','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_PROCEDURE_LOCATION','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_PROCEDURE_ISINDB','type',5,'data',0);
Tag(length(Tag)+1)=struct('name','EndOfParameters','type',-1,'data',[]);
Tag(length(Tag)+1)=struct('name','_DATASET_INFO','type',2,'data',[]);
Tag(length(Tag)+1)=struct('name','WS1_','type',0,'data',[]);
Tag(length(Tag)+1)=struct('name','_DATASET_VERSION','type',5,'data',2);
Tag(length(Tag)+1)=struct('name','_DATASET_UID','type',10,...
'data','2.16.124.113000.000000.00000000000000.000000000.00000000.0042');
Tag(length(Tag)+1)=struct('name','_DATASET_PATIENTUID','type',10,...
'data','2.16.124.113000.000000.00000000000000.000000000.00000000.0011');
Tag(length(Tag)+1)=struct('name','_DATASET_PROCEDUREUID','type',10,...
'data','2.16.124.113000.000000.00000000000000.000000000.00000000.0041');
Tag(length(Tag)+1)=struct('name','_DATASET_STATUS','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_DATASET_RPFILE','type',10,'data','default.rp');
Tag(length(Tag)+1)=struct('name','_DATASET_PROCSTEPTITLE','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_DATASET_PROCSTEPPROTOCOL','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_DATASET_PROCSTEPDESCRIPTION','type',10,...
'data','');
Tag(length(Tag)+1)=struct('name','_DATASET_COLLECTIONDATETIME','type',10,...
'data','Unknown');
Tag(length(Tag)+1)=struct('name','_DATASET_COLLECTIONSOFTWARE','type',10,...
'data','Acq ');
Tag(length(Tag)+1)=struct('name','_DATASET_CREATORDATETIME','type',10,...
'data',sprintf('%d',floor(clock)));
Tag(length(Tag)+1)=struct('name','_DATASET_CREATORSOFTWARE','type',10,...
'data','Acq ');
Tag(length(Tag)+1)=struct('name','_DATASET_KEYWORDS','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_DATASET_COMMENTS','type',10,...
'data','Dummy infods.');
Tag(length(Tag)+1)=struct('name','_DATASET_OPERATORNAME','type',10,'data','');
Tag(length(Tag)+1)=struct('name','_DATASET_LASTMODIFIEDDATETIME','type',10,...
'data',sprintf('%d',floor(clock)));
if exist_hc
nominalPositions=0; % Measured
else
nominalPositions=1; % Nominal
end
Tag(length(Tag)+1)=struct('name','_DATASET_NOMINALHCPOSITIONS','type',5,...
'data',nominalPositions);
Tag(length(Tag)+1)=struct('name','_DATASET_COEFSFILENAME','type',10,...
'data','ds.res4.scrr');
Tag(length(Tag)+1)=struct('name','_DATASET_SENSORSFILENAME','type',10,...
'data','ds.res4.senres');
%Tag(length(Tag)+1)=struct('name','_DATASET_COEFSFILENAME','type',10,...
% 'data','/opt/ctf-5.1/hardware/M015/M015_1609.coef');
%Tag(length(Tag)+1)=struct('name','_DATASET_SENSORSFILENAME','type',10,...
% 'data','/opt/ctf-5.1/hardware/M015/M015_1609.sens');
Tag(length(Tag)+1)=struct('name','_DATASET_SYSTEM','type',10,'data','DSQ-2010');
Tag(length(Tag)+1)=struct('name','_DATASET_SYSTEMTYPE','type',10,'data','Untitled');
Tag(length(Tag)+1)=struct('name','_DATASET_LOWERBANDWIDTH','type',4,'data',0);
Tag(length(Tag)+1)=struct('name','_DATASET_UPPERBANDWIDTH','type',4,'data',...
round(0.25*sample_rate));
Tag(length(Tag)+1)=struct('name','_DATASET_ISINDB','type',5,'data',0);
if exist_HLC
HZ_MODE=5;
elseif exist_hc
HZ_MODE=1;
else
HZ_MODE=DATASET_HZ_UNKNOWN;
end
Tag(length(Tag)+1)=struct('name','_DATASET_HZ_MODE','type',5,'data',HZ_MODE);
Tag(length(Tag)+1)=struct('name','_DATASET_MOTIONTOLERANCE','type',4,'data',0.005);
Tag(length(Tag)+1)=struct('name','_DATASET_MAXHEADMOTION','type',4,'data',0.005);
Tag(length(Tag)+1)=struct('name','_DATASET_MAXHEADMOTIONTRIAL','type',7,'data',0);
Tag(length(Tag)+1)=struct('name','_DATASET_MAXHEADMOTIONCOIL','type',10,'data','1');
Tag(length(Tag)+1)=struct('name','EndOfParameters','type',-1,'data',[]);
Tag(length(Tag)+1)=struct('name','EndOfParameters','type',-1,'data',[]);
return
% ************* End of function make_dummy_infods*********************************************
% **************************************************************************************
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%Function combineMarkers %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function mrkNew=combineMarkers(mrkOld,nTrialOld,mrk,nTrialNew,res4);
% Combines existing marker information with markers for new trial(s) being added to the
% dataset ny addCTFtral.
% Start by examining the new markers defined in structure mrk.
% Examines structure ds to see if a sensible MarkerFile can be created from ds.mrk.
% Output: mrkNew : New marker structure. If the new markers are invlaid, or empty, then
% mrkNew=struct([]) is returned.
MarkerFileOK=~isempty(mrk);
if MarkerFileOK
if isempty([mrk.trial]) | isempty([mrk.time])
MarkerFileOK=0; % Do not create MarkerFile.mrk if all of the marker classes are empty.
else
% Are the markers appropriate?
minMarkerTrial=min(min([mrk.trial]));
maxMarkerTrial=max(max([mrk.trial]));
minMarkerTime=min(min([mrk.time]));
maxMarkerTime=max(max([mrk.time]));
MarkerFileOK=(maxMarkerTrial<=nTrialNew & minMarkerTrial>=1 & ...
maxMarkerTime<=(res4.no_samples/res4.sample_rate) & ...
minMarkerTime>=(-res4.preTrigPts/res4.sample_rate));
if ~MarkerFileOK
fprintf(['addCTFtrial: Structure mrk cannot possibly be a set of markers ',...
'for %d trial(s) in array(data).\n'],nTrialNew);
fprintf([' minMarkerTrial=%d (must be >=1) ',...
'maxMarkerTrial=%d (must be <=%d)\n'],...
minMarkerTrial,maxMarkerTrial,ds.res4.no_trials);
fprintf([' minMarkerTime=%7.4f (must be >=%7.4f) ',...
'maxMarkerTrial=%7.4f (must be <=%7.4f )\n'],...
minMarkerTime,-res4.preTrigPts/res4.sample_rate,...
maxMarkerTime,res4.no_samples/res4.sample_rate);
fprintf(' MarkerFile.mrk will not be updated.\n');
end
end
end
if MarkerFileOK==0
mrkNew=struct([]); % return an empty marker structure
% Check mrkOld to see if each existing trial had at least one marker.
if isequal(unique([mrkOld.trial]),[1:nTrialOld])
fprintf(['addCTFtrial: All of the trials in the existing data have at least one\n',...
' marked point,but the new trials have no marker points?\n']);
end
return
end
% There are valid new markers. Add the new markers to the existing marker structure,
% and extend the marker definition if new markers have been defined.
% Check the Name
mrkNew=mrkOld;
maxClassId=max([mrkNew.ClassId]);
for k=1:length(mrk)
addq=1;
% Check if the marker is already defined.
for q=1:length(mrkOld)
if strcmp(mrkOld(q).Name,mrk(k).Name)
mrkNew(q).trial=[mrkNew(q).trial mrk(k).trial+nTrialOld];
mrkNew(q).time=[mrkNew(q).time mrk(k).time];
addq=0;
break;
end
end
if addq % Create a new marker class
newClassId=~isfield(mrk(k),'ClassId');
if ~newClassId
newClassId=any(mrk(k).ClassId==[mrkNew.ClassId]);
end
if newClassId
mrk(k).ClassId=max([mrkNew.ClassId])+1;
end
if ~isfield(mrk(k),'Color');mrk(k).Color='Red';end
if ~isfield(mrk(k),'Comment');mrk(k).Comment=char([]);end
if ~isfield(mrk(k),'ClassGroupId');mrk(k).ClassGroupId=3;end
if mrk(k).ClassGroupId==0
if ~isfield(mrk(k),'BitNumber') | ~isfield(mrk(k),'Polarity') | ...
~isfield(mrk(k),'Source') | ~isfield(mrk(k),'Threshold')
fprintf(['addCTFtrial: Structure mrk defines ClassGroupId=0 marker %s, ',...
'but not fields BitNumber, Polarity, Source or Threshold.\n'],mrk(k).Name);
fprintf(' Marker set %s will be defined with ClassGroupId=3.\n',...
mrk(k).Name);
mrk(k).ClassGroupId=3;
end
end
% ClassGroupId : make 4 fields empty.
if mrk(k).ClassGroupId==3
mrk(k).BitNumber=[];
mrk(k).Polarity=[];
mrk(k).Source=[];
mrk(k).Threshold=[];
end
q0=length(mrkNew)+1;
mrkNew(q0)=mrk(k);
mrkNew(q0).trial=mrk(k).trial+nTrialOld;
mrkNew(q0).time=mrk(k).time;
end
clear addq;
end
return
%%%%%%%%%%%%%% end of combineMarkers %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%% Function writeBadSegments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function writeBadSegments(badSegmentsFile,badSegments,nTrial,tTrial);
% Creates a bad.segments file in a CTF data set from the information in structure
% badSegments which is created by read_badSegments, or by the user.
% If structure badSegments is empty, then the file is not created.
% badSegments structure:
% badSegments.trial = List of trial numbers
% badSegments.StartTime = List of bad segment start times (relative to trial).
% badSegments.EndTime = List of bad segment end times.
% Check badSegmentsFile
if exist('badSegmentsFile')~=1;badSegmentsFile=char([]);end
if isempty(badSegmentsFile) | ~ischar(badSegmentsFile)
fprintf('addCTFtrial(writeBadSegments): Bad file name.\n');
badSegmentsFile
return
end
% Check that structure badSegments is defined correctly
if exist('badSegments')~=1 | exist('nTrial')~=1
return
elseif ~isstruct(badSegments) | isempty(badSegments)
return
elseif ~isfield(badSegments,'trial') | ~isfield(badSegments,'StartTime') | ...
~isfield(badSegments,'EndTime')
return
elseif isempty(badSegments.trial) | isempty(badSegments.StartTime) | ...
isempty(badSegments.EndTime)
return
elseif ~isequal(size(badSegments.trial),size(badSegments.StartTime),...
size(badSegments.EndTime))
fprintf(['\naddCTFtrial (writeBadSegments): ',...
'The fields of structure badSegments do not all have the same size.\n']);
return
elseif any(badSegments.trial>nTrial) | any(badSegments.trial<1) | ...
any(badSegments.StartTime<0) | any(badSegments.EndTime>tTrial)
fprintf(['\naddCTFtrial (writeBadSegments): badSegments cannot possibly describe ',...
'bad segments for these data.\n',...
'\tmin(badSegments.trial)=%d max(badSegments.trial)=%d ',...
'min(badSegments.StartTime)=%0.4f max(badSegments.EndTime)=%0.4f s\n\t\tDataset:',...
' nTrial=%d tTrial=%0.4f s\n'],...
min(badSegments.trial),max(badSegments.trial),min(badSegments.StartTime),...
max(badSegments.EndTime),nTrial,tTrial);
fprintf('\t\tNew bad.segments file will not be created.\n\n');
return
end
% Convert all fields to simple vectors
nSeg=prod(size(badSegments.trial));
trial=reshape(badSegments.trial,1,nSeg);
StartTime=reshape(badSegments.StartTime,1,nSeg);
EndTime=reshape(badSegments.EndTime,1,nSeg);
fid=fopen(badSegmentsFile,'w','ieee-be');
if fid<0
fprintf('writeCTFds (writeBadSegments): Could not open file %s\n',badSegmentsFile);
return
end
% Extra tabs are inserted to reproduce the format of bad.segments files produced by
% DataEditor (5.3.0-experimental-linux-20060918).
fprintf(fid,'%0.6g\t\t%0.6g\t\t%0.6g\t\t\n',[trial;StartTime;EndTime]);
fclose(fid);
return
%%%%%%%%% End of writeBadSegments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%Function checkCls %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ClassFileOK=checkCls(ds);
% Examines structure ds to see if a sensible ClassFile can be created from ds.TrialClass.
ClassFileOK=isfield(ds,'TrialClass');
if ClassFileOK
ClassFileOK=~isempty(ds.TrialClass);
end
if ClassFileOK
% Are the class trials appropriate?
minClassTrial=[];
maxClassTrial=[];
for k=1:length(ds.TrialClass)
maxClassTrial=max([maxClassTrial max(ds.TrialClass(k).trial)]);
minClassTrial=min([minClassTrial min(ds.TrialClass(k).trial)]);
end
% Create ClassFile.cls even when the trail classes are empty.
if ~isempty(maxClassTrial)
ClassFileOK=(maxClassTrial<=ds.res4.no_trials & minClassTrial>=1);
if ~ClassFileOK
fprintf(['\nwriteCTFds (checkCls): ds.TrialClass cannot possibly be a set of ',...
'trial classes for array(data).\n minClassTrial=%d (must be >=1) ',...
'maxClassTrial=%d (must be <=%d)\n'],...
minClassTrial,maxClassTrial,ds.res4.no_trials);
fprintf(' ClassFile.cls will not be created.\n');
end
end
end
return
%%%%%%%%%%%%%% end of checkCls %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%Function combineClasses %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function clsNew=combineClasses(clsOld,nTrialOld,cls,nTrialNew);
% Combines existing trial class information with classes for new trial(s) that are
% being added to the dataset by addCTFtral.
% Start by examining the new markers defined in structure mrk.
% Examines structure ds to see if a sensible CLassFile can be created from clsOld and cls.
% Output: clsNew : New class structure. If the new classes are invalid, or empty, then
% clsNew=struct([]) is returned.
ClassFileOK=~isempty(cls);
if ClassFileOK
if isempty([cls.trial])
ClassFileOK=0; % Do not create ClassFile.cls if all of the trial classes are empty.
else
% Are the markers appropriate?
minClassTrial=min(min([cls.trial]));
maxClassTrial=max(max([cls.trial]));
ClassFileOK=(maxClassTrial<=nTrialNew & minClassTrial>=1);
if ~ClassFileOK
fprintf(['addCTFtrial: Structure cls cannot possibly be a set of classes ',...
'for %d trial(s) in array data .\n'],nTrialNew);
fprintf([' minClassTrial=%d (must be >=1) ',...
'maxClassTrial=%d (must be <=%d)\n'],...
minClassTrial,maxClassTrial,nTrialNew);
fprintf(' ClassFile.cls will not be updated.\n');
end
end
end
if ClassFileOK==0
clsNew=struct([]); % return an empty class structure
% Check clsOld to see if each existing trial had at least one class.
if isequal(unique([clsOld.trial]),[1:nTrialOld])
fprintf(['addCTFtrial: All of the trials in the existing data are assigned to at ',...
'least one class\n',...
' but the new trials have no classes?\n']);
end
return
end
% There are valid new classes. Add the new classes to the existing class structure,
% and extend the class definition if new classes have been defined.
clsNew=clsOld;
maxClassId=max([clsNew.ClassId]);
for k=1:length(cls)
addq=1;
% Check if the class is already defined.
for q=1:length(clsOld)
if strcmp(clsOld(q).Name,cls(k).Name)
clsNew(q).trial=[clsNew(q).trial cls(k).trial+nTrialOld];
addq=0;
break;
end
end
if addq % Create a new trial class
newClassId=~isfield(cls(k),'ClassId');
if ~newClassId % Check if cls(k).ClassId is already in use.
newClassId=any(cls(k).ClassId==[clsNew.ClassId]);
end
if newClassId
cls(k).ClassId=max([clsNew.ClassId])+1;
end
if ~isfield(cls(k),'Color');cls(k).Color='Red';end
if ~isfield(cls(k),'Comment');cls(k).Comment=char([]);end
if ~isfield(cls(k),'ClassGroupId');cls(k).ClassGroupId=3;end
q0=length(clsNew)+1;
clsNew(q0)=cls(k);
clsNew(q0).trial=cls(k).trial+nTrialOld;
end
clear addq;
end
return
%%%%%%%%%%%%%% end of combineClasses %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%% Function writeClassFile %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function writeClassFile(ClassFile,TrialClass);
% Write the ClassFile of a CTF data set.
% The CLassFile allows a user to store a list of trial classifications in a data set.
% The ClassFile format is defined in document CTF MEG File Formats, PN900-0088.
% This format is rigid.
% Inputs :
% ClassFile : marker file including the full path and extension .mrk.
% TrialClass : Structure creted by read_ClassFile.
% Output : ClassFile.cls.
% Check input TrialClass.
if exist('TrialClass')~=1;TrialClass=[];end
if isempty(TrialClass) | ~isstruct(TrialClass)
fprintf('writeCTFds (writeClassFile): TrialClass is empty or is not a structure.\n');
TrialClass
return
end
% Check ClassFile
if exist('ClassFile')~=1;ClassFile=char([]);end
if isempty(ClassFile) | ~ischar(ClassFile)
fprintf('writeCTFds (writeClassFile): Bad file name.\n');
ClassFile
end
fid=fopen(ClassFile,'w','ieee-be');
if fid<0
fprintf('writeCTFds (writeClassFile): Could not open file %s\n',ClassFile);
return
end
nClass=length(TrialClass);
% Generate datasetname from ClassFIle.
ksep=max([0 strfind(ClassFile,filesep)]);
datasetname=ClassFile(1:ksep-1);
if isempty(datasetname);datasetname=cd;end
fprintf(fid,'PATH OF DATASET:\n%s\n\n\n',datasetname);
fprintf(fid,'NUMBER OF CLASSES:\n%d\n\n\n',nClass);
for k=1:nClass
if k==1 % Add sign character to make output match the output of Acq.
sgn=char([]); % There should be no real significance to this.
else % Why does DataEditor places the + sign only on ClassID 2,3,...?
sgn='+';
end
No_of_Trials=prod(size(TrialClass(k).trial));
fprintf(fid,'CLASSGROUPID:\n%s%d\nNAME:\n%s\nCOMMENT:\n%s\n',...
sgn,TrialClass(k).ClassGroupId,TrialClass(k).Name,TrialClass(k).Comment);
fprintf(fid,'COLOR:\n%s\nEDITABLE:\n%s\nCLASSID:\n%s%d\nNUMBER OF TRIALS:\n%d\n',...
TrialClass(k).Color,TrialClass(k).Editable,sgn,TrialClass(k).ClassId,No_of_Trials);
fprintf(fid,'LIST OF TRIALS:\nTRIAL NUMBER\n');
% Subtract one so trial numbering starts at 0 in ClassFile.cls
fprintf(fid,'%20d\n',reshape(TrialClass(k).trial,1,No_of_Trials)-1);
fprintf(fid,'\n\n');
end
fclose(fid);
return
%%%%%%%%%%%%%% end of writeClassFile %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%% Function updateCreatorSoftware %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ds=updateCreatorSoftware(ds,creatorSoftware,originalCreatorSoftware);
% Changes the creator software fields of the ds structure, and returns ds=struct([]) if
% field infods is missing from structure ds, or if it thinks that the dataset was not
% created by the MATLAB code specified by originalCreatorSoftware (i.e. writeCTFds).
% Makes sure that creatorSoftware info is changed in structure infods, newds and res4.
% Inputs: ds : ds structure produced by readCTFds.
% creatorSoftware : Character string indicating that the data set was
% modified by addCTFtrial. Added to infods tags listed in addCreatorTag and
% appName field of res4.
% originalCreatorSoftware : Character string indicating that the data set was
% created by writeCTFds. Added to infods tags listed in addCreatorTag and
% appName field of res4.
% Output: ds : ds structure with changes to ds.infids, ds.res4, ds.newds.
% If the input ds structure does not indicate that iot was created by
% writeCTFds (originalCreatorSoftware), ds=struct([]) is returned.
% Adds comment (clinical use message) and creator software name to infods, newds and hist files.
if ~isfield(ds,'infods');
fprintf(['addCTFtrial (updateCreatorSoftware): Structure ds does not include',...
' field infods.\n']);
whos ds
ds=struct([]); % Force an error in the calling program
return
end
% The infods tags and red4 fields that display creator software must also indicate that
% the dataset was created by originalCreatorSoftware.
% infods tags that will display the creator software.
addCreatorTag=strvcat('_PROCEDURE_COMMENTS','_DATASET_STATUS',...
'_DATASET_COLLECTIONSOFTWARE','_DATASET_CREATORSOFTWARE');
% res4 text fields that will display the creator software.
addCreatorField=strvcat('appName','run_description');
addCreatorLength=[256 -1]'; % -1 indicates variable length
if exist('creatorSoftware')~=1;
creatorSoftware=char([]);
elseif ~ischar(creatorSoftware)
creatorSoftware=char([]);
else
creatorSoftware=deblank(creatorSoftware);
end
if exist('originalCreatorSoftware')~=1;
originalCreatorSoftware=char([]);
elseif ~ischar(originalCreatorSoftware)
originalCreatorSoftware=char([]);
else
originalCreatorSoftware=deblank(originalCreatorSoftware);
end
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Check that the string originalCreatorSoftware appears in the infods and res4 files.
tagName=getArrayField(ds.infods,'name')';
if length(ds.infods)==1;tagName=tagName';end
% Update the infods fields.
for k=1:size(addCreatorTag,1)
q=strmatch(deblank(addCreatorTag(k,:)),tagName);
if isempty(q);
fprintf('addCTFtrial (updateCreatorSoftware): Tag %s is missing from ds.infods.\n',...
deblank(addCreatorTag(k,:)));
ds=struct([]);
return
elseif length(q)>1
fprintf(['addCTFtrial (updateCreatorSoftware): Tag %s appears %d times in ',...
'ds.infods.\n'],deblank(addCreatorTag(k,:)),length(q));
ds=struct([]);
return
else
strng=ds.infods(q).data;
% Strng must contain originalCreatorSoftware
nChar=length(strng);
if length(originalCreatorSoftware)>0
qpos=strfind(strng,originalCreatorSoftware);
if isempty(qpos)
fprintf(['addCTFtrial (updateCreatorSoftware): String %s does not appear in',...
' ds.infods tag %s\n'],originalCreatorSoftware,addCreatorTag(k,:));
fprintf([' This dataset was not created ',...
'by CTF MATLAB Export software.\n']);
ds=struct([]);
return
end
qpos=qpos+length(originalCreatorSoftware)-1;
else
qpos=length(strng);
end
% Add creatorSoftware string if it is not already present.
if isempty(strfind(strng,creatorSoftware))
ds.infods(q).data=[strng(1:qpos) ' ' creatorSoftware ' ' strng(qpos+1:nChar)];
end
end
end
% Update the res4 fields: add creatorSoftware message.
% Don't check field length. Truncate later.
for q=1:size(addCreatorField,1);
strng=deblank(getfield(ds.res4,deblank(addCreatorField(q,:))));
nChar=length(strng);
if length(originalCreatorSoftware)>0
qpos=strfind(strng,originalCreatorSoftware);
if isempty(qpos)
fprintf(['addCTFtrial (updateCreatorSoftware): String %s does not appear in',...
' ds.res4.%s\n'],originalCreatorSoftware,deblank(addCreatorField(q,:)));
fprintf([' This dataset was not created ',...
'by CTF MATLAB Export software.\n']);
ds=struct([]);
return
end
qpos=qpos+length(originalCreatorSoftware);
else
qpos=nChar;
end
% Add creatorSoftware string if it is not already present.
if isempty(strfind(strng,creatorSoftware))
newStrng=[strng(1:qpos) ' ' creatorSoftware ' ' strng(qpos+1:nChar)];
ds.res4=setfield(ds.res4,deblank(addCreatorField(q,:)),newStrng);
end
end
clear q strng nChar strng0 ns newStrng;
% Update res4.run_description
ds.res4.run_description=[deblank(ds.res4.run_description),char(0)];
ds.res4.rdlen=length(ds.res4.run_description);
% Truncate the .res4. fields. Leave room for a final char(0).
for q=1:size(addCreatorField,1);
strng=deblank(getfield(ds.res4,deblank(addCreatorField(q,:))));
if length(strng)>addCreatorLength(q)-1 & addCreatorLength(q)>0
ds.res4=setfield(ds.res4,deblank(addCreatorField(q,:)),...
strng(length(strng)+[-addCreatorLength(q)+2:0]));
end
end
clear q strng;
% Add the creator and comment information to the newds file
if isfield(ds,'newds');
nChar=length(ds.newds);
% Keyword positions
aNpos=max(strfind(ds.newds,[char(9) 'appName:' char(9)]));
if isempty(aNpos)
fprintf(['addCTFtrial (updateCreatorSoftware): Keyword ''appName'' ',...
'does not appear in ds.newds.\n',...
' set ds.newds=[].\n']);
ds.newds=char([]);
else
eol=max([11 min(strfind(ds.newds(aNpos+1:length(ds.newds)),char(10)))]);
wPos=min(strfind(ds.newds(aNpos+[1:eol]),originalCreatorSoftware));
addPos=min(strfind(ds.newds(aNpos+[1:eol]),creatorSoftware));
if isempty(addPos)
if isempty(wPos)
ds.newds=[ds.newds(1:(aNpos+eol-1)) ' ' creatorSoftware ...
ds.newds((aNpos+eol):length(ds.newds))];
else
ds.newds=[ds.newds(1:(aNpos+wPos+length(originalCreatorSoftware)-1)) ', ' ...
creatorSoftware ...
ds.newds((aNpos+wPos+length(originalCreatorSoftware)):length(ds.newds))];
end
end
clear eol wPos addPos;
end
clear nChar aNpos;
end
return
%%%%%%%%%%%%%% End of update_creatorSoftware %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%% Function updateHLC %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [infods,status]=updateHLC(infods,HLCdata,HLC0,nTrial0);
% Adds notes and continuous-head-localization tags to .infods file.
% Updates MAXHEADMOTION tags when called from addCTFtrial
% Inputs : infods : Structure of tags to be written to output infods file.
% HLCdata : 0 or [] or not defined - There are no HLC channels
% (head-coil position) in the data. Just pass the existing tags to
% the output dataset.
% HLCdata : real array : size(HLCdata)=[samplesPerTrial 3 Ncoil nTrial]
% Calculate the head motion tags.
% HLC0 : Head coil positions (m) in dewar coordinates at the start of the run.
% size(HLC0)=[3 Ncoil]
% nTrial0=No. of trials of data already written to the dataset.
% Outputs : status : 0: Everything looks OK
% 1: Couldn't find _DATASET tags.
% <0: There is a problem with the new infods file.
% Calls:
% - getArrayField: Extracts field names from structure array S.
% Defaults for the head localization tags.
% Might do this better with a structure.
HZ_MODE_UNKNOWN=2^31-1; % Bug in DataEditor and acquisition software, Oct. 2006
% Should be -1.
% New dataset tags for HLC specification.
addTag=strvcat('_DATASET_HZ_MODE',...
'_DATASET_MOTIONTOLERANCE',...
'_DATASET_MAXHEADMOTION',...
'_DATASET_MAXHEADMOTIONTRIAL',...
'_DATASET_MAXHEADMOTIONCOIL');
addTagType=[5 4 4 7 10]';
if exist('nTrial0')~=1
nTrial0=0;
elseif isempty(nTrial0)
nTrial0=0;
elseif min(nTrial0)<0
nTrial0=0;
end
% Check HLCdata array. HLCdata=[] indicates no continuous head localization.
if exist('HLCdata')~=1
HLCdata=[];
elseif ~isempty(HLCdata)
[samplesPerTrial nDim Ncoil nTrial]=size(HLCdata);
if nDim~=3;
fprintf('addCTFtrial (updateHLC): size(HLCdata)=[');fprintf(' %d',size(HLCdata));
fprintf(']\n');
fprintf(' nDim=%d?? Setting HLCdata=[].\n',nDim);
HLCdata=[];
end
end
if exist('HLC0')~=1
HLC0=[];
elseif ~isequal(size(HLC0),[3 size(HLCdata,3)])
HLC0=[];
end
if isempty(HLC0) & ~isempty(HLCdata)
HLC0=squeeze(HLCdata(1,:,:,1));
end
% Assume that all the tag names are different. There is no checking when a tag listed in
% addTag matches more than one entry in array name.
name=getArrayField(infods,'name')'; %size(name)=[nTag lengthTag]
DATASET_tags=strmatch('_DATASET',name)'; % size(DATASET_tags)=[1 nTag]
if isempty(DATASET_tags)
status=1; % No _DATASET tags. Don't add anything.
else
status=0;
if isempty(HLCdata)
TagValue(1)=HZ_MODE_UNKNOWN;
TextTagValue=char(0);
addTag=addTag(1,:); % Remove the other HLC tags
addTagType=addTagType(1);
else % ~isempty(HLCdata)
% Remove HLC offsets.
for q=1:Ncoil
for k=1:3
HLCdata(:,k,q,:)=HLCdata(:,k,q,:)-HLC0(k,q);
end
end
% Calculate motions as displacement from the start of the dataset.
absMotion=squeeze(sqrt(sum(HLCdata.^2,2))); %size(absMotion)=[samplesPerTrial Ncoil nTrial]
maxCoilMotion=squeeze(max(absMotion,[],1)); % size(maxCoilMovement)=[Ncoil nTrial]
maxHeadMotion=max(max(maxCoilMotion));
[mx maxHeadMotionCoil]=max(max(maxCoilMotion,[],2));
[mx maxHeadMotionTrial]=max(max(maxCoilMotion,[],1));
% Create a list of head motion tag values
TagValue(1)=5; % Indicates continuous head localization
TagValue(2)=max(2*maxHeadMotion,0.02); % _DATASET_MOTIONTOLERANCE
TagValue(3)=maxHeadMotion;
TagValue(4)=maxHeadMotionTrial-1+nTrial0; % _DATASET_MAXHEADMOTIONTRIAL
TextTagValue=strvcat(char(zeros(4,1)),sprintf('%d',maxHeadMotionCoil));
% Does the existing infods have the head-motion tags?
TagNo2=strmatch(deblank(addTag(2,:)),name,'exact');
TagNo3=strmatch(deblank(addTag(3,:)),name,'exact');
TagNo4=strmatch(deblank(addTag(4,:)),name,'exact');
TagNo5=strmatch(deblank(addTag(5,:)),name,'exact');
if ~isempty(TagNo2) & ~isempty(TagNo3) & ~isempty(TagNo4) & ...
~isempty(TagNo5) & nTrial0>0
% Structure infods already has the head-motions tags from previous data.
TagValue(2)=max(TagValue(2),infods(TagNo2).data);
if TagValue(3)<=infods(TagNo3).data
TagValue(3)=infods(TagNo3).data;
TagValue(4)=infods(TagNo4).data;
TextTagValue=strvcat(char(zeros(4,1)),infods(TagNo5).data);
end
elseif (~isempty(TagNo2) | ~isempty(TagNo3) | ~isempty(TagNo4) | ...
~isempty(TagNo5)) & nTrial0>0
fprintf(['addCTFtrial (updateHLC): Some, but not all, of the ds.infods CHL ',...
'tags are defined.\n',...
' Infods will be defines with information from the %d new ',...
'trial(s) being added.\n'],size(HLCdata,4));
end
TagValue=[TagValue 0]; % Placeholder only since the 5th tag is a text string.
end
% Add or insert tags.
for q=1:size(addTag,1)
nTag=length(infods);
tagName=deblank(addTag(q,:));
TagNo=strmatch(tagName,name,'exact')';
if isempty(TagNo) % Insert a tag at the end of the _DATASET tags.
TagNo=max(DATASET_tags)+1;
infods((TagNo+1):(nTag+1))=infods(TagNo:nTag);
name=strvcat(name(1:TagNo-1,:),tagName,name(TagNo:nTag,:));
DATASET_tags=[DATASET_tags TagNo];
end
if addTagType(q)~=10
infods(TagNo)=struct('name',tagName,'type',addTagType(q),'data',TagValue(q));
else
infods(TagNo)=struct('name',tagName,'type',addTagType(q),...
'data',deblank(TextTagValue(q,:)));
end
end % End loop over head position and head motion tags.
clear q TagNo TextTagValue TagValue;
end % End section add _DATASET tags
return
%%%%%%%%%%%%%% End of updateHLC %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%% Function getArrayField %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function x=getArrayField(S,yfield)
% Extracts one field of a structure array.
% Inputs: S : structure array.
% yfield: name of field of S (string)
% Output: x. x(:,n)=S(n).yfield; size(x)=[size(yfield) length(S)]
% Field sizes: Two options:
% 1. size(S(n).yfield) is the same for all n. Any size allowed.
% 2. S(n).yfield is a 2-D array for all structure elements S(n).
% Then yfield of different array elements S(n) can have different sizes.
% The array returned will be large enough to accomodate all of the data.
sizeS=size(S);
nS=prod(sizeS);
S=reshape(S,1,nS);
% Determine which array-size option to use.
sizey=size(getfield(S,{1},yfield));
option1=1;
option2=(length(sizey)==2);
for n=2:nS
sizeyn=size(getfield(S,{n},yfield));
option1=option1 & isequal(sizey,sizeyn);
option2=option2 & length(sizeyn)==2;
if option2
sizey=max([sizey;sizeyn],[],1);
end
end
if option1 % All fields have the same size
nY=prod(sizey);
if isnumeric(getfield(S,{1},yfield))
x=zeros(nY,nS);
elseif ischar(getfield(S,{1},yfield))
x=char(zeros(nY,nS));
end
for n=1:nS
x(:,n)=reshape(getfield(S,{n},yfield),nY,1);
end
x=reshape(x,[sizey nS]);
elseif option2 % All fields have only two dimensions
if isnumeric(getfield(S,{1},yfield))
x=zeros([sizey nS]);
elseif ischar(getfield(S,{1},yfield))
x=char(zeros([sizey nS]));
end
for n=1:nS
y=getfield(S,{n},yfield);
sizeyn=size(y);
x(1:sizeyn(1),1:sizeyn(2),n)=y;
end
else
fprintf(['getArrayField: Field %s of the structure array has >2 dimensions ',...
'and not all field have the same size.\n'],yfield);
x=[];
end
x=squeeze(x);
return
%%%%%%%% End of getArrayField %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
github
|
philippboehmsturm/antx-master
|
setCTFDataBalance.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/ctf/setCTFDataBalance.m
| 32,056 |
utf_8
|
894c3744554abe635876ce6944dca0cd
|
function [data,ds]=setCTFDataBalance(data,ds,balance1,unit,chanList,messages);
% Version 1.1 13 April 2007 Mod to chanList: If chanList is omitted and
% size(data,2)<ds.res4.no_channels, then setCTFDataBalance
% sets chanList=1:size(data,2) and prints a warning the first
% time it happens.
% 7 Dec. 2006. Fixed a bug. Changed calls to getCTFBalanceCoefs so
% setCTFDataBalance would balance and unbalance reference gradiometers.
% Version 1.0 27 October 2006
% Adjusts the gradient order balance from balance0 to balance1.
% Inputs :
% data : Array of data to be balanced. precision= single or double.
% size(data)=[Npt Nchan Ntrial]. If chanList is not supplied, it is assumed that
% array data has dataset channels 1:Nchan (i.e. data is not just SQUID sensors
% although only SQUID channels are affected by setCTFDataBalance.)
% ds : Structure produced by readCTFds that describes the dataset.
% balance1 : Character array defining balance of the output data.
% Parameter balance1 must be specified, even if it is only balance1=[];
% balance1=[],' ' or 'NONE' : Output is unbalanced.
% size(balance,1)=1 : MEG balancing. Assume no reference balancing.
% size(balance,1)=2 : MEG balance = balance(1,:).
% Gref balance = balance(2,:)
% unit : Options : [],' ', 'fT', or 'T' : Physical unit
% 'int' or 'phi0' : Raw units.
% If the unit argument is not included, unit is set to 'fT'.
% chanList : Optional list of dataset channels included in array data.
% Channel numbering is referred to structure ds (the output of readCTFds).
% If length(chanList)=Nchan.
% data(:,k,q)=trial q of channel chanList(k) of the dataset.
% If chanList=[],<0 or not defined : Array data has dataset channels 1:Nchan.
% Otherwise, length(chanList)=Nchan=size(data,2).
% If length(chanList)~=size(data,2) : Error.
% messages=0: Don't print tracing message
% =1: Print a message when there is a change in requested balance.
% =2: Always print a message
% Outputs: data: Data with balanced SQUID signals. Set data=[] on failure.
% ds: ds structure for balanced data. Set ds=-1 on failure.
% In any event, print error messages.if exist('messages')~=1;messages=1;end
% The balance and unbalance is made complicated because this code allows for situations
% where the reference gradiometers are also balanced (although this option seems never
% to be used).
% Function calls: Most functions are called only once, and are intended to be
% called only by setCTFDataBalance or its subprograms.
% - getCTFBalanceCoefs. Called by balance_data and unbalance_data. Gets the balance
% tables from structure ds.
% Included in this listing:
% - getDsBalance: Gets the current balance state of the data and checks for error in
% the grad_order_no field of ds.rs4.senres.
% - check_balance : Makes balance1 into [2 4] character arrays.
% - unbalance_data : Converts data from balance0 to unbalanced.
% - balance_data: Converts data from unbalanced to balance1.
% - reindex : Called by functions unbalance_data and balance_data to re-order indices
% when chanList does not include all the channels, or the channels have
% been reordered in array data.
% If virtual memory is a problem, consider bringing functions balance_data and
% unbalance_data into the code. In the present configuration, a copy of array data is
% made when these functions are called.
% In the event of an error, returns data=[], ds1=-1 This should force an error in the
% calling program.
persistent chanListWarning
if nargout==0 & nargin==0
fprintf(['\nsetCTFDataBalance: Version 1.1 13 April 2007 ',...
'Balances MEG data.\n',...
'\t\tCall : ',...
'[data1,ds1]=setCTFDataBalance(data0,ds0,balance1,unit,chanList,messages);\n\n']);
return
end
buffsize=6e6; % process blocks of buffsize words (=8*buffsize bytes) at a time
balanceOptions=strvcat('NONE','G1BR','G2BR','G3BR');
unit_options=strvcat('fT','T','phi0','int');
default_unit='fT';
% Check that the inputs are sensible.
if nargin<3
fprintf(['\nsetCTFDataBalance: Only %d input arguments? ',...
'Must specify at least data, ds and balance.\n\n'],nargin);
data=[];ds=-1;
return
elseif ~any(strmatch(class(data),strvcat('single','double'))) | isempty(data) | ...
~isstruct(ds) | isempty(ds) | isempty(balance1) |~ischar(balance1)
fprintf('\nsetCTFDataBalance: Wrong argument types or sizes.\n\n');
whos data ds balance1
data=[];ds=-1;
return
elseif ~isfield(ds,'res4')
fprintf('\nsetCTFDataBalance: Field res4 is missing from structure ds.\n\n');
ds
data=[];ds=-1;
return
end
if nargout~=2
fprintf(['\nsetCTFDataBalance: %d output arguments specified. ',...
'Must have 2 outputs (data,ds).\n\n'],nargout);
data=[];ds=-1;
return
end
% Single or double precision data.
prec=class(data);
% Force upper-case characters
balance1=upper(balance1);
% Check that arrays data and chanList are consistent and sensible
if size(data,2)>ds.res4.no_channels
fprintf('\nsetCTFDataBalance: ds.res4.no_channels=%d, but size data=[',...
ds.res4.no_channels);
fprintf(' %d',size(data));fprintf(']\n\n');
data=[];ds=-1;
return
end
if exist('chanList')~=1;chanList=[];end
if ~isempty(chanList) % chanList~=[]. Check chanList
if ~isnumeric(chanList)
fprintf('\nsetCTFDataBalance: chanList has the wrong type.\n\n');
whos data ds balance1 chanList
data=[];ds=-1;
return
else % chanList is numeric and non-empty
% Check that chanList is a vector
if sum(size(chanList)>1)>1
fprintf('\nsetCTFDataBalance: size(chanList)=[');fprintf(' %d',size(chanList));
fprintf('] Not a vector.\n\n');
data=[];ds=-1; % Force an error in the calling program
return
else
chanList=reshape(chanList,1,length(chanList)); % chanList is a row vector.
if any(chanList<=0) | any(chanList>ds.res4.no_channels) | ...
length(chanList)~=size(data,2)
fprintf('setCTFDataBalance: Error in input chanList:\n');
fprintf(' min(chanList)=%d max(chanList)=%d Dataset has %d channels.\n',...
min(chanList),max(chanList),ds.res4.no_channels);
fprintf('length(chanList)=%d size(data)=[',length(chanList));
fprintf(' %d',size(data));
fprintf('] Must have length(chanList)=size(data,2)\n');
data=[];ds=-1; % Force an error in the calling program
return
end
end
end
else % chanList=[]. Array data must include all of the channels.
if size(data,2)<ds.res4.no_channels
if isempty(chanListWarning)
fprintf('setCTFDataBalance: No chanList supplied and size(data)=[');
fprintf(' %d',size(data));fprintf(']\n');
fprintf(' Set chanList=1:%d\n',size(data,2));
fprintf(' No. of channels=ds.res4.no_channels=%d\n',...
ds.res4.no_channels);
chanListWarning=1;
end
chanList=1:size(data,2);
end
end
% Check the data units, convert to lower case and flag incorrect unit specification
if ~exist('unit');
unit=default_unit;
elseif isempty(unit);
unit=default_unit;
elseif ~ischar(unit)
fprintf('\nsetCTFDataBalance: Input unit has the wrong type: class(unit)=%s\n\n',...
class(unit));
data=[];ds=-1;
return
end
unit=lower(unit);
if isempty(strmatch(unit,lower(unit_options)))
fprintf('\nsetCTFDataBalance: unit=%s. Must be one of',unit);
for k=1:size(unit_options,1);fprintf(' %s',unit_options(k,:));end;fprintf('\n');
data=[];ds=-1; % Force an error in the calling program
return
end
% Make sure message request is sensible. This is important only as a way of checking
% that the input list is sensible. The value of messages does not affect the output of
% setCTFDataBalance.
if exist('messages')~=1;messages=1;end
if ~isnumeric(messages)
fprintf(['\nsetCTFDataBalance: Input messages has the wrong type: ',...
'class(messages)=%s\n\n'],class(messages));
data=[];ds=-1;
return
elseif isempty(messages);
messages=1;
elseif ~isequal(size(messages),[1 1])
fprintf('\nsetCTFDataBalance: Input messages doesn''t make sense. size(messages)=[');
fprintf(' %d',size(messages));fprintf('] (Must be [1 1])\n\n');
data=[];ds=-1;
return
elseif messages<0 | messages>2
fprintf('\nsetCTFDataBalance: Input messages=%d. Must be [], 0, 1 or 2.\n\n',messages);
data=[];ds=-1;
return
end
% Process data in blocks of nChBlock channels to reduce virtual memory demand.
nChBlock=max(1,floor(buffsize/size(data,1)));
% badGref = list of bad reference gradiometers referred to dataset channel numbering.
% badGMEG = list of bad MEG gradiometers referred to dataset channel numbering.
% These gradiometers are considered bad because their grad_order_no is wrong, not
% because thay are listed in ds.BadChannels
[balance0,badGref,badGMEG,Greflist,GMEGlist]=getDsBalance(ds);
if strmatch('BAD',balance0)
fprintf(['\nsetCTFDataBalance: The balance order of the Grefs and/or the MEG ',...
'channels cannot be determined.\n',...
' Check ds.res4.senres().grad_order_no.\n\n']);
data=[];ds=-1; % Force an error in the calling program
return
end
% Check balance1 and put in a standard form.
balance1=check_balance(balance1);
if isempty(balance1) | isempty(balance0)
fprintf(['\nsetCTFDataBalance: size(ds balance) =[%d %d] (after call to ',...
'getDsBalance.)\n',...
' size(new balance)=[%d %d] (after call to check_balance.)\n\n'],...
size(balance0),size(balance1));
data=[];ds=-1; % Force an error in the calling program
return
end
% Print a message?
chanset=strvcat('MEGs','Grefs');
for k=1:2
if messages==2 | (messages==1 & ~strcmp(balance0(k,:),balance1(k,:)))
fprintf('setCTFDataBalance: Adjusting %s from balance=%s to balance=%s.\n',...
chanset(k,:),balance0(k,:),balance1(k,:));
end
end
clear k chanset;
if isequal(balance0,balance1)
return
end
% Convert from balance0 to unbalanced.
if ~isequal(balance0,strvcat('NONE','NONE'));
data=unbalance_data(data,ds,balance0,unit,nChBlock,chanList,badGref);
% unbalance_data returns data=[] when list badGref includes a Gref that is required for
% balancing.
if isempty(data);ds=-1;return;end
end
% Convert from unbalanced to balance1.
if ~isequal(balance1,strvcat('NONE','NONE'));
% balance_data returns data=[] when badGref includes a Gref that is required for
% balancing.
data=balance_data(data,ds,balance1,unit,nChBlock,chanList,badGref,messages);
if isempty(data);ds=-1;return;end
end
% Mark the balance order in structure ds.
% Make sure that the bad channels are marked with a different order. This will force
% errors if these data are used later. Set the data in the bad channels to zero, and add
% the bad channels to ds.BadChannels.
Gorder=strmatch(balance1(2,:),balanceOptions)-1;
MEGorder=strmatch(balance1(1,:),balanceOptions)-1;
for k=setdiff(Greflist,badGref)
ds.res4.senres(k).grad_order_no=Gorder;
end
for k=setdiff(GMEGlist,badGMEG)
ds.res4.senres(k).grad_order_no=MEGorder;
end
for k=badGref
ds.res4.senres(k).grad_order_no=0;
end
for k=badGMEG
ds.res4.senres(k).grad_order_no=round(3-MEGorder);
end
% Set channels with bad balance order parameter to zero.
kBad=[badGref badGMEG];
if ~isempty(chanList)
kBad=reindex(chanList,intersect(chanList,kBad));
end
for k=kBad
if strcmp(prec,'single')
data(:,k,:)=single(zeros(size(data,1),1,size(data,3)));
else
data(:,k,:)=zeros(size(data,1),1,size(data,3));
end
end
clear k Gorder MEGorder;
if isempty([badGref badGMEG]);return;end
% Add bad channels to ds.BadChannels
if ~isfield(ds,'BadChannels');ds.BadChannels=char([]);end
BadList=union(badGref,badGMEG);
if ~isempty(ds.BadChannels)
for k=1:size(ds.BadChannels,1)
BadList=[BadList strmatch(deblank(ds.BadChannels(k,:)),ds.res4.chanNames)];
end
ds.BadChannels=char([]);
end
for k=sort(BadList)
ds.BadChannels=strvcat(ds.BadChannels,strtok(ds.res4.chanNames(k,:),'- '));
end
return
% ************** End of function setCTFDataBalance **********************************
% **********************************************************************************
% ********************************************************************************
% ******************* function getDsBalance **************************************
function [dsbalance,badGref,badGMEG,Greflist,GMEGlist]=getDsBalance(ds);
% Get the current balance state from structure ds. Check for channels that are marked
% as bad by having a different grad_order_no.
% Check whether things make sense.
% Return the balance and lists of bad gradiometers.
% Also return the complete list of reference gradiometers and MEG gradiometers since
% setCTFDataBalance uses them.
% In normal operation, getDsBalance will return badGref=[], badGMEG=[];
balanceOptions=strvcat('NONE','G1BR','G2BR','G3BR');
Greflist=[]; % List of reference gradiometers (sensorTypeIndex=1)
Greforder=[];
GMEGlist=[]; % List of MEG gradiometers (sensorTypeIndex=5)
GMEGorder=[];
% Make lists of sensors and gradient balancing.
for k=1:ds.res4.no_channels
if ds.res4.senres(k).sensorTypeIndex==1
Greflist=[Greflist k];
Greforder=[Greforder ds.res4.senres(k).grad_order_no];
elseif ds.res4.senres(k).sensorTypeIndex==5
GMEGlist=[GMEGlist k];
GMEGorder=[GMEGorder ds.res4.senres(k).grad_order_no];
end
end
% Reference balance OK?
dsbalance=char(zeros(2,4));
if any(Greforder<0) | any(Greforder>1)
fprintf(['\nsetCTFDataBalance: The reference gradiometer balance orders make no ',...
'sense.\n %2d Gref channels. %2d have grad_order_no=0\n'],...
length(Greflist),sum(Greforder==0));
fprintf(' %2d have grad_order_no=1\n',sum(Greforder==1));
fprintf(' %2d have grad_order_no<0 or >1\n',...
sum(Greforder>1)+sum(Greforder<0));
dsbalance=strvcat(dsbalance(1,:),'BAD');
badGref=Greflist; % Mark everything bad
elseif sum(Greforder==0)>sum(Greforder==1)
dsbalance=strvcat(dsbalance(1,:),balanceOptions(1,:));
badGref=Greflist(find(Greforder~=0));
else
dsbalance=strvcat(dsbalance(1,:),balanceOptions(2,:));
badGref=Greflist(find(Greforder~=1));
end
% Sort MEG gradiometer balance. In correct operation, all MEG channels should have the
% same balance (0,1,2 or 3).
for bal=0:3
nMEGbal(bal+1)=sum(GMEGorder==bal);
end
[maxbal MEGorder]=max(nMEGbal);
MEGorder=MEGorder-1;
if maxbal>ceil(0.5*length(GMEGlist)) & all(GMEGorder>=0) & all(GMEGorder<=3)
dsbalance(1,:)=balanceOptions(MEGorder+1,:);
badGMEG=GMEGlist(GMEGorder~=MEGorder);
else
fprintf('\nsetCTFDataBalance: The MEG-sensor balance orders make no sense.\n');
fprintf(' %3d MEG gradiometer channels.\n',length(GMEGlist));
fprintf(' %3d have grad_order_no=%d\n',[nMEGbal;0:3]);
if sum(nMEGbal)<length(GMEGlist)
fprintf(' %3d have grad_order_no<0 or >3\n\n',...
length(GMEGlist)-sum(nMEGbal));
end
dsbalance=strvcat('BAD',dsbalance(2,:));
badGMEG=GMEGlist; % Mark everything bad`
end
return
% ************** End of function getDsBalance **********************************
% **********************************************************************************
% ********************************************************************************
% ******************* function check_balance **************************************
function balance=check_balance(balance);
% make sure that character array balance has the correct format.
balance_options=strvcat('NONE','G1BR','G2BR','G3BR');
% Make balance into a [4 2] character array
if ~ischar(balance) & ~isempty(balance)
fprintf('setCTFDataBalance (check_balance): balance is not a character array.\n');
balance=char([]); % Force an error.
return;
elseif isempty(deblank(balance))
balance=strvcat('NONE','NONE');
return
elseif size(balance,1)==1
balance=strvcat(balance,'NONE'); % No Gref balancing
elseif size(balance,1)>2
fprintf('setCTFDataBalance (check_balance): size(balance)=[%d %d]?\n',size(balance));
balance=char([]); % Force an error.
return
end
balance=upper(balance);
if size(balance,2)>4;balance=balance(:,1:4);end
for k=1:2 % k=1:MEGs, k=2:Grefs
if isempty(deblank(balance(k,:)));
balance(k,:)='NONE';
elseif isempty(strmatch(balance(k,:),balance_options(1:(6-2*k),:)))
fprintf('check_balance: balance(%d,:)=%s Not an allowed option.\n',k,balance(k,:));
balance=char([]); % Force an error?
return
end
end
return
% ************** End of function check_balance **********************************
% **********************************************************************************
% ************************************************************************
% ****** Convert from balanced to unbalanced data **********************
function data=unbalance_data(data,ds,balance0,unit,nChBlock,chanList,badGref);
% Inputs: data: Data array. size(data)=[Npt Nchan Ntrial]
% ds: ds strtcuture for the data.
% balance0: balance0(1,:) = MEG balance before unbalancing
% balance0(2,:) = Gref balance before unbalancing
% unit : 'ft','t' (physical units)
% 'int', 'phi0'
% chanList: List if channels included in array data (referred to the channel
% numbering in structure ds)
% badGref: A list of gRef channels markes as bad because they seen to have the
% wrong grad_order_no.
if ~exist('chanList');chanList=[];end
prec=class(data);
% Read the balance tables for both MEG and reference gradiometers.
% Usually balance0(2,:)='NONE', and it returns alphaGref=[].
[alphaMEG,MEGindex,MEGbalanceindex,alphaGref,Grefindex,Gbalanceindex]=...
getCTFBalanceCoefs(ds,balance0,unit);
% Unbalance the Grefs first. In almost all cases, balance0(2,:)='NONE',
% so the program will skip this section.
if ~strcmp(upper(balance0(2,:)),'NONE')
% The index lists give channel numbers referred to data set channel numbering
if isempty(Grefindex) | isempty(Gbalanceindex)
fprintf('setCTFDataBalance (unbalance_data): balance=%s\n',...
'\t\tsize(Grefindex)=[%d %d] size(Gbalanceindex)=[%d %d] ??\n',balance0(2,:),...
size(Grefindex),size(Gbalanceindex));
data=[]; % Force an error in the calling program
return
end
% Are there any badGref in the Gbalanceindex list?
if ~isempty(intersect(Gbalanceindex,badGref))
fprintf(['setCTFDataBalance (unbalance_data): A reference gradiometer marked bad ',...
'because of its grad_order_no\n',...
' appears in the list of reference sensors required for ',...
'%s Gref balancing.\n'],balance0(2,:));
fprintf(' Gbalanceindex=');fprintf(' %d',Gbalanceindex);fprintf('\n');
fprintf(' badGref=');fprintf(' %d',badGref);fprintf('\n');
data=[]; % Force an error in the calling program
return
end
if isequal(chanList,1:max(max(Gbalanceindex),max(Grefindex)));chanList=[];end
if ~isempty(chanList)
if ~isempty(setdiff(Gbalanceindex,chanList))
fprintf(['setCTFDataBalance (unbalance_data): List chanList does not include ',...
'all of the reference sensors in the %s table for reference gradiometers.\n'],...
balance0(2,:));
data=[];
return
end
[Gbalanceindex,Grefindex,alphaGref]=...
reindex(chanList,Gbalanceindex,Grefindex,alphaGref);
end
% Balancing reference gradiometers:
% balanced_data(:,Grefindex)
% =raw_data(:,Grefindex)-raw_data(:,Gbalanceindex)*alphaGref
% size(alphaGref)=[length(Gbalanceindex) length(Grefindex)]
% Note : not all of the sensors in list Gbalanceindex are gradiometers.
% Rewrite as a matrix equation:
% balanced_data(:,Gindex)=raw_data(:,Gindex)*Gbalmat
% Gindex=list of all the sensors involved in balancing the reference
% gradiometers.
% size(Gbalmat)=[length(Gindex) length(Gindex)]
[Gindex]=union(Gbalanceindex,Grefindex);
[Cx,Fbal]=intersect(Gindex,Gbalanceindex); % Gindex(Fbal)=Gbalanceindex
[Cx,Fref]=intersect(Gindex,Grefindex); % Gindex(Fref)=Grefindex
Gbalmat=eye(length(Gindex));
Gbalmat(Fbal,Fref)=Gbalmat(Fbal,Fref)-alphaGref;
clear Fbal Fref Cx Grefindex Gbalanceindex alphaGref;
% Convert to unbalanced reference gradiometers
for pt=1:size(data,3)
if strcmp(prec,'single')
data(:,Gindex,pt)=single(double(data(:,Gindex,pt))/Gbalmat);
else
data(:,Gindex,pt)=data(:,Gindex,pt)/Gbalmat;
end
end
clear Gbalmat pt;
end % Finished unbalancing the reference gradiometers
if strcmp(upper(balance0(1,:)),'NONE');
return; % No unbalancing required for MEG gradiometers
end
% Are there any badGref in the MEGbalanceindex list?
if ~isempty(intersect(MEGbalanceindex,badGref))
fprintf(['setCTFDataBalance (unbalance_data): A reference gradiometer marked bad ',...
'because of its grad_order_no\n',...
' appears in the list of reference sensors required for ',...
'%s MEG balancing.\n'],balance0(1,:));
fprintf(' MEGbalanceindex=');fprintf(' %d',MEGbalanceindex);fprintf('\n');
fprintf(' badGref=');fprintf(' %d',badGref);fprintf('\n');
data=[]; % Force an error in the calling program
return
end
% Don't bother with chanList if it obviously includes all the SQUID channels and in
% the dataset ordering.
if isequal(chanList,1:max(max(MEGindex),max(MEGbalanceindex)));chanList=[];end
if isempty(alphaMEG) | isempty(MEGindex) | isempty(MEGbalanceindex)
return;
elseif ~isequal(size(alphaMEG),[length(MEGbalanceindex) length(MEGindex)])
fprintf(['setCTFDataBalance (unbalance_data): size(alphaMEG)=[%d %d] ',...
'length(MEGbalanceindex)=%d length(MEGindex)=%d\n'],...
size(alphaMEG),length(MEGbalanceindex),length(MEGindex));
data=[];
return
elseif all(reshape(alphaMEG,1,length(MEGbalanceindex)*length(MEGindex))==0)
return
end
% Make the index lists refer to the entries in chanList.
if ~isempty(chanList)
if ~isempty(setdiff(MEGbalanceindex,chanList))
fprintf(['setCTFDataBalance (unbalance_data): List chanList does not include ',...
'all of the reference sensors in the %s table for MEG gradiometers.\n'],...
balance0(1,:));
data=[];
return
end
[MEGbalanceindex,MEGindex,alphaMEG]=...
reindex(chanList,MEGbalanceindex,MEGindex,alphaMEG);
end
% Reverse the balance applied to the MEG channels. Needs unbalanced reference data.
if ~isempty(alphaMEG) & ...
~isequal(alphaMEG,zeros(length(MEGbalanceindex),length(MEGindex)))
% Unbalance MEG data trial-by-trial and in blocks of nChBlock channels
for pt=1:size(data,3)
for m=1:nChBlock:length(MEGindex)
mptr=m:min(m+nChBlock-1,length(MEGindex));
MEGblock=MEGindex(mptr);
if strcmp(prec,'single');
data(:,MEGblock,pt)=single(double(data(:,MEGblock,pt))+...
double(data(:,MEGbalanceindex,pt))*alphaMEG(:,mptr));
else
data(:,MEGblock,pt)=data(:,MEGblock,pt)+...
data(:,MEGbalanceindex,pt)*alphaMEG(:,mptr);
end
end
end
clear pt m mptr MEGblock;
end
return
% ******************* End of function unbalance_data ****************************
% ***********************************************************************************
% ***********************************************************************************
% *************** Convert from unbalanced data to balanced data *******************
function data=balance_data(data,ds,balance,unit,nChBlock,chanList,badGref,messages);
% Extracts the balance table from structure ds and balances data as specified in balance.
% If the balancing requires a reference gradiometer marked in the badGref list, an error
% message is printed and the data array is set to [].
% If a MEG channel is missing from the balance table, then the channel is set to zero.
% Inputs: data: The aray of data to be balanced.
% ds: The ds structure read by readCTFds that contains the balance table.
% balance: The desired output balance state.
% balance(1,:) = MEG balance
% balance(2,:) = Gref balance
% unit : Data units ('fT','T','phio','int')
% nChBlock : rad the data in blocks of nChBlock to reduce memory requirements.
% chanList: List of the channels that actual;ly appear in data. referred to the
% dataset channel numbering (not to te list of SQUID channels)
% badGref: List of reference gradiometer channels that cannot be used for
% balancing.
if ~exist('chanList');chanList=[];end
prec=class(data);
[alphaMEG,MEGindex,MEGbalanceindex,alphaGref,Grefindex,Gbalanceindex]=...
getCTFBalanceCoefs(ds,balance,unit);
if ~strcmp(lower(balance(1,:)),'NONE');
% Are there any MEG channels missing from list MEGindex (i.e. missing from the balance table)?
% Make a list of MEG channels referred to dataset channel numbering.
MEGlist=[];
for k=1:ds.res4.no_channels
if ds.res4.senres(k).sensorTypeIndex==5;MEGlist=[MEGlist k];end
end
missingMEG=setdiff(MEGlist,MEGindex);
if ~isempty(missingMEG) & messages~=0 & ...
(isempty(chanList) | intersect(missingMEG,chanList))
fprintf('setCTFDataBalance (balance_data): Channel(s) missing from the balance table:\n');
for k=missingMEG
fprintf('\t%3d: %s\n',k,strtok(ds.res4.chanNames(k,:),'- '));
end
end
clear MEGlist k;
% Are there any badGref in the MEGbalanceindex list?
if ~isempty(intersect(MEGbalanceindex,badGref))
fprintf(['setCTFDataBalance (unbalance_data): A reference gradiometer marked bad ',...
'because of its grad_order_no\n',...
' appears in the list of reference sensors required for ',...
'%s MEG balancing.\n'],balance(1,:));
fprintf(' MEGbalanceindex=');fprintf(' %d',MEGbalanceindex);fprintf('\n');
fprintf(' badGref=');fprintf(' %d',badGref);fprintf('\n');
data=[]; % Force an error in the calling program
return
end
if isequal(chanList,1:max(max(MEGindex),max(MEGbalanceindex)));
chanList=[];
end
% Check if alphaMEG is all zeros or is improperly defined.
do_balance=~isempty(alphaMEG) & ~isempty(MEGindex) & ~isempty(MEGbalanceindex);
if do_balance
if ~isequal(size(alphaMEG),[length(MEGbalanceindex) length(MEGindex)]);
fprintf(['setCTFDataBalance (balance_data): size(alphaMEG)=[%d %d] ',...
'length(MEGbalanceindex)=%d length(MEGindex)=%d\n'],...
size(alphaMEG),length(MEGbalanceindex),length(MEGindex));
data=[];
return
elseif isempty(chanList) & size(data,2)<max(MEGindex)
fprintf(['setCTFDataBalance (balance_data): chanList=[], but size(data,2)=%d ',...
'max(MEGindex)=%d ?\n'],size(data,2),max(MEGindex));
data=[];
return
end
do_balance=~all(reshape(alphaMEG,1,length(MEGbalanceindex)*length(MEGindex))==0);
end
if do_balance
if ~isempty(chanList)
% Re-sort the reference sensor indices and make them refer to chanList
[MEGbalanceindex,MEGindex,alphaMEG]=...
reindex(chanList,MEGbalanceindex,MEGindex,alphaMEG);
% Refer the missing MEG channels to chanList
if ~isempty(missingMEG);missingMEG=reindex(chanList,missingMEG);end
end
% Balance MEGs data trial-by-trial and in blocks of nChBlock channels
for pt=1:size(data,3)
for m=1:nChBlock:length(MEGindex)
mptr=m:min(m+nChBlock-1,length(MEGindex));
MEGblock=MEGindex(mptr);
if strcmp(prec,'single')
data(:,MEGblock,pt)=single(double(data(:,MEGblock,pt))-...
double(data(:,MEGbalanceindex,pt))*alphaMEG(:,mptr));
else
data(:,MEGblock,pt)=data(:,MEGblock,pt)-...
data(:,MEGbalanceindex,pt)*alphaMEG(:,mptr);
end
end
% Zero the channel with missing coefficients. They cannot possibly be correct.
for m=missingMEG
if strcmp(prec,'single')
data(:,m,pt)=single(zeros(size(data,1),1,1));
else
data(:,m,pt)=zeros(size(data,1),1,1);
end
end
end
end
clear alphaMEG MEGindex MEGbalanceindex Ix pt m mptr MEGblock do_balance missingMEG;
end % Finished balancing the MEG data
% Is Gref balancing requested? In most cases, balance(2,:)='NONE'
if size(balance,1)==1;return;end
if strcmp(balance(2,:),'NONE');return;end
% Are there any bad Gref sensors in the Gbalanceindex list?
if ~isempty(intersect(Gbalanceindex,badGref))
fprintf(['setCTFDataBalance (balance_data): A reference gradiometer marked bad ',...
'because of its grad_order_no\n',...
' appears in the list of reference sensors required for ',...
'%s Gref balancing.\n'],balance(2,:));
fprintf(' Gbalanceindex=');fprintf(' %d',Gbalanceindex);fprintf('\n');
fprintf(' badGref=');fprintf(' %d',badGref);fprintf('\n');
data=[]; % Force an error in the calling program
return
end
% Make the index lists refer to the entries in chanList.
if ~isempty(chanList)
[Gbalanceindex,Grefindex,alphaGref]=...
reindex(chanList,Gbalanceindex,Grefindex,alphaGref);
end
% Balance the reference channels
for pt=1:size(data,3)
for m=1:nChBlock:length(Grefindex)
mptr=m:min(m+nChBlock-1,length(Grefindex));
Grefblock=Grefindex(mptr);
if strcmp(prec,'single');
data(:,Grefblock,pt)=single(double(data(:,Grefblock,pt))-...
double(data(:,Gbalanceindex,pt))*alphaGref(:,mptr));
else
data(:,Grefblock,pt)=data(:,Grefblock,pt)-...
data(:,Gbalanceindex,pt)*alphaGref(:,mptr);
end
end
end
clear pt m mptr Grefblock Grefindex Gbalanceindex;
return
% ******************** End of function balance_data ****************************
% ***********************************************************************************
% ***********************************************************************************
% ************** Reassign indices in sensor and reference lists. ******************
function [refindex,sensorindex,alfa2]=reindex(chanlist,reflist,sensorlist,alfa);
% Reindex lists reflist and sensor list, and reorders 2nd index of matrix alfa.
% Inputs : Lists of sensor and references for balancing and matrix of balance
% coefficients.
% Outputs : index lists: chanlist(refindex)=reflist
% chanlist(sensorindex)=sensorlist
% alfa2=The part of alfa that refers to the part of sensorlist
% that appears in chanlist.
refindex=[];sensorindex=[];alfa2=[]; % Force an error on an early return.
% Sensible argument lists?
if nargout>nargin-1 | nargout==0
fprintf('reindex: %d outputs, but only %d inputs.\n',nargout,nargin);
return
end
[X c1 c2]=intersect(chanlist,reflist);
[Y ylist]=sort(c2);
refindex=c1(ylist);
if length(refindex)~=length(reflist)
fprintf('setCTFDataBalance (reindex): length(refindex)=%d length(reflist)=%d\n',...
length(refindex),length(reflist));
fprintf(' Some references are not included in chanlist.\n');
return
end
if nargin>=3 & nargout>=2
[X c1 c2]=intersect(chanlist,sensorlist);
[Y ylist]=sort(c2);
sensorindex=c1(ylist);
end
if nargin>=4 & nargout>=3
alfa2=alfa(:,Y);
end
return
% ***********************************************************************************
|
github
|
philippboehmsturm/antx-master
|
writeCTFMRI.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/ctf/writeCTFMRI.m
| 8,517 |
utf_8
|
c6bdbc15d67e3621b8109f6b399f5eae
|
function writeCTFMRI(fileName,MRItags,MRIdata);
% Version 1.2 25 April 2007 Module writeCPersist changed, and removed from this text
% file.
% Version 1.1 19 April 2007 : No changes from v1.0
% Version 1.0 27 Oct. 2006
% Write a CTF MRI in v4 format.
% For file format and a defineition fo CPersist objects, see document
% "CTF MEG FIle Formats", PN900-0088
% Input: fileName : Name of MRI file including path and extension.
% Outputs: MRItags : CPersist tags describing the MRI in the format of the structure array
% produced by readMRI. There must be no start and stop tags.
% Clnical use messages are added to _PATIENT_ID, _PATIENT_NAME,
% _STUDY_COMMENTS, _CTFMRI_COMMENTS.
% I.e name='WS1_', type=0, data=[] and
% name='EndOfParameters', type -1, data=[]
% MRIdata: 256x256x256 array. No value may exceed 2^15-1 since the data are
% converted to int16.
% MRIdata(j,k,n) = pixel(j,k) of slice n.
% j = coronal slice. j=1:anterior, j=256:posterior
% k = axial slice. k=1:superior, k=256:inferior
% n = sagittal slice. j=1:left, j=256:right
% Calls: writeCPersist (not included in this listing)
% update_MRI_descriptors (included in this listing)
persistent printWarning
clinical_use_message='NOT FOR CLINICAL USE';
creatorSoftware='writeCTFMRI.m'; % Added to .infods file
NpxNot256Warning=1; % Print a warning if the no. of slices is not 256
if nargin==0 & nargout==0
fprintf(['writeCTFMRI: Version 1.2 25 April 2007 Creates MRIs in CTFMRI v4 format.\n',...
'\twriteCTFMRI(MRIfilename,MRItags,MRIdata);\n',...
'\t\tMRIfilename = complete name including path and extension .mri\n',...
'\t\tMRItags= structure array listing descriptors in the format produced',...
'by function readMRI.\n',...
'\t\tMRIdata = MRI data array.\n\n',...
'\tSee document "CTF MEG FIle Formats", PN900-0088\n']);
return
end
if nargin~=3
fprintf(['writeCTFMRI: Found %d input arguments. ',...
'Must have 3 inputs (filename,MRItags,MRIdata).\n'],nargin);
return
elseif ~ischar(fileName) | isempty(fileName) | ~isstruct(MRItags) | isempty(MRItags) |...
~isnumeric(MRIdata) | isempty(MRIdata)
fprintf('writeCTFMRI : Wrong argument type, or argument(s) empty.\n');
whos fileName MRItags MRIdata;
return
elseif ~isfield(MRItags,'name') | ~isfield(MRItags,'type') | ~isfield(MRItags,'data')
fprintf('writeCTFMRI: MRItags does not have the correct fields (name, type,data).\n');
MRItags
return
elseif ndims(MRIdata)~=3 | ~all(size(MRIdata)==size(MRIdata,1))
fprintf('writeCTFMRI: size(MRIdata)=[');fprintf(' %d',size(MRIdata));...
fprintf('] Must be Npx*[1 1 1] in CTF MRI format.\n');
return
elseif exist(fileName)==2
fprintf('writeCTFMRI: File %s already exists.\n',fileName);
return
end
% Verify that this really is a CTF MRI.
name=char([]);
for k=1:length(MRItags);
name=strvcat(name,MRItags(k).name);
end
isCTFMRI=(~isempty(strmatch('_CTFMRI_',name)));
MRIsize=size(MRIdata,1); % assume square slices
nSlice=size(MRIdata,3);
if NpxNot256Warning & MRIsize~=256
fprintf(['\nwriteCTFMRI: size(MRIdata)=%d*[1 1 1]. CTF MRI format standard is ',...
'256*[1 1 1].\n\t\t\tThis file may not work with MRIViewer.\n\n'],MRIsize);
end
if isCTFMRI
sizeTag=strmatch('_CTFMRI_SIZE',name,'exact');
if length(sizeTag)~=1
isCTFMRI=0;
else
MRItags(sizeTag).data=MRIsize;
end
clear sizeTag;
end
if ~isCTFMRI
fprintf(['writeCTFMRI: Structure array MRItags does not contain the tags ',...
'for a CTF MRI file (v4 format).\n'],fileName);
return
end
clear isCTFMRI
% Add clinical use and creator software messgaes
MRItags=update_MRI_descriptors(MRItags,clinical_use_message,creatorSoftware);
% Add MRIdata to MRItags, and add start and end tags
nTag=length(MRItags);
MRItags(2:nTag+1)=MRItags(1:nTag);
MRItags(1)=struct('name','WS1_','type',0,'data',[]); % Start tag
nTag=nTag+1;
for k=1:nSlice
MRItags(nTag+k)=struct('name',['_CTFMRI_SLICE_DATA#',num2str(k,'%5.5d')],'type',3,...
'data',int16(reshape(MRIdata(:,:,k),MRIsize^2,1)));
end
nTag=nTag+nSlice;
MRItags(nTag+1)=struct('name','EndOfParameters','type',-1,'data',[]); % End tag
clear MRIdata k nSlice MRIsize nTag;
if isempty(printWarning)
fprintf(['\nwriteCTFMRI: The MRI you are creating has been processed by software not\n',...
'\tmanufactured by VSM MedTech Ltd. and that has not received marketing clearance\n',...
'\tfor clinical applications. This MRI should not be later employed for clinical\n',...
'\tand/or diagnostic purposes.\n']);
printWarning=1;
end
% Create the MRI file.
writeCPersist(fileName,MRItags);
return
%%%%%%%%%%%%%% end of readMRI %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%% Function update_MRI_descriptors %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function MRItags=update_MRI_descriptors(MRItags,comment,creatorSoftware);
% Makes sure that certain tags are in structure MRItags.
% Inputs: MRItags : Structure array produced by readCTFMRI.
% comment : Character string that is added to infods tags listed in addCommentTag.
% creatorSoftware : Character string indicating that the MRI set was
% created by writeCTFMRI. Added to the tags listed in addCreatorTag.
% Adds comment (clinical use message) and creator software name to
% MRI tags that will display the comment.
addCommentTag=strvcat('_PATIENT_ID','_PATIENT_NAME',...
'_STUDY_COMMENTS','_CTFMRI_COMMENT');
% MRI tags that will display the creator software.
addCreatorTag=strvcat('_CTFMRI_COMMENT');
% Check that the comment and creator tags are in structure MRItags. If not, issue an
% error message and set MRItags to [].
addTag=strvcat(addCommentTag,addCreatorTag);
addIndex=zeros(1,size(addTag,1));
k=0;
for k=1:length(MRItags)
tagIndex=strmatch(MRItags(k).name,addTag,'exact');
addIndex(tagIndex)=k;
if all(addIndex)~=0;break;end
end
% addTag(j) is MRItags(addIndex(j))
if any(addIndex==0)
% At least one of the addTags is missing. Print an error message and return.
fprintf(['writeCTFMRI (update_MRI_descriptors): At least one tag is missing from ',...
'structure array MRItags.\n']);
for k=1:size(addTag,1)
if isempty(strmatch(addTag(k,:),addTag(1:k-1,:),'exact'))
fprintf('\t\t\t%s\n',deblank(addTag(k,:)));
end
end
MRItags=struct([]); % Force an error in the calling program.
return
end
% Check that all of the addTags are text strings
type=[MRItags.type];
if any(type(addIndex)~=9 & type(addIndex)~=10)
fprintf('writeCTFMRI (update_MRI_descriptors): At least one of the new tags is not a character string.\n');
for k=1:length(addTag)
if isempty(strmatch(addTag(k,:),addTag(1:k-1,:),'exact'))
fprintf('\t\t\t%s type=%d\n',deblank(addTag(k,:)),type(addIndex(k)));
end
end
MRItags=struct([]); % Force an error in the calling program.
return
end
addCommentIndex=addIndex(1:size(addCommentTag,1));
addCreatorIndex=addIndex(size(addCommentTag,1)+[1:size(addCreatorTag,1)]);
if exist('creatorSoftware')~=1;
creatorSoftware=char([]);
elseif ~ischar(creatorSoftware)
creatorSoftware=char([]);
else
creatorSoftware=deblank(creatorSoftware);
end
if exist('comment')~=1;
comment=char([]);
elseif ~ischar(comment)
comment=char([]);
else
comment=deblank(comment);
end
for k=addCreatorIndex
if isempty(MRItags(k).data)
MRItags(k).data=creatorSoftware;
else
MRItags(k).data=[creatorSoftware ' ' MRItags(k).data];
end
end
for k=addCommentIndex
if isempty(MRItags(k).data)
MRItags(k).data=comment;
else
MRItags(k).data=[comment ' ' MRItags(k).data];
end
end
% Shorten type 9 (CStr32) strings to 31 characters plus a terminating null.
for k=addIndex
if MRItags(k).type==9 & length(MRItags(k).data)>31;
MRItags(k).data=[MRItags(k).data(1:31) char(0)];
end
end
return
%%%%%%%%%%%%%% End of update_MRI_descriptors %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
github
|
philippboehmsturm/antx-master
|
readCTFds.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/ctf/readCTFds.m
| 36,336 |
utf_8
|
4526ccf95cbee4b0f46584ff977b80ba
|
function ds=readCTFds(datasetname)
% ************************************************************************
%
% This program is provided to users of CTF MEG systems as a courtesy only.
% It's operation has not been verified for clinical use.
% Please do not redistribute it without permission from CTF Systems Inc.
%
% ************************************************************************
% readCTFds opens a CTF data set and creates a MATLAB structure with the information
% in the .res4, .infods, .newds, .acq, .hc, .hist, .EEG, bad.segments, BadChannels,
% ClassFile.cls andMarkerFile.mrk files. It confirms the existence of a .meg4 file
% with the correct size.
% See document CTF MEG File Formats, PN900-0088 for a description of the formats of
% dataset files.
% Author : Harold Wilson
% ***************** Revisions and bug fixes **************************************
% Version 1.3 4 October 2007
% 1. readCTFds v1.2 failed when run in MATLAB 7.2, but ran correctly in
% MATLAB 6.5 and 7.3. The failure occurred when calls to fscanf with a
% final '\n' in the format string were followed by fgetl. In MATLAB 6.5 and 7.3,
% this returns the next line of a text file, but in MATLAB 7.2, this
% returns an empty charatcer string.
% Changes were made to subprograms
% - readHc,
% - readClassFile
% - readMarkerFile.
% 2. In v1.1 and 1.2, if any of the head coil positions exceeded 100 cm, readHc
% reported an error and returned hc=struct([]). In v1.3, is reports the error,
% and returns the erroneaous values.
% Version 1.2: 24 April 2007
% - readHc modified to read fMEG .hc files.
% - readCPersist modified to handle extra bytes that appear in some .acq files.
% Version 1.1: 13 April 2007
% readCTFds is modified to handle cases where the data files exceed a total of 2^31-8
% bytes. In these cases files .1_meg4,.2_meg4,... appear in the dataset.
% ***********************************************************************************
% Inputs : datasetname : Complete name of the data set directory. Includes the complete
% path and the .ds extension.
% Output: ds : A structure that gives data set parameters.
% Function calls included in this listing:
% - readRes4
% - readHc
% - readEEG
% - readMarkerFile
% - readClassFile
% - readBadSegments
% - readVirtualChannels
% External functions: - readCPersist Reads infods and acq files.
% - The data directory is datasetname.
% - path is the complete path to the directory including the last file delimiter.
% - baseName is the directory name, less the last file extension.
% - datasetname=[path,baseName,'.ds'];
persistent printWarning multipleMeg4Files
if nargin==0 & nargout==0 % Print a version number
fprintf(['\treadCTFds: Version 1.3 4 October 2007 ',...
'Reads v4.1 and v4.2 CTF data sets including fMEG .hc files.\n',...
'\tCall: ds=readCTFds(datasetname)\n',...
'\t\tdatasetname = Name of the dataset including the path.\n',...
'\t\tds = Structure containing all dataset information except for data in ',...
'the .meg4 file.\n\n']);
return
end
MAX_COILS=8;
MAX_BALANCING=50; % max. no. of balancing coefficients
SENSOR_LABEL=31; % No. of characters in sensor labels in the balancing
% coefficient tables
len_sensor_name=32;
% length of sensor coefficient records in bytes. See listing for MEGDefs.h
%senres_lenrec=len_sensor_name+8+2+MAX_BALANCING*SENSOR_LABEL+8*MAX_BALANCING;
% Allowed 8-byte headers for res4 and meg4 files.
res4Headers=strvcat(['MEG41RS',char(0)],['MEG42RS',char(0)]);
meg4Headers=strvcat(['MEG41CP',char(0)],['MEG42CP',char(0)]);
delim=filesep;
ds=struct([]);
% Check that the data set exists.
if exist('datasetname')~=1
fprintf('\nreadCTFds: No input datasetname specified.\n\n');
return
elseif ~ischar(datasetname) | isempty(datasetname) | size(datasetname,1)~=1
fprintf('\nreadCTFds: Dataset name is not a string, or is empty, or is an array.\n\n');
whos datasetname
return
else
% Separate datasetname into a path and the baseName and add extension .ds.
datasetname=deblank(datasetname);
ksep=max([0 findstr(datasetname,delim)]);
baseName=datasetname((ksep+1):length(datasetname));
path=datasetname(1:ksep); % String path is terminated by the file delimiter (or path=[]).
% Remove the last .ds from baseName.
kdot=max(findstr(baseName,'.ds'));
if kdot==(length(baseName)-2)
baseName=baseName(1:(max(kdot)-1));
else
datasetname=[datasetname,'.ds'];
end
clear ksep kdot;
if exist(datasetname)~=7
fprintf('\nreadCTFds: Cannot find dataset %s.\n\n',datasetname);
return
end
end
% Check that the res4 and meg4 files exist.
res4File=[datasetname,delim,baseName,'.res4'];
meg4File=[datasetname,delim,baseName,'.meg4'];
if exist(res4File)~=2 | exist(meg4File)~=2
fprintf('readCTFds: In directory %s, cannot find .res4 and/or .meg4 files.\n',...
datasetname);
return
end
% Check the headers on .meg4, .1_meg4, ...
qFile=0;
meg4Ext='.meg4';
meg4Size=[];
while 1
if qFile>0;
meg4Ext=['.',int2str(qFile),'_meg4'];
meg4File=[datasetname,delim,baseName,meg4Ext];
end
if qFile>1 & isempty(multipleMeg4Files)
fprintf('readCTFds: This dataset has multiple meg4 files.\n');
multipleMeg4Files=1;
end
fid=fopen(meg4File,'r','ieee-be');
if fid<=0;break;end
D=dir([datasetname,delim,baseName,meg4Ext]);
meg4Size=[meg4Size D.bytes];
meg4Header=char(fread(fid,8,'uint8')');
fclose(fid);
if isempty(strmatch(meg4Header,meg4Headers,'exact'))
fprintf('\nreadCTFds: %s file header=%s Valid header options:',meg4Ext,meg4Header);
for k=1:size(meg4Headers,1);fprintf(' %s',meg4Headers(k,:));end
fprintf('\n\n');
ds=struct([]);
return
end
qFile=qFile+1;
end
Nmeg4=length(meg4Size);
clear D fid qFile;
% Add baseName and path to structure ds.
ds=struct('baseName',baseName,'path',path);
% Read the res4 file
ds.res4=readRes4(res4File,res4Headers,...
MAX_COILS,MAX_BALANCING,SENSOR_LABEL,len_sensor_name);
if isempty(ds.res4);ds=struct([]);return;end
dataBytes=4*ds.res4.no_trials*ds.res4.no_channels*ds.res4.no_samples;
% Assemble ds.meg4.
ds.meg4.fileSize=sum(meg4Size);
ds.meg4.header=meg4Header;
clear meg4Header meg4Size;
% Does the size of the .meg4 file match the size specified by the .res4 file?
if ds.meg4.fileSize~=8*Nmeg4+dataBytes
fprintf(['\nreadCTFds: Data set error : size of meg4 file(s)\n\t\t',...
'%10d bytes (from dir command)\n'],ds.meg4.fileSize);
fprintf('\t\t%10d bytes (from res4 file)\n\n',8*Nmeg4+dataBytes);
return
end
if isempty(printWarning)
fprintf(['\nreadCTFds: You are reading CTF data for use with a software-application tool\n',...
'\tthat is not manufactured by VSM MedTech Ltd. and has not received marketing\n',...
'\tclearance for clinical applications. If CTF MEG data are processed by this tool,\n',...
'\tthey should not be later employed for clinical and/or diagnostic purposes.\n\n']);
printWarning=1;
end
% .infods file
if exist([datasetname,delim,baseName,'.infods'])==2
ds.infods=readCPersist([datasetname,delim,baseName,'.infods']);
end
% .newds file
if exist([datasetname,delim,baseName,'.newds'])==2
fid=fopen([datasetname,delim,baseName,'.newds'],'r','ieee-be');
ds.newds=char(fread(fid,'uint8'))';
fclose(fid);
clear fid;
end
% .acq file
if exist([datasetname,delim,baseName,'.acq'])==2
ds.acq=readCPersist([datasetname,delim,baseName,'.acq']);
end
% .hist file
if exist([datasetname,delim,baseName,'.hist'])==2
fid=fopen([datasetname,delim,baseName,'.hist'],'r','ieee-be');
ds.hist=char(fread(fid,'uint8'))';
fclose(fid);
end
% .hc file
if exist([datasetname,delim,baseName,'.hc'])==2
ds.hc=readHc([datasetname,delim,baseName,'.hc']);
end
% .eeg file
if exist([datasetname,delim,baseName,'.eeg'])==2
ds.eeg=readEEG([datasetname,delim,baseName,'.eeg']);
if isempty(ds.eeg);ds=rmfield(ds,'eeg');end
end
% marker file
if exist([datasetname,delim,'MarkerFile.mrk'])==2
ds.mrk=readMarkerFile([datasetname,delim,'MarkerFile.mrk']);
end
% ClassFile
if exist([datasetname,delim,'ClassFile.cls'])==2
ds.TrialClass=readClassFile([datasetname,delim,'ClassFile.cls']);
end
% bad.segments
if exist([datasetname,delim,'bad.segments'])==2
ds.badSegments=readBadSegments([datasetname,delim,'bad.segments']);
end
% BadChannels
if exist([datasetname,delim,'BadChannels'])==2
fid=fopen([datasetname,delim,'BadChannels'],'r','ieee-be');
ds.BadChannels=char([]);
while 1
strng=fscanf(fid,'%s\n',1);
if isempty(strng);break;end
ds.BadChannels=strvcat(ds.BadChannels,strng);
end
fclose(fid);
clear fid;
end
% VirtualChannels Assume this is the name of the file. Modify to accept *.vc?
if exist([datasetname,delim,'VirtualChannels'])==2
ds.Virtual=readVirtualChannels([datasetname,delim,'VirtualChannels']);
end
% processing.cfg
if exist([datasetname,delim,'processing.cfg'])==2
fid=fopen([datasetname,delim,'processing.cfg']);
ds.processing=char(fread(fid,'uint8'))';
fclose(fid);
clear fid;
end
return
%%%%%%%%%%%%%%%%% End of readCTFds %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%% Function readRes4 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function res4=readRes4(res4File,res4Headers,...
MAX_COILS,MAX_BALANCING,SENSOR_LABEL,len_sensor_name);
% Open the res4 file
fid=fopen(res4File,'r','ieee-be');
% Check header.
res4.header=char(fread(fid,8,'uint8')');
if isempty(strmatch(res4.header,res4Headers,'exact'))
fprintf(['\nreadCTFds (readRes4):res4 file header = %s. ',...
'Valid header options:'],res4.header);
for k=1:size(res4Headers,1);fprintf(' %s',res4Headers(k,:));end;fprintf('\n\n');
res4=struct([]);
fclose(fid);
return
end
% Remove trailing blanks, but include a final null (char(0)).
res4.appName=[deblank(char(fread(fid,256,'uint8')')) char(0)];
res4.dataOrigin=[deblank(char(fread(fid,256,'uint8')')) char(0)];
res4.dataDescription=[deblank(char(fread(fid,256,'uint8')')) char(0)];
res4.no_trials_avgd=fread(fid,1,'int16');
res4.data_time=[deblank(char(fread(fid,255,'uint8')')) char(0)];
res4.data_date=[deblank(char(fread(fid,255,'uint8')')) char(0)];
% new_general_setup_rec_ext part of meg41GeneralResRec
res4.no_samples=fread(fid,1,'int32');
temp=fread(fid,2,'int16');
res4.no_channels=temp(1);
res4.sample_rate=fread(fid,1,'float64');
res4.epoch_time=fread(fid,1,'float64');
temp=fread(fid,2,'int16');
res4.no_trials=temp(1);
res4.preTrigPts=fread(fid,1,'int32');
res4.no_trials_done=fread(fid,1,'int16');
res4.no_trials_display=fread(fid,1,'int16');
res4.save_trials=fread(fid,1,'int32');
% meg41TriggerData part of new_general_setup_rec_ext 10 bytes total
res4.primaryTrigger=fread(fid,1,'int32');
res4.triggerPolarityMask=fread(fid,1,'int32');
temp=fread(fid,1,'int16'); %Skip 2 bytes of padding
% end of meg41TriggerData part of new_general_setup_rec_ext
temp=fread(fid,3,'int16'); %Skip 2 bytes of padding
res4.trigger_mode=temp(2);
res4.accept_reject_Flag=fread(fid,1,'int32');
temp=fread(fid,2,'int16'); %Skip 2 bytes of padding
res4.run_time_display=temp(1);
res4.zero_Head_Flag=fread(fid,1,'int32');
res4.artifact_mode=fread(fid,1,'int32');
% end of new_general_setup_rec_ext part of meg41GeneralResRec
% meg4FileSetup part of meg41GeneralResRec
% Remove trailing blanks, but include a final null (char(0))
res4.nf_run_name=[deblank(char(fread(fid,32,'uint8')')) char(0)];
res4.nf_run_title=[deblank(char(fread(fid,256,'uint8')')) char(0)];
res4.nf_instruments=[deblank(char(fread(fid,32,'uint8')')) char(0)];
res4.nf_collect_descriptor=[deblank(char(fread(fid,32,'uint8')')) char(0)];
res4.nf_subject_id=[deblank(char(fread(fid,32,'uint8')')) char(0)];
res4.nf_operator=[deblank(char(fread(fid,32,'uint8')')) char(0)];
res4.nf_sensorFileName=[deblank(char(fread(fid,56,'uint8')')) char(0)];
temp=fread(fid,3,'int32');
res4.rdlen=temp(2);
res4.run_description=[deblank(char(fread(fid,res4.rdlen,'uint8')')) char(0)];
% end of meg4FileSetup part of meg41GeneralResRec
% Filter descriptions. Set field res4.filters=[] if no filters are
% defined.
res4.num_filters=fread(fid,1,'int16');
if res4.num_filters==0
res4.filters=[];
else
for kfilt=1:res4.num_filters
res4.filters(kfilt).freq=fread(fid,1,'float64');
res4.filters(kfilt).fClass=fread(fid,1,'int32');
res4.filters(kfilt).fType=fread(fid,1,'int32');
res4.filters(kfilt).numParam=fread(fid,1,'int16');
for kparm=1:res4.filters(kfilt).numParam
res4.filters(kfilt).Param(kparm)=fread(fid,1,'float64');
end
end
clear kfilt kparm;
end
% Read channel names. Must have size(res4.chanNames)=[channels 32]
% Clean up the channel names. The MEG system software leaves junk
% bytes in the channel name following the first zero.
res4.chanNames=char(zeros(res4.no_channels,32));
for kchan=1:res4.no_channels
xname=strtok(char(fread(fid,32,'uint8')'),char(0));
res4.chanNames(kchan,1:length(xname))=xname;
end
clear kchan xname;
% Read sensor resource table. Floating point values are 'double'
% but the code could be changed to convert to 'single' to save memory.
for kchan=1:res4.no_channels
res4.senres(kchan).sensorTypeIndex=fread(fid,1,'int16');
res4.senres(kchan).originalRunNum=fread(fid,1,'int16');
res4.senres(kchan).coilShape=fread(fid,1,'int32');
res4.senres(kchan).properGain=fread(fid,1,'double');
res4.senres(kchan).qGain=fread(fid,1,'double');
res4.senres(kchan).ioGain=fread(fid,1,'double');
res4.senres(kchan).ioOffset=fread(fid,1,'double');
res4.senres(kchan).numCoils=fread(fid,1,'int16');
numCoils=res4.senres(kchan).numCoils;
temp=fread(fid,3,'int16');
res4.senres(kchan).grad_order_no=temp(1);
% Special code to take care of situations where someone wants to label bad channels
% by setting their gain to zero.
invgain=(res4.senres(kchan).ioGain*...
res4.senres(kchan).properGain*res4.senres(kchan).qGain);
if abs(invgain)>1e-50
res4.senres(kchan).gain=1/invgain;
else
res4.senres(kchan).gain=sign(invgain)*1e50;
end
if res4.senres(kchan).sensorTypeIndex>=0 & res4.senres(kchan).sensorTypeIndex<=7
% Nominal gain (fT/integer step)
res4.senres(kchan).gain=1e15*res4.senres(kchan).gain;
end
% Data that was included in res4.senres(kchan).coilTbl in earlier versions of readCTFds
res4.senres(kchan).pos0=zeros(3,res4.senres(kchan).numCoils);
res4.senres(kchan).ori0=zeros(3,res4.senres(kchan).numCoils);
res4.senres(kchan).area=zeros(1,res4.senres(kchan).numCoils);
res4.senres(kchan).numturns=zeros(1,res4.senres(kchan).numCoils);
for qx=1:numCoils
buff=fread(fid,8,'double');
res4.senres(kchan).pos0(:,qx)=buff(1:3);
res4.senres(kchan).ori0(:,qx)=buff(5:7);
temp=fread(fid,4,'int16');
res4.senres(kchan).numturns(qx)=temp(1);
res4.senres(kchan).area(qx)=fread(fid,1,'double');
end
if numCoils<MAX_COILS % Skip the rest of the coilTbl
buff=fread(fid,10*(MAX_COILS-numCoils),'double');
end
% Data that was included in res4.senres(kchan).HdcoilTbl in earlier versions of readCTFds
res4.senres(kchan).pos=zeros(3,res4.senres(kchan).numCoils);
res4.senres(kchan).ori=zeros(3,res4.senres(kchan).numCoils);
for qx=1:numCoils
buff=fread(fid,8,'double');
res4.senres(kchan).pos(:,qx)=buff(1:3);
res4.senres(kchan).ori(:,qx)=buff(5:7);
temp=fread(fid,2,'double'); % Don't bother with area and numturns. Already read.
end
if numCoils<MAX_COILS % Skip the rest of the HdcoilTbl
buff=fread(fid,10*(MAX_COILS-numCoils),'double');
end
end
clear kchan buff numCoils temp qx;
% End reading sensor resource table
res4.numcoef=fread(fid,1,'int16'); % Number of coefficient records
% Create structure array res4.scrr which holds the balancing tables.
for nx=1:res4.numcoef
res4.scrr(nx).sensorName=uint8(fread(fid,len_sensor_name,'uint8'))';
buff=fread(fid,8,'uint8');
res4.scrr(nx).coefType=uint8(buff(1:4))'; % discard bytes 5-8
res4.scrr(nx).numcoefs=double(fread(fid,1,'int16'));
numcoef=res4.scrr(nx).numcoefs;
buff=fread(fid,SENSOR_LABEL*MAX_BALANCING,'uint8');
buff=reshape(buff,SENSOR_LABEL,MAX_BALANCING);
res4.scrr(nx).sensor=[uint8(buff(:,1:numcoef)) ...
uint8(zeros(SENSOR_LABEL,MAX_BALANCING-numcoef))];
buff=fread(fid,MAX_BALANCING,'double');
res4.scrr(nx).coefs=[buff(1:numcoef);zeros(MAX_BALANCING-numcoef,1)];
end
fclose(fid); % Close the res4 file
return
%%%%%%%%%% End of readRes4 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%% Function readHc %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function hc=readHc(hcFile);
% Reads the .hc file and returns a structure with head-coil posiiotns.
% The hc file format is given in document CTF MEG File Formats (PN900-0088).
% .hc file format: Coils and positions are specified by 4 lines of text:
% Line 1: A B coil position relative to C (cm):
% " 2: [tag]x = F
% " 3: [tag]y = F
% " 4: [tag]z = F
% A = 'standard' or 'stadard' or 'measured'. 'stadard' is a typographical error that
% appeared in v4 of the CTF Acq. The first set of coil positions is 'standard' or
% 'stanard'. The next two sets are 'measured'.
% B = coil label. For MEG systems, the first three coils must have the names 'nasion',
% 'left ear', 'right ear'. They may be followed by other coil names.
% For fMEG systems, there is no fixed standard for coil names.b readHc will
% accept any coil names. Typically the coils are 'back','left hip','right hip',
% 'sternum', 'belly'. In some UAMS data the names are 'nasion',...
% The string 'coil position relative to' appears in all valid .hc files. It marks
% the end of the coil label and the start ot the coordinate-system.
% C = coordinate system = 'dewar' and 'head'(MEG) or 'abdomen' (fMEG). No variations
% are permitted. The first two sets of coil positions are in dewar coordinates.
% The last set is in 'head' or 'abdomen' coordinates.
% Units : For .hc to be a valid coil position file, the coordinates must be in cm.
% The program searches for the string '(cm):'.
% F = coordinate (numeric)
% There are exactly 3 sets of coil positions in the file appearing in the order
% (1) A='standard', C='dewar'
% (2) A='measured', C='dewar'
% (3) A='measured', C='head' or 'abdomen'
% The coils must appear in the same order in each set.
% Input : Name of hc file (including complete path and .hc extension)
% Output : Structure hc containing standard, dewar and CTF coordinates of the
% nasion,left,right coils.
% hc.name= names of the coils size(hc.name)=[nCoil x]
% MEG: hc.standard, hc.dewar, hc.head : size=[3 nCoil] : coil positions in cm
% fMEG: hc.standard, hc.dewar, hc.abdomen : size=[3 nCoil] : coil positions in cm
if nargin==0 & nargout==0
fprintf(['readHc: Version 1.3 4 Oct. 2007\n',...
'\thc=readHc(hcFile) reads head-coil file hcFile and returns the head coil',...
'\t positions in structure hc\n\n',...
'\tThe file format is defined in document CTF MEG File Formats, PN900-0088.\n\n']);
return
end
basicString='coil position relative to';
% In MEG systems, the first three coil names are fixed.
MEGCoilLabel=strvcat('nasion','left ear','right ear');
C3options=strvcat('head','abdomen');
unitString='(cm):';
maxRCoil=200; % Report an error if any coil position is > maxRCoil cm.
printWarning=1;
hc=struct([]); % Return in event of an error.
if exist(hcFile)~=2
return
end
prec=1e-6; % Round positions.
% Decide if this is a MEG or an fMEG system. Find the first line that contains the
% string 'coil position relative to'.
% MEG system: This line contains 'nasion'.
% fMEG system: This line does not contains 'nasion'.
fhc=fopen(hcFile,'rt','ieee-be');
% Decide system type and generate arrays for strings A and C.
% Search for first line. Allow for the posibility that extra text lines migt be added at
% the start of the file.
strngA=char([]);
while 1
textline=fgetl(fhc);
if isequal(textline,-1)
break
elseif strfind(textline,'coil position relative to');
stringA=strtok(textline);
% Fix typographic error in some releases of Acq, not in all coils.
if strcmp(stringA,'stadard')
stringA = 'standard';
end
if ~strcmp(stringA,'standard')
break
end
stringA=strvcat(stringA,'measured','measured');
break;
end
end
if isequal(textline,-1) | size(stringA,1)<3
fprintf('readHc: File %s does not have the head position file format.\n',hcFile);
fclose(fhc);
return
end
% Set stringC(3,:)='head' or 'abdomen' later.
stringC=strvcat('dewar','dewar');
% textline is the first useful line of the head coil file.
coilLabel=char([]); % Names given to the coils
rhc=zeros(3,0); % Coil positions (cm)
coil=0;
nCoil=0;
lastPositionSet=1;
while ~isequal(textline,-1)
% Parse the line
[A,R]=strtok(textline);
% Fix typographic error in some releases of Acq, not in all coils.
if strcmp(A,'stadard')
A = 'standard';
end
kpos=strfind(R,basicString);
coilName=deblank(R(2:kpos-1));
[C,R]=strtok(R(kpos+length(basicString):length(R)));
if strmatch(C,C3options)
stringC=strvcat(stringC,C);
end
[unit,R]=strtok(R);
positionSet=intersect(strmatch(A,stringA),strmatch(C,stringC));
if isempty(positionSet) | ~strcmp(unit,unitString) | ~isempty(R)
break;
end
if positionSet==lastPositionSet
coil=coil+1;
else
coil=1;
end
if positionSet==1
% Assemble list of coil names
coilLabel=strvcat(coilLabel,coilName);
nCoil=coil;
elseif ~strcmp(coilName,deblank(coilLabel(coil,:)));
break;
end
% The line describing the coil and coordinate frame is OK.
% Get the coordinates by reading 3 lines.
buff=fscanf(fhc,'%s%s%f',9);
if ~isequal(size(buff),[9 1])
break
end
rhc=[rhc prec*round(buff(3:3:9)/prec)];
fgetl(fhc); % Skip to the start of the next line.
textline=fgetl(fhc);
lastPositionSet=positionSet;
end
fclose(fhc);
clear lastPositionSet coil textline fhc;
clear stringA A C R kpos coilName unit buff;
if size(rhc,2)~=positionSet*nCoil
fprintf('readHc: File %s does not have %d complete sets of %d coils.\n',...
hcFile,positionSet,nCoil);
return
end
if max(max(abs(rhc)))>maxRCoil & printWarning
fprintf('readHc: Head Coil file %s\n max(coil position)>%d.\n',...
hcFile,round(maxRCoil));
end
% Assemble structure hc.
hc=struct('names',coilLabel);
coilCoords=deblank(strvcat('standard','dewar',stringC(3,:)));
for q=1:positionSet
hc=setfield(hc,deblank(coilCoords(q,:)),rhc(:,nCoil*(q-1)+[1:nCoil]));
end
return
%%%%%%%%% End of readHc %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%% Function readEEG %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function EEG=readEEG(EEGfile);
% Reads the EEG file of a dataset and stores the infoemation in strucure array EEG.
% EEG(k).chanName = channel name in the dataset (EEGmmm where mmm=channel number)
% EEG(k).name = channel name given by the user (e.g. Fp4)
% EEG(k).pos = electrode position in cm in CTF head coordinates
if exist(EEGfile)~=2
EEG=struct([]);
return
end
fid=fopen(EEGfile,'r');
EEG=struct('chanNum',[],'name',char([]),'pos',[]);
nEEG=0;
while 1
chanNum=fscanf(fid,'%d',1);
name=fscanf(fid,'%s',1);
pos=fscanf(fid,'%f',3);
if isempty(pos);break;end
nEEG=nEEG+1;
EEG(nEEG)=struct('chanNum',chanNum,'name',name,'pos',pos);
end
fclose(fid);
return
%%%%%%%%% End of readEEG %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%% Function readClassFile %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function TrialClass=readClassFile(ClassFileName);
% Reads a CTF ClassFile and stores information in a structure.
% The class file allows a user to store a list of classsified trials in a data set.
% The ClassFile format is defined in document CTF MEG File Formats, PN900-0088.
% This format is rigid and readClassFile assumes that the ClassFile has the format
% current in October 2006.
% Inputs :
% ClassFileName : marker file including the full path and extension .mrk.
% trialList : List of trials to read. Trial numbering : 1,2,...
% If omitted or empty, read all markers.
% Output : Structure array marker. Output trial numbering starts at 1.
% See CTF MEG File Formats, (PN900-0088) for the meaning of the structure
% fields. A trial mat=y start before the t=0 point, so it is possible to have
% markers with time<0 (see ds.res4.preTrigPts).
TrialClass=struct([]);
if exist(ClassFileName)~=2
return % File doesn't exist.
end
fid=fopen(ClassFileName,'r','ieee-be');
for k=1:5;fgetl(fid);end % Skip 5 lines (including path info)
nClass=sscanf(fgetl(fid),'%d',1); %Read value and skip to the start of the next non-blank line.
if nClass<=0
fprintf('readClassFile: File %s has %d classes.\n',nClass);
return
end
TrialClass=struct('ClassGroupId',[],'Name',char([]),...
'Comment',char([]),'Color',char([]),'Editable',char([]),'ClassId',[],'trial',[]);
for k=1:nClass
% Find the start of the next class identification
% There is no need to check for end of file because the loop ends before an attempt
% is made to read class nClass+1.
while ~strcmp('CLASSGROUPID:',fgetl(fid));end
ClassGroupId=sscanf(fgetl(fid),'%d',1);
fgetl(fid);
Name=deblank(fgetl(fid));
fgetl(fid);
Comment=deblank(fgetl(fid));
fgetl(fid);
Color=deblank(fgetl(fid));
fgetl(fid);
Editable=deblank(fgetl(fid));
fgetl(fid);
ClassId=sscanf(fgetl(fid),'%d',1);
fgetl(fid);
No_of_Trials=sscanf(fgetl(fid),'%d',1);
fgetl(fid);fgetl(fid);
if No_of_Trials>0
trial=reshape(fscanf(fid,'%d',No_of_Trials),1,No_of_Trials);
else
trial=[];
end
% Adjust trial numbering so it starts at 1.
TrialClass(k)=struct('ClassGroupId',ClassGroupId,'Name',Name,...
'Comment',Comment,'Color',Color,'Editable',Editable,'ClassId',ClassId,...
'trial',trial+1);
end
fclose(fid);
return
%%%%%%%%% End of readClassFile %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%% Function readBadSegments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function badSegments=readBadSegments(badSegmentsFile);
% Reads the bad.segements file of a CTF data set and stores the information in structure
% bad_segments.
% badSegments.trial = List of trial numbers
% badSegments.StartTime = List of bad segment start times (relative to trial).
% badSegments.EndTime = List of bad segment end times.
% Reads the file one line at a time. Each line has three numbers.
% 1st: Trial number=integer. Trial numbering for bad.segments starts at 1.
% 2nd,3rd : Start, End times (s).
if exist(badSegmentsFile)~=2
badSegments=struct([]);
return
end
fid=fopen(badSegmentsFile,'r','ieee-be');
badSegments=struct('chanName',char([]),'name',char([]),'pos',[]);
nLine=0;
data=zeros(3,0);
while 1
txt=fgetl(fid);
if isequal(txt,-1);break;end
nLine=nLine+1;
[buff,count]=sscanf(txt,'%f');
% Are the data good?
badline=(count~=3);
if ~badline;badline=(abs((buff(1)-round(buff(1)))>0.0001) | buff(3)<buff(2));end
if badline
fprintf('readCTFds (readBadSegments): Format error in file bad.segments.\n');
fprintf('\tLine %d has %d numbers: ',nLine,count);fprintf('\t %g',buff);fprintf('\n');
fprintf('\tMust have 3 numbers on each line: #1=integer, #2,#3=float, #3>=#2.\n');
badSegments=struct([]);
return
end
data=[data buff];
end
fclose(fid);
badSegments=struct('trial',data(1,:),'StartTime',data(2,:),'EndTime',data(3,:));
return
%%%%%%%%% End of readBadSegments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%% Function readVirtualChannels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Virtual=readVirtualChannels(VirtualChannelsName);
% Reads the Virtual channels file associated with a data set
Virtual=struct([]);
% Check VirtualChannelsName
if exist('VirtualChannelsName')~=1;VirtualChannelsName=char([]);end
if isempty(VirtualChannelsName)
fprintf('readVirtualChannels: Must specify a VirtualChannels file.\n');
return
elseif ~ischar(VirtualChannelsName)
fprintf('readVirtualChannels: VirtualChannelsName must be a character string.\n');
return
elseif exist(VirtualChannelsName)~=2
fprintf('readVirtualChannels: Cannot find file %s\n',VirtualChannelsName);
return
end
fid=fopen(VirtualChannelsName,'r');
count=0;
Virtual=struct('Name',char([]),'Unit',char([]),'chan',char([]),'wt',[]);
strng=textread(VirtualChannelsName,'%s','delimiter',',\t');
k=0;
while k<length(strng)
k=k+1;
if strmatch('VirtualChannel',strng{k});
Refcount=0;
chan=char([]);
wt=[];
elseif strmatch('Name:',strng{k});
k=k+1;
Name=strng{k};
if isempty(Name);break;end
elseif strmatch('Unit:',strng{k});
k=k+1;
Unit=strng{k};
elseif strmatch('Ref:',strng{k});
chan=strvcat(chan,strng{k+1});
wt=[wt;str2num(strng{k+2})];
k=k+2;
elseif strmatch('}',strng{k});
count=count+1;
Virtual(count)=struct('Name',Name,'Unit',Unit,'chan',chan,'wt',wt);
clear Name Unit chan wt Refcount;
end
end
fclose(fid);
if isempty(Virtual(1).Name)
Virtual=struct([]);
end
return
%%%%%%%%% End of readVirtualChannels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%% Function readMarkerFile %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function marker=readMarkerFile(MarkerFileName,trialList);
% Version 1.3 4 Oct. 2007
% Reads specified trials of a CTF MarkerFile.
% The MarkerFile format is defined in document CTF MEG File Formats, PN900-0088.
% This format is rigid and readMarkerFile assumes that the MarkerFile has the format
% current in October 2006. The document lists 4 Class Groups, but only CLASSGROUPID=0
% (triggers) and CLASSGROUPID=3 (Manual) are actually used. read_MArkerFile reads only
% these two groups, but it prints a message if the other groups are encountered.
% Trigger markers (CLASSGROUPID=0) have an additional 4 pieces of information supplied:
% BITNUMBER(int), POLARITY(+ or 1),SOURCE(text) and THRESHOLD (float). FOr
% CLASSGROUPID=3, these fields are left empty.
% Inputs :
% MarkerFileName : marker file including the full path and extension .mrk.
% trialList : List of trials to read. Trial numbering : 1,2,...
% If omitted or empty, read all markers.
% Output : marker: Structure array. Output trial numbering starts at 1.
% See CTF MEG File Formats, (PN900-0088) for the meaning of the structure
% fields. A trial may start before the t=0 point, so it is possible to have
% markers with time<0 (see ds.res4.preTrigPts).
% Fields: ClassGroupId, Name,Comment,Color,Editable,ClassId,trial,time;
% Other fields that appear with ClassGroupId=0 are not included.
if nargin==0 & nargout==0
fprintf(['readMarkerFile: Version 1.3 4 Oct. 2007\n',...
'\tReads a CTF dataset MarkerFile and returns a structure array.\n',...
'\tmarker=readMarkerFile(FileName) reads ',...
'a marker file and returns the trials and times.\n',...
'\tmarker=readMarkerFile(FileName,trialList) reads a marker file and returns only\n',...
'\t\t\tthe markers for trials listed in vector trialList.\n\n',...
'\treadMarkerFile increments trial numbers by 1 so first trial in a dataset has trial=1.\n\n',...
'\tThe MarkerFile format is defined in document CTF MEG File Formats, PN900-0088.\n\n']);
return
end
marker=struct([]);
% Check MarkerFileName
if exist('MarkerFileName')~=1;MarkerFileName=char([]);end
if exist(MarkerFileName)~=2 % No MarkerFile present
fprintf('readMarkerFile: Could not find MarkerFile.\n');
MarkerFileName
return
end
% Check input trialList
if exist('trialList')~=1
trialList=[];
else
trialList=reshape(trialList,1,length(trialList));
if any((trialList-round(trialList))>0.1) | any(round(trialList)<=0)
fprintf('readMarkerFile: trialList must have only positive integers.\n');
return
end
end
fid=fopen(MarkerFileName,'r','ieee-be');
for k=1:5;fgetl(fid);end % Skip 5 lines (including path info)
nMarker=sscanf(fgetl(fid),'%d',1); %Read value and skip to the start of the next non-blank line.
if nMarker<=0
fprintf('readMarkerFile: File %s has %d markers.\n',nMarker);
fclose(fid);
return
end
marker=struct('ClassGroupId',[],'Name',char([]),...
'Comment',char([]),'Color',char([]),'Editable',char([]),'ClassId',[],...
'BitNumber',[],'Polarity',char([]),'Source',char([]),'Threshold',[],...
'trial',[],'time',[]);
for k=1:nMarker
% Find the start of the next marker identification
% There is no need to check for end of file because the loop ends before an attempt
% is made to read marker class nClass+1.
while ~strcmp('CLASSGROUPID:',fgetl(fid));end
ClassGroupId=sscanf(fgetl(fid),'%d',1);
if ~any(ClassGroupId==[0 3])
fprintf('read_MarkerFile: Skipping a marker with CLASSGROUPID=%d\n',ClassGroupId);
continue;
end
fgetl(fid);
Name=deblank(fgetl(fid));
fgetl(fid);
Comment=deblank(fgetl(fid));
fgetl(fid);
Color=deblank(fgetl(fid));
fgetl(fid);
Editable=deblank(fgetl(fid));
fgetl(fid);
ClassId=sscanf(fgetl(fid),'%d',1);
if ClassGroupId==0
fgetl(fid);
BitNumber=sscanf(fgetl(fid),'%d',1);
fgetl(fid);
Polarity=deblank(fgetl(fid));
fgetl(fid);
Source=deblank(fgetl(fid));
fgetl(fid);
Threshold=sscanf(fgetl(fid),'%f',1);
else
BitNumber=[];
Polarity=char([]);
Source=char([]);
Threshold=[];
end
fgetl(fid);
No_of_Samples=sscanf(fgetl(fid),'%d',1);
fgetl(fid);fgetl(fid);
trial=zeros(1,No_of_Samples);
time=zeros(1,No_of_Samples);
if No_of_Samples>0
buff=fscanf(fid,'%d %f\n',2*No_of_Samples);
trial=reshape(buff(1:2:2*No_of_Samples-1),1,No_of_Samples)+1; % Trial numbering starts at 1.
time=reshape(buff(2:2:2*No_of_Samples),1,No_of_Samples);
clear buff;
end
% Keep only the specified trials.
if ~isempty(trialList)
index=[];
for q=trialList;
index=[index find(trial==q)];
end
trial=trial(index);
time=time(index);
No_of_Samples=length(index);
clear q index;
end
marker(k)=struct('ClassGroupId',ClassGroupId,'Name',Name,...
'Comment',Comment,'Color',Color,'Editable',Editable,'ClassId',ClassId,...
'BitNumber',BitNumber,'Polarity',Polarity,'Source',Source,'Threshold',Threshold,...
'trial',trial,'time',time);
end
fclose(fid);
%clear k ClassGroupId Name Comment Color Editable ClassID No_of_Samples trial time;
return
%%%%%%%%%%%% End of readMarkerFile %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
github
|
philippboehmsturm/antx-master
|
ft_artifact_manual.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_artifact_manual.m
| 18,495 |
utf_8
|
532b06f68db8ce590b675f50faa4380e
|
function [cfg, artifact] = ft_artifact_manual(cfg);
% THIS FUNCTION IS DEPRECIATED, USE FT_REJECTVISUAL INSTEAD
%
% FT_ARTIFACT_MANUAL allows the user to detect artifacts manually using visual
% inspection.
%
% Use as:
% [cfg, artifact] = ft_artifact_manual(cfg)
% required configuration options:
% cfg.dataset or both cfg.headerfile and cfg.datafile
%
% The configuration should also contain:
% cfg.artfctdef.manual.channel = cell-array with channels to be displayed.
% (Be careful not to specify to much channels because the function then will be very slow.)
% cfg.continuous = 'yes' or 'no' whether the file contains continuous data
%
% You can specify:
% cfg.artfctdef.manual.pretrialtime = time shown before trialstart (default 0)
% cfg.artfctdef.manual.posttrialtime = time shown after trialend (default 0)
% cfg.artfctdef.manual.fft = 'no' (default) or 'yes' turns on FFT window
% cfg.artfctdef.manual.padding = 'no' (default) or FFT-padding in seconds
%
% The FFT will be executed on the complete time interval including pre and post
% trial times.
%
% cfg.artfctdef.manual.timeaxrelative = 'yes' (default) or 'no'.
%
% Set to yes defines the time axes relative to trialstart. Set to no defines it
% relative to the beginning of the experiment.
%
% cfg.artfctdef.manual.demean = 'no' (default) or 'yes' apply baseline correction
% cfg.artfctdef.manual.bpfilter = 'no' (default) or 'yes' apply bandpass filter
% cfg.artfctdef.manual.bpfreq = [0.3 30] in Hz
% cfg.artfctdef.manual.bpfiltord = 2
%
% See also FT_REJECTARTIFACT, FT_REJECTVISUAL
% Undocumented local options:
% cfg.artfctdef.manual.maxnumberofchannels = 20 (default)
% Copyright (C) 2004, Geerten Kramer, FCDC
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_artifact_manual.m 3710 2011-06-16 14:04:19Z eelspa $
ft_defaults
% record start time and total processing time
ftFuncTimer = tic();
ftFuncClock = clock();
% check if the input cfg is valid for this function
cfg = ft_checkconfig(cfg, 'trackconfig', 'on');
cfg = ft_checkconfig(cfg, 'renamed', {'datatype', 'continuous'});
cfg = ft_checkconfig(cfg, 'renamedval', {'continuous', 'continuous', 'yes'});
% set default rejection parameters if necessary.
if ~isfield(cfg, 'artfctdef'), cfg.artfctdef = []; end
if ~isfield(cfg.artfctdef,'manual'), cfg.artfctdef.manual = []; end
if ~isfield(cfg.artfctdef.manual,'zscale'), cfg.artfctdef.manual.zscale = 100; end
if ~isfield(cfg.artfctdef.manual,'fft'), cfg.artfctdef.manual.fft ='no'; end
if ~isfield(cfg.artfctdef.manual,'padding'), cfg.artfctdef.manual.padding ='no'; end
if ~isfield(cfg.artfctdef.manual,'pretrialtime'), cfg.artfctdef.manual.pretrialtime = 0; end
if ~isfield(cfg.artfctdef.manual,'posttrialtime'), cfg.artfctdef.manual.posttrialtime = 0; end
if ~isfield(cfg.artfctdef.manual,'timeaxrelative'), cfg.artfctdef.manual.timeaxrelative = 'yes'; end
if ~isfield(cfg.artfctdef.manual,'maxnumberofchannels'),cfg.artfctdef.manual.maxnumberofchannels = 20; end
if ~isfield(cfg, 'headerformat'), cfg.headerformat = []; end
if ~isfield(cfg, 'dataformat'), cfg.dataformat = []; end
% for backward compatibility
if isfield(cfg.artfctdef.manual,'sgn')
cfg.artfctdef.manual.channel = cfg.artfctdef.manual.sgn;
cfg.artfctdef.manual = rmfield(cfg.artfctdef.manual, 'sgn');
end
cfg.artfctdef = ft_checkconfig(cfg.artfctdef, 'renamed', {'blc', 'demean'});
cfg.artfctdef = ft_checkconfig(cfg.artfctdef, 'renamed', {'blcwindow' 'baselinewindow'});
if ~isfield(cfg.artfctdef.manual,'channel'),
% set an unusual default because all crashes the program.
cfg.artfctdef.manual.channel = [];
end
% read the header and do some preprocessing on the configuration
fprintf('Reading raw data...');
cfg = ft_checkconfig(cfg, 'dataset2files', {'yes'});
cfg = ft_checkconfig(cfg, 'required', {'headerfile', 'datafile'});
hdr = ft_read_header(cfg.headerfile, 'headerformat', cfg.headerformat);
cfg.artfctdef.manual.channel=ft_channelselection(cfg.artfctdef.manual.channel, hdr.label);
cfg.artfctdef.manual.trl=cfg.trl;
if(isempty(cfg.artfctdef.manual.channel))
error(sprintf('\nNo channels selected for artifact_manual!\nSelect at least one channel in cfg.artfctdef.manual.channel'));
end;
channelindx=match_str(hdr.label, cfg.artfctdef.manual.channel);
ntrial=size(cfg.trl, 1);
nch=length(channelindx);
if(nch<1)
error(sprintf('\nNo channels selected for artifact_manual!\nSelect at least one channel in cfg.artfctdef.manual.channel'));
elseif(nch>cfg.artfctdef.manual.maxnumberofchannels)
error(sprintf('\nMore than %i channels selected in cfg.artfctdef.manual.channel',cfg.artfctdef.manual.maxnumberofchannels));
end
% set default cfg.continuous
if ~isfield(cfg, 'continuous')
if hdr.nTrials==1
cfg.continuous = 'yes';
else
cfg.continuous = 'no';
end
end
show=ft_read_data(cfg.datafile, 'header', hdr, 'begsample', 1, 'endsample', hdr.nTrials*hdr.nSamples, 'chanindx', channelindx, 'checkboundary', strcmp(cfg.continuous, 'no'), 'dataformat', cfg.dataformat);
show=show';
N=length(show);
S=floor(N./hdr.Fs); % In seconds
x=1:N;
x=x./hdr.Fs; % In seconds.
fprintf(' done.\n');
fprintf('Processing raw data for artifact_manual...');
% these elements are stored inside the figure so that the callback routines can modify them
dat.RejMarkList=zeros(length(cfg.trl),1);
dat.ResRejMarkList=zeros(length(cfg.trl),1);
dat.RejCount=0;
dat.ResRejCount=0;
dat.stop=0;
dat.trln=1;
dat.numtrl=length(cfg.trl);
dat.FFT=strcmp(cfg.artfctdef.manual.fft,'yes')|strcmp(cfg.artfctdef.manual.fft,'Yes')...
|strcmp(cfg.artfctdef.manual.fft,'on')|strcmp(cfg.artfctdef.manual.fft,'On');
if(strcmp(cfg.artfctdef.manual.padding,'no')|strcmp(cfg.artfctdef.manual.padding,'No')...
|strcmp(cfg.artfctdef.manual.padding,'Off')|strcmp(cfg.artfctdef.manual.padding,'off'))
cfg.artfctdef.manual.padding=[];
end;
dat.IfRelOn=strcmp(cfg.artfctdef.manual.timeaxrelative,'yes')|strcmp(cfg.artfctdef.manual.timeaxrelative,'Yes')...
|strcmp(cfg.artfctdef.manual.timeaxrelative,'on')|strcmp(cfg.artfctdef.manual.timeaxrelative,'On');
ival=cell(dat.numtrl,1);
dataX=cell(dat.numtrl,1);
dataY=cell(dat.numtrl,1);
dataFx=cell(dat.numtrl,1);
dataFy=cell(dat.numtrl,1);
dataXLim=cell(dat.numtrl,1);
dataYLim=cell(dat.numtrl,1);
% first we calculate everything and put it into varables.
for(i=1:dat.numtrl)
begpadding = round(cfg.artfctdef.manual.pretrialtime.*hdr.Fs);
endpadding = round(cfg.artfctdef.manual.posttrialtime.*hdr.Fs);
ival{i}=(cfg.trl(i,1)-begpadding):(cfg.trl(i,2)+endpadding);
dataY{i}=show(ival{i},:);
% don't remove the padding
[dataY{i}, dumlab, dumtime, dumcfg] = preproc(dataY{i}', cfg.artfctdef.manual.channel, hdr.Fs, cfg.artfctdef.manual, cfg.trl(i,3)-begpadding, 0, 0);
dataY{i} = dataY{i}';
try, if(~rem(i,fix(dat.numtrl/10)))fprintf('.');end; end
end;
clear show; % Now, we don't need the complete dataset anymore...
for(i=1:dat.numtrl) % we go on with the calculations ....
dataX{i}=x(ival{i})-dat.IfRelOn.*(x(ival{i}(1))+cfg.artfctdef.manual.pretrialtime);
dataYLim{i}=[];
for(j=1:nch)
mini=min(dataY{i}(:,j));
maxi=max(dataY{i}(:,j));
dataYLim{i}=[dataYLim{i};[mini-.03.*(maxi-mini),maxi+.03.*(maxi-mini)]];
dataXLim{i}=[min(dataX{i}),max(dataX{i})];
end;
if(dat.FFT) % if FFT is on, calculate the FFT of the trials too...
tmp=[];
for(k=1:nch) tmp=[tmp,dataY{i}(:,k)-mean(dataY{i}(:,k),1)];end;
dataFy{i}=abs(fft(tmp,cfg.artfctdef.manual.padding,1));
tmp=floor((max(ival{i})-min(ival{i}))/2);
dataFx{i}=(1:tmp)./tmp.*hdr.Fs./2;
dataFy{i}=dataFy{i}(1:length(dataFx{i}),:);
end;
if(~rem(i,fix(dat.numtrl/10)))fprintf('.');end;
end;
fprintf(' done.\n');
thisfig('fig_trace');% See the help of thisfig
set(fig_trace,'name','Traces');
if(dat.FFT);
thisfig('fig_spec');
set(fig_spec,'name','Spectra of traces');
end;
gt=[5 40 5 25 0 50 5 60 5 60 5 60 5 60 5 60 5 25 0 25];
uicontrol(fig_trace,'units','pixels','position',[sum(gt(1:1)),5,gt(2),18],'String','Done','Callback',@stop);
uicontrol(fig_trace,'units','pixels','position',[sum(gt(1:3)),5,gt(4),18],'String','<','Callback',@prevtrial);
uicontrol(fig_trace,'units','pixels','position',[sum(gt(1:5)),5,gt(6),18],'String','>','Callback',@nexttrial);
uicontrol(fig_trace,'units','pixels','position',[sum(gt(1:7)),5,gt(8),18],'String','Reject >','Callback',@reject_next);
uicontrol(fig_trace,'units','pixels','position',[sum(gt(1:9)),5,gt(10),18],'String','Reject','Callback',@reject);
uicontrol(fig_trace,'units','pixels','position',[sum(gt(1:11)),5,gt(12),18],'String','Accept','Callback',@undo);
uicontrol(fig_trace,'units','pixels','position',[sum(gt(1:13)),5,gt(14),18],'String','Accept All','Callback',@undoAll);
uicontrol(fig_trace,'units','pixels','position',[sum(gt(1:15)),5,gt(16),18],'String','Redo All','Callback',@redoAll);
uicontrol(fig_trace,'units','pixels','position',[sum(gt(1:17)),5,gt(18),18],'String','<<','Callback',@pptrial);
uicontrol(fig_trace,'units','pixels','position',[sum(gt(1:19)),5,gt(20),18],'String','>>','Callback',@nntrial);
set(fig_trace, 'KeyPressFcn',@keypress);
% set(get(fig_trace, 'children'),'KeyPressFcn',@keypress);
show_help;
thisfig('fig_trace'); % See the help of thisfig.
while(ishandle(fig_trace))
if(dat.FFT) % Plots FFT when requested
if(exist('HF')) % this is for remembering the zoom of the FFT-window
if(ishandle(HF)) % while zapping trough the data.
saveXLim=get(HF,'XLim');
saveYLim=get(HF,'YLim');
end;
end;
thisfig('fig_spec');
plot(dataFx{dat.trln},dataFy{dat.trln});
HF=get(fig_spec,'CurrentAxes');
if(exist('saveXLim'))set(HF,'XLim',saveXLim);end;
if(exist('saveYLim'))set(HF,'YLim',saveYLim);end;
xlabel('Frequency [Hz]');
ylabel('Power [A.U.]');
thisfig('fig_trace');
end;
for(j=1:nch) % This loop fils the traces figure with the traces.
H=subplot(nch,1,j);
plot(dataX{dat.trln},dataY{dat.trln}(:,j),'b-');
line([dataXLim{1}(1)+cfg.artfctdef.manual.pretrialtime dataXLim{1}(1)+cfg.artfctdef.manual.pretrialtime], dataYLim{dat.trln}(j,:), 'color', 'g');
line([dataXLim{1}(2)-cfg.artfctdef.manual.posttrialtime dataXLim{1}(2)-cfg.artfctdef.manual.posttrialtime], dataYLim{dat.trln}(j,:), 'color', 'r');
set(H,'YLim',dataYLim{dat.trln}(j,:) + [-eps +eps]);
set(H,'XLim',dataXLim{dat.trln});
xlabel('Time [s]','position',...
[dataXLim{dat.trln}(2),dataYLim{dat.trln}(j,1)-(dataYLim{dat.trln}(j,2)-dataYLim{dat.trln}(j,1)).*.05]...
,'HorizontalAlignment','left');
ylabel(sprintf('%s', cfg.artfctdef.manual.channel{j}));
end;
if(dat.RejMarkList(dat.trln)==0)
tiet=sprintf('trial %i: ACCEPT',dat.trln);
else
tiet=sprintf('trial %i: REJECT',dat.trln);
end;
H=subplot(nch,1,1);
title(tiet);
guidata(fig_trace,dat);
uiwait;
if(ishandle(fig_trace)) dat=guidata(fig_trace);end;
if(dat.stop)break;end;
end
if(~ishandle(fig_trace))
error('Figure closed unexpectedly, no manual artifacts marked.');
else
close(fig_trace)
end;
if(dat.FFT)
if(ishandle(fig_spec))close(fig_spec);end;
end;
fprintf('Rejected %i trials.\n',dat.RejCount);
fprintf('Exported %i trials.\n',length(cfg.trl)-dat.RejCount);
artifact=cfg.trl(find((dat.RejMarkList)),[1,2]);
% remember the details that were used here
cfg.artfctdef.manual.artifact = artifact;
% get the output cfg
cfg = ft_checkconfig(cfg, 'trackconfig', 'off', 'checksize', 'yes');
% add version information to the configuration
cfg.version.name = mfilename('fullpath');
cfg.version.id = '$Id: ft_artifact_manual.m 3710 2011-06-16 14:04:19Z eelspa $';
% add information about the Matlab version used to the configuration
cfg.callinfo.matlab = version();
% add information about the function call to the configuration
cfg.callinfo.proctime = toc(ftFuncTimer);
cfg.callinfo.calltime = ftFuncClock;
cfg.callinfo.user = getusername();
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% here the SUBFUNCTIONS start that implement the gui callbacks
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function varargout=nexttrial(h, eventdata, handles, varargin)
dat=guidata(h);
if(dat.trln<dat.numtrl)
dat.trln=dat.trln + 1;
else
dat.trln=1;
end;
guidata(h,dat);
uiresume;
function varargout=prevtrial(h, eventdata, handles, varargin)
dat=guidata(h);
if(dat.trln > 1),
dat.trln=dat.trln - 1;
else
dat.trln=dat.numtrl;
end;
guidata(h,dat);
uiresume;
function varargout=stop(h, eventdata, handles, varargin)
dat=guidata(h);
dat.stop=1;
guidata(h,dat);
uiresume;
function varargout=reject(h, eventdata, handles, varargin)
dat=guidata(h);
if(dat.RejMarkList(dat.trln)==0)
dat.RejCount=dat.RejCount+1;
dat.RejMarkList(dat.trln)=1;
if(~dat.ResRejMarkList(dat.trln))
dat.ResRejCount=dat.ResRejCount+1;
dat.ResRejMarkList(dat.trln)=1;
fprintf('Rejected trial %i!\n',dat.trln);
else
fprintf('Rejected trial %i again!\n',dat.trln);
end;
else
fprintf('Trial %i is already marked for rejection.\n',dat.trln);
end;
guidata(h,dat);
uiresume;
function varargout=reject_next(h, eventdata, handles, varargin)
dat=guidata(h);
if(dat.RejMarkList(dat.trln)==0)
dat.RejCount=dat.RejCount+1;
dat.RejMarkList(dat.trln)=1;
if(~dat.ResRejMarkList(dat.trln))
dat.ResRejCount=dat.ResRejCount+1;
dat.ResRejMarkList(dat.trln)=1;
fprintf('Rejected trial %i!\n',dat.trln);
else
fprintf('Rejected trial %i again!\n',dat.trln);
end;
else
fprintf('Trial %i is already marked for rejection.\n',dat.trln);
end;
if(dat.trln < dat.numtrl)
dat.trln=dat.trln + 1;
else
dat.trln=1;
end;
guidata(h,dat);
uiresume;
function varargout=undo(h, eventdata, handles, varargin)
dat=guidata(h);
if(dat.RejMarkList(dat.trln)>0)
dat.RejCount=dat.RejCount-1;
dat.RejMarkList(dat.trln)=0;
fprintf('Rejected trial %i recovered.\n',dat.trln);
end;
guidata(h,dat);
uiresume;
function varargout=undoAll(h, eventdata, handles, varargin)
dat=guidata(h);
dat.RejCount=0;
dat.RejMarkList=zeros(dat.numtrl,1);
fprintf('All rejected trials recovered.\n');
guidata(h,dat);
uiresume;
function varargout=redoAll(h, eventdata, handles, varargin)
dat=guidata(h);
dat.RejMarkList=dat.ResRejMarkList;
dat.RejCount=dat.ResRejCount;
fprintf('All recovered trials rejected again.\n');
guidata(h,dat);
uiresume;
function varargout=nntrial(h, eventdata, handles, varargin)
dat=guidata(h);
if(dat.trln<(dat.numtrl-10))
dat.trln=dat.trln + 10;
else
dat.trln=1;
end;
guidata(h,dat);
uiresume;
function varargout=pptrial(h, eventdata, handles, varargin)
dat=guidata(h);
if(dat.trln > 10),
dat.trln=dat.trln - 10;
else
dat.trln=dat.numtrl;
end;
guidata(h,dat);
uiresume;
function keypress(h, eventdata, handles, varargin)
dat=guidata(gcbf);
key=get(gcbf, 'CurrentCharacter');
if key
switch key
case 28 % arrow left
if(dat.trln > 1),
dat.trln=dat.trln - 1;
else
dat.trln=dat.numtrl;
end;
case 29 % arrow right
if(dat.trln<dat.numtrl)
dat.trln=dat.trln + 1;
else
dat.trln=1;
end;
% case 30 % arrow up
% dat.zscale=data.zscale*1.5;
% case 31 % arrow down
% dat.zscale=data.zscale/1.5;
% case 'a'
% dat.reject(data.trlop)=0;
% case 'r'
% dat.reject(data.trlop)=1;
case {'a', 'A'}
if(dat.RejMarkList(dat.trln)==1)
dat.RejCount=dat.RejCount-1;
dat.RejMarkList(dat.trln)=0;
fprintf('Accepted trial %i\n',dat.trln);
end
if(dat.trln < dat.numtrl)
dat.trln=dat.trln + 1;
else
dat.trln=1;
end;
case {'0', 'r', 'R'}
if(dat.RejMarkList(dat.trln)==0)
dat.RejCount=dat.RejCount+1;
dat.RejMarkList(dat.trln)=1;
if(~dat.ResRejMarkList(dat.trln))
dat.ResRejCount=dat.ResRejCount+1;
dat.ResRejMarkList(dat.trln)=1;
fprintf('Rejected trial %i! \n',dat.trln);
else
fprintf('Rejected trial %i again! \n',dat.trln);
end;
else
fprintf('Trial %i is already marked for rejection.\n',dat.trln);
end;
if(dat.trln < dat.numtrl)
dat.trln=dat.trln + 1;
else
dat.trln=1;
end;
otherwise
show_help;
end
end
set(gcbf, 'CurrentCharacter', '-');
guidata(gcbf, dat);
uiresume(h);
function show_help;
fprintf('You can use the buttons in the window to navigate through the trials, \n');
fprintf('reject trials or undo and redo your rejection selection. If you want to \n');
fprintf('use the keyboard, you first have to click in the figure every time you \n');
fprintf('pressed a button with the mouse. \n');
fprintf(' \n');
fprintf('Use the left and right arrow to walk through the trials \n');
fprintf('Press "a" to accept, "r" to reject. \n');
function thisfig(NameOfHandle);
assignin('caller','This_Name_Will_Never_be_Used_gk',NameOfHandle);
if(~evalin('caller','exist(This_Name_Will_Never_be_Used_gk)')|~ishandle(evalin('caller',NameOfHandle)))
H=figure;
assignin('caller',NameOfHandle,H);
else
figure(evalin('caller',NameOfHandle));
end;
evalin('caller','clear This_Name_Will_Never_be_Used_gk;');
|
github
|
philippboehmsturm/antx-master
|
ft_prepare_layout.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_prepare_layout.m
| 26,587 |
utf_8
|
117888be4827d20a2f38900a75e94637
|
function [lay] = ft_prepare_layout(cfg, data)
% FT_PREPARE_LAYOUT creates a 2-D layout of the channel locations. This layout
% is required for plotting the topographical distribution of the potential
% or field distribution, or for plotting timecourses in a topographical
% arrangement.
%
% Use as
% lay = ft_prepare_layout(cfg, data)
%
% There are several ways in which a 2-D layout can be made: it can be read
% directly from a *.lay file, it can be created based on 3-D electrode or
% gradiometer positions in the configuration or in the data, or it can be
% created based on the specification of an electrode of gradiometer file.
%
% You can specify either one of the following configuration options
% cfg.layout filename containg the layout
% cfg.rotate number, rotation around the z-axis in degrees (default = [], which means automatic)
% cfg.projection string, 2D projection method can be 'stereographic', 'orthographic', 'polar', 'gnomic' or 'inverse' (default = 'polar')
% cfg.elec structure with electrode positions, or
% cfg.elecfile filename containing electrode positions
% cfg.grad structure with gradiometer definition, or
% cfg.gradfile filename containing gradiometer definition
% cfg.output filename to which the layout will be written (default = [])
% cfg.montage 'no' or a montage structure (default = 'no')
% cfg.image filename, use an image to construct a layout (e.g. usefull for ECoG grids)
% cfg.bw if an image is used and bw = 1 transforms the image in black and white (default = 0, do not transform)
%
% Alternatively the layout can be constructed from either
% data.elec structure with electrode positions
% data.grad structure with gradiometer definition
%
% Alternatively you can specify the following layouts which will be
% generated for all channels present in the data. Note that these layouts
% are suitable for multiplotting, but not for topoplotting.
% cfg.layout = 'ordered' will give you a NxN ordered layout
% cfg.layout = 'vertical' will give you a Nx1 ordered layout
% cfg.layout = 'butterfly' will give you a layout with all channels on top of each other
%
% See also FT_LAYOUTPLOT, FT_TOPOPLOTER, FT_TOPOPLOTTFR, FT_MULTIPLOTER, FT_MULTIPLOTTFR
% TODO switch to using planarchannelset function
% undocumented and non-recommended option (for SPM only)
% cfg.style string, '2d' or '3d' (default = '2d')
% Copyright (C) 2007-2009, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_prepare_layout.m 3800 2011-07-07 15:17:47Z roboos $
% Undocumented option:
% cfg.layout can contain a lay structure which is simply returned as is
ft_defaults
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% basic check/initialization of input arguments
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if (nargin<1) || (nargin>2), error('incorrect number of input arguments'); end;
if (nargin<2), data = []; end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% set default configuration options
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isfield(cfg, 'rotate'), cfg.rotate = []; end % [] => rotation is determined based on the type of sensors
if ~isfield(cfg, 'style'), cfg.style = '2d'; end
if ~isfield(cfg, 'projection'), cfg.projection = 'polar'; end
if ~isfield(cfg, 'layout'), cfg.layout = []; end
if ~isfield(cfg, 'grad'), cfg.grad = []; end
if ~isfield(cfg, 'elec'), cfg.elec = []; end
if ~isfield(cfg, 'gradfile'), cfg.gradfile = []; end
if ~isfield(cfg, 'elecfile'), cfg.elecfile = []; end
if ~isfield(cfg, 'output'), cfg.output = []; end
if ~isfield(cfg, 'feedback'), cfg.feedback = 'no'; end
if ~isfield(cfg, 'montage'), cfg.montage = 'no'; end
if ~isfield(cfg, 'image'), cfg.image = []; end
if ~isfield(cfg, 'bw'), cfg.bw = 0; end
if ~isfield(cfg, 'channel'), cfg.channel = 'all'; end
if ~isfield(cfg, 'skipscale'), cfg.skipscale = 'no'; end
if ~isfield(cfg, 'skipcomnt'), cfg.skipcomnt = 'no'; end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% try to generate the layout structure
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
skipscale = strcmp(cfg.skipscale, 'yes'); % in general a scale is desired
skipcomnt = strcmp(cfg.skipcomnt, 'yes'); % in general a comment desired
if isa(cfg.layout, 'config')
% convert the nested config-object back into a normal structure
cfg.layout = struct(cfg.layout);
end
% check whether cfg.layout already contains a valid layout structure (this can
% happen when higher level plotting functions are called with cfg.layout set to
% a lay structure)
if isstruct(cfg.layout) && isfield(cfg.layout, 'pos') && isfield(cfg.layout, 'label') && isfield(cfg.layout, 'width') && isfield(cfg.layout, 'height')
lay = cfg.layout;
elseif isstruct(cfg.layout) && isfield(cfg.layout, 'pos') && isfield(cfg.layout, 'label') && (~isfield(cfg.layout, 'width') || ~isfield(cfg.layout, 'height'))
lay = cfg.layout;
% add width and height for multiplotting
d = dist(lay.pos');
nchans = length(lay.label);
for i=1:nchans
d(i,i) = inf; % exclude the diagonal
end
mindist = min(d(:));
lay.width = ones(nchans,1) * mindist * 0.8;
lay.height = ones(nchans,1) * mindist * 0.6;
elseif isequal(cfg.layout, 'butterfly')
if nargin>1 && ~isempty(data)
% look at the data to determine the overlapping channels
cfg.channel = ft_channelselection(cfg.channel, data.label);
chanindx = match_str(data.label, cfg.channel);
nchan = length(data.label(chanindx));
lay.label = data.label(chanindx);
else
nchan = length(cfg.channel);
lay.label = cfg.channel;
end
lay.pos = zeros(nchan,2); % centered at (0,0)
lay.width = ones(nchan,1) * 1.0;
lay.height = ones(nchan,1) * 1.0;
lay.mask = {};
lay.outline = {};
skipscale = true; % a scale is not desired
skipcomnt = true; % a comment is initially not desired, or at least requires more thought
elseif isequal(cfg.layout, 'vertical')
if nargin>1 && ~isempty(data)
% look at the data to determine the overlapping channels
cfg.channel = ft_channelselection(data.label, cfg.channel); % with this order order of channels stays the same
[dum chanindx] = match_str(cfg.channel, data.label); % order of channels according to cfg specified by user
nchan = length(data.label(chanindx));
lay.label = data.label(chanindx);
else
nchan = length(cfg.channel);
lay.label = cfg.channel;
end
for i=1:(nchan+2)
x = 0.5;
y = 1-i/(nchan+1+2);
lay.pos (i,:) = [x y];
lay.width (i,1) = 0.9;
lay.height(i,1) = 0.9 * 1/(nchan+1+2);
if i==(nchan+1)
lay.label{i} = 'SCALE';
elseif i==(nchan+2)
lay.label{i} = 'COMNT';
end
end
lay.mask = {};
lay.outline = {};
elseif isequal(cfg.layout, 'ordered')
if nargin>1 && ~isempty(data)
% look at the data to determine the overlapping channels
cfg.channel = ft_channelselection(cfg.channel, data.label);
chanindx = match_str(data.label, cfg.channel);
nchan = length(data.label(chanindx));
lay.label = data.label(chanindx);
else
nchan = length(cfg.channel);
lay.label = cfg.channel;
end
ncol = ceil(sqrt(nchan))+1;
nrow = ceil(sqrt(nchan))+1;
k = 0;
for i=1:nrow
for j=1:ncol
k = k+1;
if k<=nchan
x = (j-1)/ncol;
y = (nrow-i-1)/nrow;
lay.pos(k,:) = [x y];
lay.width(k,1) = 0.8 * 1/ncol;
lay.height(k,1) = 0.8 * 1/nrow;
end
end
end
lay.label{end+1} = 'SCALE';
lay.width(end+1) = 0.8 * 1/ncol;
lay.height(end+1) = 0.8 * 1/nrow;
x = (ncol-2)/ncol;
y = 0/nrow;
lay.pos(end+1,:) = [x y];
lay.label{end+1} = 'COMNT';
lay.width(end+1) = 0.8 * 1/ncol;
lay.height(end+1) = 0.8 * 1/nrow;
x = (ncol-1)/ncol;
y = 0/nrow;
lay.pos(end+1,:) = [x y];
% try to generate layout from other configuration options
elseif ischar(cfg.layout) && ft_filetype(cfg.layout, 'matlab')
fprintf('reading layout from file %s\n', cfg.layout);
load(cfg.layout, 'lay');
elseif ischar(cfg.layout) && ft_filetype(cfg.layout, 'layout')
fprintf('reading layout from file %s\n', cfg.layout);
lay = readlay(cfg.layout);
elseif ischar(cfg.layout) && ~ft_filetype(cfg.layout, 'layout')
% assume that cfg.layout is an electrode file
fprintf('creating layout from electrode file %s\n', cfg.layout);
lay = sens2lay(ft_read_sens(cfg.layout), cfg.rotate, cfg.projection, cfg.style);
elseif ischar(cfg.elecfile)
fprintf('creating layout from electrode file %s\n', cfg.elecfile);
lay = sens2lay(ft_read_sens(cfg.elecfile), cfg.rotate, cfg.projection, cfg.style);
elseif ~isempty(cfg.elec) && isstruct(cfg.elec)
fprintf('creating layout from cfg.elec\n');
lay = sens2lay(cfg.elec, cfg.rotate, cfg.projection, cfg.style);
elseif isfield(data, 'elec') && isstruct(data.elec)
fprintf('creating layout from data.elec\n');
lay = sens2lay(data.elec, cfg.rotate, cfg.projection, cfg.style);
elseif ischar(cfg.gradfile)
fprintf('creating layout from gradiometer file %s\n', cfg.gradfile);
lay = sens2lay(ft_read_sens(cfg.gradfile), cfg.rotate, cfg.projection, cfg.style);
elseif ~isempty(cfg.grad) && isstruct(cfg.grad)
fprintf('creating layout from cfg.grad\n');
lay = sens2lay(cfg.grad, cfg.rotate, cfg.projection, cfg.style);
elseif isfield(data, 'grad') && isstruct(data.grad)
fprintf('creating layout from data.grad\n');
lay = sens2lay(data.grad, cfg.rotate, cfg.projection, cfg.style);
elseif ~isempty(cfg.image) && isempty(cfg.layout)
fprintf('reading background image from %s\n', cfg.image);
img = imread(cfg.image);
img = flipdim(img, 1); % in combination with "axis xy"
figure
bw = cfg.bw;
if bw
% convert to greyscale image
img = mean(img, 3);
imagesc(img);
colormap gray
else
% plot as RGB image
image(img);
end
hold on
axis equal
axis off
axis xy
% get the electrode positions
pos = zeros(0,2);
electrodehelp = [ ...
'-----------------------------------------------------\n' ...
'specify electrode locations\n' ...
'press the right mouse button to add another electrode\n' ...
'press backspace on the keyboard to remove the last electrode\n' ...
'press "q" on the keyboard to continue\n' ...
];
again = 1;
while again
fprintf(electrodehelp)
disp(round(pos)); % values are integers/pixels
try
[x, y, k] = ginput(1);
catch
% this happens if the figure is closed
return;
end
switch k
case 1
pos = cat(1, pos, [x y]);
% add it to the figure
plot(x, y, 'b.');
plot(x, y, 'yo');
case 8
if size(pos,1)>0
% remove the last point
pos = pos(1:end-1,:);
% completely redraw the figure
cla
h = image(img);
hold on
axis equal
axis off
plot(pos(:,1), pos(:,2), 'b.');
plot(pos(:,1), pos(:,2), 'yo');
end
case 'q'
again = 0;
otherwise
warning('invalid button (%d)', k);
end
end
% get the mask outline
polygon = {};
thispolygon = 1;
polygon{thispolygon} = zeros(0,2);
maskhelp = [ ...
'------------------------------------------------------------------------\n' ...
'specify polygons for masking the topgraphic interpolation\n' ...
'press the right mouse button to add another point to the current polygon\n' ...
'press backspace on the keyboard to remove the last point\n' ...
'press "c" on the keyboard to close this polygon and start with another\n' ...
'press "q" on the keyboard to continue\n' ...
];
again = 1;
while again
fprintf(maskhelp);
fprintf('\n');
for i=1:length(polygon)
fprintf('polygon %d has %d points\n', i, size(polygon{i},1));
end
try
[x, y, k] = ginput(1);
catch
% this happens if the figure is closed
return;
end
switch k
case 1
polygon{thispolygon} = cat(1, polygon{thispolygon}, [x y]);
% add the last line segment to the figure
if size(polygon{thispolygon},1)>1
x = polygon{i}([end-1 end],1);
y = polygon{i}([end-1 end],2);
end
plot(x, y, 'g.-');
case 8 % backspace
if size(polygon{thispolygon},1)>0
% remove the last point
polygon{thispolygon} = polygon{thispolygon}(1:end-1,:);
% completely redraw the figure
cla
h = image(img);
hold on
axis equal
axis off
% plot the electrode positions
plot(pos(:,1), pos(:,2), 'b.');
plot(pos(:,1), pos(:,2), 'yo');
for i=1:length(polygon)
x = polygon{i}(:,1);
y = polygon{i}(:,2);
if i~=thispolygon
% close the polygon in the figure
x(end) = x(1);
y(end) = y(1);
end
plot(x, y, 'g.-');
end
end
case 'c'
if size(polygon{thispolygon},1)>0
% close the polygon
polygon{thispolygon}(end+1,:) = polygon{thispolygon}(1,:);
% close the polygon in the figure
x = polygon{i}([end-1 end],1);
y = polygon{i}([end-1 end],2);
plot(x, y, 'g.-');
% switch to the next polygon
thispolygon = thispolygon + 1;
polygon{thispolygon} = zeros(0,2);
end
case 'q'
if size(polygon{thispolygon},1)>0
% close the polygon
polygon{thispolygon}(end+1,:) = polygon{thispolygon}(1,:);
% close the polygon in the figure
x = polygon{i}([end-1 end],1);
y = polygon{i}([end-1 end],2);
plot(x, y, 'g.-');
end
again = 0;
otherwise
warning('invalid button (%d)', k);
end
end
% remember this set of polygons as the mask
mask = polygon;
% get the outline, e.g. head shape and sulci
polygon = {};
thispolygon = 1;
polygon{thispolygon} = zeros(0,2);
maskhelp = [ ...
'-----------------------------------------------------------------------------------\n' ...
'specify polygons for adding outlines (e.g. head shape and sulci) to the layout\n' ...
'press the right mouse button to add another point to the current polygon\n' ...
'press backspace on the keyboard to remove the last point\n' ...
'press "c" on the keyboard to close this polygon and start with another\n' ...
'press "n" on the keyboard to start with another without closing the current polygon\n' ...
'press "q" on the keyboard to continue\n' ...
];
again = 1;
while again
fprintf(maskhelp);
fprintf('\n');
for i=1:length(polygon)
fprintf('polygon %d has %d points\n', i, size(polygon{i},1));
end
try
[x, y, k] = ginput(1);
catch
% this happens if the figure is closed
return;
end
switch k
case 1
polygon{thispolygon} = cat(1, polygon{thispolygon}, [x y]);
% add the last line segment to the figure
if size(polygon{thispolygon},1)>1
x = polygon{i}([end-1 end],1);
y = polygon{i}([end-1 end],2);
end
plot(x, y, 'm.-');
case 8 % backspace
if size(polygon{thispolygon},1)>0
% remove the last point
polygon{thispolygon} = polygon{thispolygon}(1:end-1,:);
% completely redraw the figure
cla
h = image(img);
hold on
axis equal
axis off
% plot the electrode positions
plot(pos(:,1), pos(:,2), 'b.');
plot(pos(:,1), pos(:,2), 'yo');
for i=1:length(polygon)
x = polygon{i}(:,1);
y = polygon{i}(:,2);
if i~=thispolygon
% close the polygon in the figure
x(end) = x(1);
y(end) = y(1);
end
plot(x, y, 'm.-');
end
end
case 'c'
if size(polygon{thispolygon},1)>0
x = polygon{thispolygon}(1,1);
y = polygon{thispolygon}(1,2);
polygon{thispolygon} = cat(1, polygon{thispolygon}, [x y]);
% add the last line segment to the figure
x = polygon{i}([end-1 end],1);
y = polygon{i}([end-1 end],2);
plot(x, y, 'm.-');
% switch to the next polygon
thispolygon = thispolygon + 1;
polygon{thispolygon} = zeros(0,2);
end
case 'n'
if size(polygon{thispolygon},1)>0
% switch to the next polygon
thispolygon = thispolygon + 1;
polygon{thispolygon} = zeros(0,2);
end
case 'q'
again = 0;
otherwise
warning('invalid button (%d)', k);
end
end
% remember this set of polygons as the outline
outline = polygon;
% convert electrode positions into a layout structure
lay.pos = pos;
nchans = size(pos,1);
for i=1:nchans
lay.label{i,1} = sprintf('chan%03d', i);
end
% add width and height for multiplotting
d = dist(pos');
for i=1:nchans
d(i,i) = inf; % exclude the diagonal
end
mindist = min(d(:));
lay.width = ones(nchans,1) * mindist * 0.8;
lay.height = ones(nchans,1) * mindist * 0.6;
% add mask and outline polygons
lay.mask = mask;
lay.outline = outline;
else
error('no layout detected, please specify cfg.layout')
end
% FIXME there is a conflict between the use of cfg.style here and in topoplot
if ~strcmp(cfg.style, '3d')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% check whether outline and mask are available
% if not, add default "circle with triangle" to resemble the head
% in case of "circle with triangle", the electrode positions should also be
% scaled
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isfield(lay, 'outline') || ~isfield(lay, 'mask')
rmax = 0.5;
l = 0:2*pi/100:2*pi;
HeadX = cos(l).*rmax;
HeadY = sin(l).*rmax;
NoseX = [0.18*rmax 0 -0.18*rmax];
NoseY = [rmax-.004 rmax*1.15 rmax-.004];
EarX = [.497 .510 .518 .5299 .5419 .54 .547 .532 .510 .489];
EarY = [.0555 .0775 .0783 .0746 .0555 -.0055 -.0932 -.1313 -.1384 -.1199];
% Scale the electrode positions to fit within a unit circle, i.e. electrode radius = 0.45
ind_scale = strmatch('SCALE', lay.label);
ind_comnt = strmatch('COMNT', lay.label);
sel = setdiff(1:length(lay.label), [ind_scale ind_comnt]); % these are excluded for scaling
x = lay.pos(sel,1);
y = lay.pos(sel,2);
xrange = range(x);
yrange = range(y);
% First scale the width and height of the box for multiplotting
lay.width = lay.width./xrange;
lay.height = lay.height./yrange;
% Then shift and scale the electrode positions
lay.pos(:,1) = 0.9*((lay.pos(:,1)-min(x))/xrange-0.5);
lay.pos(:,2) = 0.9*((lay.pos(:,2)-min(y))/yrange-0.5);
% Define the outline of the head, ears and nose
lay.outline{1} = [HeadX(:) HeadY(:)];
lay.outline{2} = [NoseX(:) NoseY(:)];
lay.outline{3} = [ EarX(:) EarY(:)];
lay.outline{4} = [-EarX(:) EarY(:)];
% Define the anatomical mask based on a circular head
lay.mask{1} = [HeadX(:) HeadY(:)];
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% apply the montage, i.e. combine bipolar channels into a new representation
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~strcmp(cfg.montage, 'no')
Norg = length(cfg.montage.labelorg);
Nnew = length(cfg.montage.labelnew);
for i=1:Nnew
cfg.montage.tra(i,:) = abs(cfg.montage.tra(i,:));
cfg.montage.tra(i,:) = cfg.montage.tra(i,:) ./ sum(cfg.montage.tra(i,:));
end
% pretend it is a sensor structure, this achieves averaging after channel matching
tmp.tra = lay.pos;
tmp.label = lay.label;
new = ft_apply_montage(tmp, cfg.montage);
lay.pos = new.tra;
lay.label = new.label;
% do the same for the width and height
tmp.tra = lay.width(:);
new = ft_apply_montage(tmp, cfg.montage);
lay.width = new.tra;
tmp.tra = lay.height(:);
new = ft_apply_montage(tmp, cfg.montage);
lay.height = new.tra;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% add axes positions for comments and scale information if required
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~any(strcmp('COMNT', lay.label)) && strcmpi(cfg.style, '2d') && ~skipcomnt
% add a placeholder for the comment in the upper left corner
lay.label{end+1} = 'COMNT';
lay.width(end+1) = mean(lay.width);
lay.height(end+1) = mean(lay.height);
X = min(lay.pos(:,1));
Y = max(lay.pos(:,2));
Y = min(lay.pos(:,2));
lay.pos(end+1,:) = [X Y];
elseif any(strcmp('COMNT', lay.label)) && skipcomnt
% remove the scale entry
sel = find(strcmp('COMNT', lay.label));
lay.label(sel) = [];
lay.pos(sel,:) = [];
lay.width(sel) = [];
lay.height(sel) = [];
end
if ~any(strcmp('SCALE', lay.label)) && strcmpi(cfg.style, '2d') && ~skipscale
% add a placeholder for the scale in the upper right corner
lay.label{end+1} = 'SCALE';
lay.width(end+1) = mean(lay.width);
lay.height(end+1) = mean(lay.height);
X = max(lay.pos(:,1));
Y = max(lay.pos(:,2));
Y = min(lay.pos(:,2));
lay.pos(end+1,:) = [X Y];
elseif any(strcmp('SCALE', lay.label)) && skipscale
% remove the scale entry
sel = find(strcmp('SCALE', lay.label));
lay.label(sel) = [];
lay.pos(sel,:) = [];
lay.width(sel) = [];
lay.height(sel) = [];
end
% to plot the layout for debugging, you can use this code snippet
if strcmp(cfg.feedback, 'yes') && strcmpi(cfg.style, '2d')
tmpcfg = [];
tmpcfg.layout = lay;
ft_layoutplot(tmpcfg);
end
% to write the layout to a text file, you can use this code snippet
if ~isempty(cfg.output) && strcmpi(cfg.style, '2d')
fprintf('writing layout to ''%s''\n', cfg.output);
fid = fopen(cfg.output, 'wt');
for i=1:numel(lay.label)
fprintf(fid, '%d %f %f %f %f %s\n', i, lay.pos(i,1), lay.pos(i,2), lay.width(i), lay.height(i), lay.label{i});
end
fclose(fid);
elseif ~isempty(cfg.output) && strcmpi(cfg.style, '3d')
% the layout file format does not support 3D positions, furthermore for
% a 3D layout the width and height are currently set to NaN
error('writing a 3D layout to an output file is not supported');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
% read the layout information from the ascii file
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function lay = readlay(filename)
if ~exist(filename, 'file')
error(sprintf('could not open layout file: %s', filename));
end
[chNum,X,Y,Width,Height,Lbl,Rem] = textread(filename,'%f %f %f %f %f %q %q');
if length(Rem)<length(Lbl)
Rem{length(Lbl)} = [];
end
for i=1:length(Lbl)
if ~isempty(Rem{i})
% this ensures that channel names with a space in them are also supported (i.e. Neuromag)
Lbl{i} = [Lbl{i} ' ' Rem{i}];
end
end
lay.pos = [X Y];
lay.width = Width;
lay.height = Height;
lay.label = Lbl;
return % function readlay
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
% convert 3D electrode positions into 2D layout
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function lay = sens2lay(sens, rz, method, style)
% remove the balancing from the sensor definition, e.g. 3rd order gradients, PCA-cleaned data or ICA projections
sens = undobalancing(sens);
fprintf('creating layout for %s system\n', ft_senstype(sens));
% apply rotation
if isempty(rz)
switch ft_senstype(sens)
case {'ctf151', 'ctf275', 'bti148', 'bti248', 'ctf151_planar', 'ctf275_planar', 'bti148_planar', 'bti248_planar', 'yokogawa160', 'yokogawa160_planar', 'yokogawa64', 'yokogawa64_planar', 'yokogawa440', 'yokogawa440_planar', 'magnetometer', 'meg'}
rz = 90;
case {'neuromag122', 'neuromag306'}
rz = 0;
case 'electrode'
rz = 90;
otherwise
rz = 0;
end
end
sens.pnt = warp_apply(rotate([0 0 rz]), sens.pnt, 'homogenous');
% use helper function for 3D layout
[pnt, label] = channelposition(sens);
if strcmpi(style, '3d')
lay.pos = pnt;
lay.label = label;
else
prj = elproj(pnt, method);
d = dist(prj');
d(find(eye(size(d)))) = inf;
% This is a fix for .sfp files, containing positions of 'fiducial
% electrodes'. Their presence determines the minimum distance between
% projected electrode positions, leading to very small boxes.
% This problem has been detected and reported by Matt Mollison.
% FIXME: consider changing the box-size being determined by mindist
% by a mean distance or so; this leads to overlapping boxes, but that
% also exists for some .lay files
if any(strmatch('Fid', label))
tmpsel = strmatch('Fid', label);
d(tmpsel, :) = inf;
d(:, tmpsel) = inf;
end
mindist = min(d(:));
X = prj(:,1);
Y = prj(:,2);
Width = ones(size(X)) * mindist * 0.8;
Height = ones(size(X)) * mindist * 0.6;
lay.pos = [X Y];
lay.width = Width;
lay.height = Height;
lay.label = label;
end
|
github
|
philippboehmsturm/antx-master
|
ft_spike_triggeredspectrum.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_spike_triggeredspectrum.m
| 15,754 |
utf_8
|
e32c9544218da94d42d8ff2acd4ec6f5
|
function [freq] = ft_spike_triggeredspectrum(cfg, data, spike)
% FT_SPIKE_TRIGGEREDSPECTRUM computes the Fourier spectrup of the LFP around the spikes.
%
% When spikes have binary representation, as obtained from APPENDSPIKE or FT_SPIKE_SPIKE2DATA, use
% [freq] = spiketriggeredspectrum(cfg, data)
% When spikes from SPIKE struct need to be directly combined with continuous representation, use as
% [freq] = ft_spike_triggeredspectrum(cfg,data,spike)
% Important: in that case data.time and spike.trialtime should be matched!
%
% Configurations:
% cfg.timwin = [begin end], time around each spike (default = [-0.1 0.1])
% cfg.foilim = [begin end], frequency band of interest (default = [0 150])
% cfg.taper = 'hanning' or many others, see WINDOW (default = 'hanning').
% cfg.tapsmofrq = number, the amount of spectral smoothing through
% multi-tapering. Note that 4 Hz smoothing means
% plus-minus 4 Hz, i.e. a 8 Hz smoothing box.
% cfg.taperopt = additional inputs going to WINDOW func as cell array, e.g.
% cfg.taperopt = {5, -35} with cfg.taper = 'taylorwin'.
% Note: multitapering rotates phases (no problem for consistency)
% cfg.spikechannel = string, name of single spike channel to trigger on. See FT_CHANNELSELECTION
% cfg.channel = Nx1 cell-array with selection of channels (default = 'all'),
% see FT_CHANNELSELECTION for details
% cfg.feedback = 'no', 'text', 'textbar', 'gui' (default = 'no')
% cfg.algorithm = 'vectorized' (default) or 'loop'. If the window around each spike
% is short, a moderate a speed up of 5-10 times is typical using vectorized
% code. However, for long windows (e.g. 0.5-1 second), vectorized
% algorithm is typically 50-100 times faster because it calls FFT only
% once per trial (instead of nSpikes times).
% In case an lfp segment contains NaNs, we use specest_nanfft.
% cfg.borderspikes = 'yes' (default) or 'no'. If 'yes', we process the spikes falling at the
% border using the same taper for the LFP that falls within the trial.
%
% If the triggered spike leads a spike in another channel, then the angle
% of the Fourier spectrum of that other channel will be negative. NOTE that
% this should be checked for consistency.
% % $Id: ft_spike_triggeredspectrum.m 3669 2011-06-09 20:26:57Z marvin $
% Copyright (C) 2008-2011, Robert Oostenveld, Martin Vinck
% set the defaults
if ~isfield(cfg, 'timwin'), cfg.timwin = [-0.1 0.1]; end
if ~isfield(cfg, 'foilim'), cfg.foilim = [0 150]; end
if ~isfield(cfg, 'taper'), cfg.taper = 'hanning'; end
if ~isfield(cfg, 'channel'), cfg.channel = 'all'; end
if ~isfield(cfg, 'spikechannel'), cfg.spikechannel = []; end
if ~isfield(cfg, 'feedback'), cfg.feedback = 'no'; end
if ~isfield(cfg, 'algorithm'), cfg.algorithm = 'loop'; end
if ~isfield(cfg, 'taperopt'), cfg.taperopt = []; end
if ~isfield(cfg,'borderspikes'), cfg.borderspikes = 'yes'; end
if strcmp(cfg.taper, 'sine')
error('sorry, sine taper is not yet implemented');
end
% determine which algorithm to use
if strcmp(cfg.algorithm,'loop')
doLoop = 1;
elseif strcmp(cfg.algorithm,'vectorized')
doLoop = 0;
else
error('unrecognized option for cfg.algorithm')
end
doBorderSpikes = strcmp(cfg.borderspikes,'yes');
% check whether a third input is specified
hasSpike = nargin==3;
% do the selection of the spikechannels
if hasSpike,
spikelabel = spike.label;
else
spikelabel = data.label;
end
% determine the channels to be averaged
cfg.channel = ft_channelselection(cfg.channel, data.label);
chansel = match_str(data.label, cfg.channel); % selected channels
nchansel = length(cfg.channel); % number of channels
% get the spikechannels
cfg.spikechannel = ft_channelselection(cfg.spikechannel, spikelabel);
spikesel = match_str(spikelabel, cfg.spikechannel);
nspikesel = length(cfg.spikechannel); % number of spike channels
if nspikesel~=1, error('MATLAB:ft_spike_triggeredspectrum:cfg:spiketriggeredspectrum:notOneSelected',...
'Onle one spike channel can be selected at a time');
end
nTrials = length(data.trial); % number of trials
% calculate number of samples left and right from spike and construct the taper
begpad = round(cfg.timwin(1)*data.fsample); % number of samples before spike
endpad = round(cfg.timwin(2)*data.fsample); % number of samples after spike
numsmp = endpad - begpad + 1; % number of samples of segment
if ~strcmp(cfg.taper,'dpss')
if iscell(cfg.taperopt)
taper = window(cfg.taper, numsmp, cfg.taperopt{:});
else
taper = window(cfg.taper, numsmp);
end
taper = taper./norm(taper);
else
% not implemented yet: keep tapers, or selecting only a subset of them.
taper = dpss(numsmp, cfg.tapsmofrq);
taper = taper(:,1:end-1); % we get 2*NW-1 tapers
taper = sum(taper,2)./size(taper,2); % using the linearity of multitapering
end
% frequency selection
freqaxis = linspace(0, data.fsample, numsmp);
fbeg = nearest(freqaxis, cfg.foilim(1));
fend = nearest(freqaxis, cfg.foilim(2));
freqs = freqaxis(fbeg:fend)'; % column vector that we use for rephasing later
nFreqs = fend - fbeg + 1;
cfg.foilim(1) = freqaxis(fbeg); % update the configuration to account for rounding off differences
cfg.foilim(2) = freqaxis(fend);
% make a representation of the spike, this is used for the phase rotation
spk = zeros(numsmp,1);
spk(1-begpad) = 1;
spike_fft = fft(spk);
spike_fft = spike_fft(fbeg:fend);
spike_fft = spike_fft./abs(spike_fft);
rephase = conj(spike_fft);
% preallocate the outputs
spectrum = cell(1,nTrials);
spiketime = cell(1,nTrials);
spiketrial = cell(1,nTrials);
% compute the spectra
for iTrial = 1:nTrials
if hasSpike
% get all the samples at once without using loops
hasTrial = spike.trial{spikesel} == iTrial;
ts = spike.time{spikesel}(hasTrial);
spikesmp = zeros(1,length(ts));
for k = 1:length(ts)
spikesmp(k) = nearest(data.time{iTrial},ts(k)); % this gives unique samples back
end
% calculate the phase shift based on difference between 'exact' and sample time
ts = ts(:);
smptime = data.time{iTrial}(spikesmp);
shift = ts - smptime(:);
elseif ~hasSpike
spikesmp = find(data.trial{iTrial}(spikesel,:)); % simply find the LFP segment belonging to the time-stamp here.
spikecnt = data.trial{iTrial}(spikesel,spikesmp);
% instead of doing the bookkeeping of double spikes below, replicate the double spikes by looking at spikecnt
sel = find(spikecnt>1);
tmp = zeros(1,sum(spikecnt(sel)));
n = 1;
for j=1:length(sel)
for k=1:spikecnt(sel(j))
tmp(n) = spikesmp(sel(j));
n = n + 1;
end
end
% remove the double spikes
spikesmp(sel) = []; % remove the double spikes
spikesmp = sort([spikesmp tmp]); % add the double spikes as replicated single spikes
end
% determine the beginning and end of the segments
begsmp = spikesmp + begpad;
endsmp = spikesmp + endpad;
% determine which spikes do not have their windows at the edges of the data
nSpikes = length(begsmp);
vldSpikes = begsmp>=1&endsmp<=size(data.trial{iTrial},2); % determine the valid spikes
earlySpikes = begsmp<1 & spikesmp>=1;
lateSpikes = spikesmp<=size(data.trial{iTrial},2) & endsmp>size(data.trial{iTrial},2);
if doBorderSpikes
vldSpikes = find(vldSpikes(:) | earlySpikes(:) | lateSpikes(:));
begsmp(earlySpikes) = 1;
endsmp(earlySpikes) = numsmp;
endsmp(lateSpikes) = size(data.trial{iTrial},2);
begsmp(lateSpikes) = size(data.trial{iTrial},2)-numsmp+1;
else
vldSpikes = find(vldSpikes);
end
nVld = length(vldSpikes);
% we want to process the incomplete spikes, also with hann window
% determine the new begsmp and endsmp for the spikes that fall around the border, we should not
% discard these, esp. not for low frequencies.
fprintf('processing trial %d of %d (%d spikes)\n', iTrial, nTrials, sum(nSpikes));
% store the spiketimes and spiketrials, constructing a type of SPIKE format
if ~hasSpike % otherwise we can immediate copy to FREQ.origtime and FREQ.origtrial
spiketime{iTrial} = data.time{iTrial}(spikesmp);
spiketrial{iTrial} = iTrial*ones(1,nSpikes);
end
% preallocate the spectrum that we create, also the spikes that will have NaNs
spectrum{iTrial} = NaN(nSpikes, nchansel, nFreqs);
rephaseMat = rephase(:,ones(1,nVld),ones(1,nchansel));
if doBorderSpikes && sum(earlySpikes)>0
for k = find(earlySpikes)
spk = zeros(numsmp,1);
spk(spikesmp(k)) = 1;
spike_fft = fft(spk);
spike_fft = spike_fft(fbeg:fend);
spike_fft = spike_fft./abs(spike_fft);
reph = conj(spike_fft);
rephaseMat(:,k,:) = repmat(reph,[1 1 nchansel]);
end
end
if doBorderSpikes && sum(lateSpikes)>0
n = size(data.trial{iTrial},2);
bg = n-numsmp;
for k = find(lateSpikes)
spk = zeros(numsmp,1);
spk(spikesmp(k)-bg) = 1;
spike_fft = fft(spk);
spike_fft = spike_fft(fbeg:fend);
spike_fft = spike_fft./abs(spike_fft);
reph = conj(spike_fft);
rephaseMat(:,k,:) = repmat(reph,[1 1 nchansel]);
end
end
if nVld<1,continue,end % continue to the next trial if this one does not contain valid spikes
if ~doLoop
% get the lfp, and reshape it such that we can index it at once.
lfp = data.trial{iTrial}(chansel,:);
lfp = reshape(lfp', [size(lfp,2) 1 nchansel]); % reshape to by time-by-1-by-nchansel
% form the indices to index the LFP at once
segment = linspacevec(begsmp(vldSpikes),endsmp(vldSpikes),numsmp)';
% cut out all windows at once to form a large 2-D matrix
segment = lfp(segment,:,:);
segment = reshape(segment,[numsmp nVld nchansel]);
segmentMean = repmat(nanmean(segment,1),[numsmp 1 1]); % nChan x Numsmp
segment = segment - segmentMean; % LFP has average of zero now (no DC)
segmentMean = []; % remove to save memory
lfp = [];
hasNan = find(any(isnan(segment))); % this will be indx for nSpikes-by-nChans
[row,col] = ind2sub([nVld nchansel], hasNan);
% replace the parts in segment where there were nans in the data
%my_fft = @specest_nanfft;
my_fft = @specest_nanfft_;
nNans = length(row);
fftNan = zeros(numsmp,nNans);
time = randn(size(segment)); % this is actually not used (MV: why is it there then?)
for iNan = 1:nNans
fftNan(:,iNan) = my_fft(segment(:,row(iNan),col(iNan)).*taper, time);
end
% fourier transform the data matrix
segment = fft(segment .* taper(:,ones(1,nVld), ones(1,nchansel)));
% replace the part of the segment with NaNs now
for iNan = 1:nNans
segment(:,row(iNan),col(iNan)) = fftNan(:,iNan);
end
% select the desired output frequencies and normalize
segment = segment(fbeg:fend,:,:) ./ sqrt(numsmp/2);
% rotate the phase at each frequency to correct for segment t=0 not being at the first sample
if hasSpike
% phase rotation according to difference data timeaxis and raw timestamps
shift = shift(vldSpikes)';
shiftrephase = shift(ones(nFreqs,1),:,ones(1,nchansel)).*freqs(:,ones(1,nVld),ones(1,nchansel));
shiftrephase = exp(i*2*pi*shiftrephase);
% rephase the fourier transform
segment = segment .* (rephase(:,ones(1,nVld),ones(1,nchansel)) .* shiftrephase);
else
segment = segment .* (rephase(:,ones(1,nVld),ones(1,nchansel)));
end
% collect the results
spectrum{iTrial}(vldSpikes,1:nchansel,1:nFreqs) = permute(segment,[2 3 1]);
else
my_fft = @specest_nanfft;
ft_progress('init', cfg.feedback, 'spectrally decomposing data around spikes');
reph = repmat(rephase,1,nchansel).';
for iSpike = vldSpikes
ft_progress(iTrial/nTrials, 'spectrally decomposing data around spike %d of %d\n', iSpike, length(spikesmp));
begsmp = spikesmp(iSpike) + begpad;
endsmp = spikesmp(iSpike) + endpad;
segment = data.trial{iTrial}(chansel,begsmp:endsmp);
% substract the DC component from every segment, to avoid any leakage of the taper
segmentMean = repmat(nanmean(segment,2),1,numsmp); % nChan x Numsmp
segment = segment - segmentMean; % LFP has average of zero now (no DC)
% taper the data segment around the spike and compute the fft
time = randn(size(segment)); % this is actually not used (MV: why is it there then?)
segment_fft = my_fft(segment * sparse(diag(taper)),time);
% select the desired output frequencies and normalize
segment_fft = segment_fft(:,fbeg:fend) ./ sqrt(numsmp/2);
% rotate the phase at each frequency to correct for segment t=0 not being at the first sample
if hasSpike
% phase rotation according to difference data timeaxis and raw timestamps
spikerephase = exp(2*pi*1i*shift(iSpike)*freqs); % use fft shift property
segment_fft = segment_fft.* reph .* spikerephase(:,ones(1,nchansel)).';
else
segment_fft = segment_fft.* reph;
end
% store the result for this spike in this trial
spectrum{iTrial}(iSpike,:,:) = segment_fft;
end % for each spike in this trial
ft_progress('close');
end
end % for each trial
% collect the results
freq.label = data.label(chansel);
freq.freq = freqaxis(fbeg:fend);
freq.dimord = 'rpt_chan_freq';
freq.fourierspctrm = cat(1, spectrum{:});
if ~hasSpike
freq.time = cat(2,spiketime{:})';
freq.trial = cat(2,spiketrial{:})';
for iTrial = 1:nTrials
freq.trialtime(iTrial,:) = [min(data.time{iTrial}) max(data.time{iTrial})];
end
else
freq.time = spike.time{spikesel}(:);
freq.trial = spike.trial{spikesel}(:);
freq.trialtime = spike.trialtime;
end
% add version information to the configuration
try
% get the full name of the function
cfg.version.name = mfilename('fullpath');
catch
% required for compatibility with Matlab versions prior to release 13 (6.5)
[st, ind] = dbstack;
cfg.version.name = st(ind);
end
% remember the configuration details of the input data
try, cfg.previous = data.cfg; end
% remember the exact configuration details in the output
freq.cfg = cfg;
function y = linspacevec(d1, d2, n)
%LINSPACEVEC Linearly spaced matrix with different stop and end values.
% Example:
% d1 = 1:10;
% d2 = 11:2:30;
% n = 10;
% indx = linspacevec(d1,d2,n)
% Copyright 2008 Vinck
if nargin == 2
n = 100;
end
d1 = d1(:);
d2 = d2(:);
d = d2-d1;
if numel(d1)==1
n = double(n);
y = [d1+(0:n-2)*d/(floor(n)-1) d2];
else
D = d(:,ones(n-1,1));
v = (0:n-2)';
N = v(:,ones(length(d1),1))';
D1 = d1(:,ones(n-1,1));
y = [D1+N.*D/(n-1) d2];
end
|
github
|
philippboehmsturm/antx-master
|
ft_freqbaseline.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_freqbaseline.m
| 7,075 |
utf_8
|
4dcbe7bcd54a8553f75b2a5fc67d4c45
|
function [freqOut] = ft_freqbaseline(cfg, freq)
% FT_FREQBASELINE performs baseline normalization for time-frequency data
%
% Use as
% [freq] = ft_freqbaseline(cfg, freq)
% where the freq data comes from FT_FREQANALYSIS and the configuration
% should contain
% cfg.baseline = [begin end] (default = 'no')
% cfg.baselinetype = 'absolute' 'relchange' 'relative' (default = 'absolute')
% cfg.param = field for which to apply baseline normalization, or
% cell array of strings to specify multiple fields to normalize
% (default = 'powspctrm')
%
% See also FT_FREQANALYSIS, FT_TIMELOCKBASELINE, FT_FREQCOMPARISON
% Undocumented local options:
% cfg.inputfile = one can specifiy preanalysed saved data as input
% cfg.outputfile = one can specify output as file to save to disk
% Copyright (C) 2004-2006, Marcel Bastiaansen
% Copyright (C) 2005-2006, Robert Oostenveld
% Copyright (C) 2011, Eelke Spaak
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_freqbaseline.m 3710 2011-06-16 14:04:19Z eelspa $
ft_defaults
% record start time and total processing time
ftFuncTimer = tic();
ftFuncClock = clock();
%% Input scaffolding
cfg = ft_checkconfig(cfg, 'trackconfig', 'on');
% set the defaults in the cfg structure
cfg.baseline = ft_getopt(cfg, 'baseline', 'no');
cfg.baselinetype = ft_getopt(cfg, 'baselinetype', 'absolute');
cfg.param = ft_getopt(cfg, 'param', 'powspctrm');
cfg.inputfile = ft_getopt(cfg, 'inputfile', []);
cfg.outputfile = ft_getopt(cfg, 'outputfile', []);
% check validity of input options
cfg = ft_checkopt(cfg, 'baseline', {'char', 'doublevector'});
cfg = ft_checkopt(cfg, 'baselinetype', 'char', {'absolute', 'relative', 'relchange'});
cfg = ft_checkopt(cfg, 'param', {'char', 'charcell'});
% make sure cfg.param is a cell array of strings
if (~isa(cfg.param, 'cell'))
cfg.param = {cfg.param};
end
% is input consistent?
if ischar(cfg.baseline) && strcmp(cfg.baseline, 'no') && ~isempty(cfg.baselinetype)
warning('no baseline correction done');
end
% process possible yes/no value of cfg.baseline
if ischar(cfg.baseline) && strcmp(cfg.baseline, 'yes')
% default is to take the prestimulus interval
cfg.baseline = [-inf 0];
elseif ischar(cfg.baseline) && strcmp(cfg.baseline, 'no')
% nothing to do
return
end
% should we read input data from file?
if ~isempty(cfg.inputfile)
if (nargin > 1)
error('cfg.inputfile should not be used in conjunction with giving input data to this function');
else
freq = loadvar(cfg.inputfile, 'freq');
end
end
% check if the input data is valid for this function
freq = ft_checkdata(freq, 'datatype', 'freq', 'feedback', 'yes');
% check if the field of interest is present in the data
if (~all(isfield(freq, cfg.param)))
error('cfg.param should be a string or cell array of strings referring to (a) field(s) in the freq input structure')
end
%% Computation of output
% initialize output structure
freqOut = [];
freqOut.label = freq.label;
freqOut.freq = freq.freq;
freqOut.dimord = freq.dimord;
freqOut.time = freq.time;
if isfield(freq, 'grad')
freqOut.grad = freq.grad;
end
if isfield(freq, 'elec')
freqOut.elec = freq.elec;
end
if isfield(freq, 'trialinfo')
freqOut.trialinfo = freq.trialinfo;
end
% loop over all fields that should be normalized
for k = 1:numel(cfg.param)
par = cfg.param{k};
if strcmp(freq.dimord, 'chan_freq_time')
freqOut.(par) = ...
performNormalization(freq.time, freq.(par), cfg.baseline, cfg.baselinetype);
elseif strcmp(freq.dimord, 'rpt_chan_freq_time') || strcmp(freq.dimord, 'chan_chan_freq_time')
freqOut.(par) = zeros(size(freq.(par)));
% loop over trials, perform normalization per trial
for l = 1:size(freq.(par), 1)
tfdata = freq.(par)(l,:,:,:);
siz = size(tfdata);
tfdata = reshape(tfdata, siz(2:end));
freqOut.(par)(l,:,:,:) = ...
performNormalization(freq.time, tfdata, cfg.baseline, cfg.baselinetype);
end
else
error('unsupported data dimensions: %s', freq.dimord);
end
end
%% Output scaffolding
% accessing this field here is needed for the configuration tracking
% by accessing it once, it will not be removed from the output cfg
cfg.outputfile;
% get the output cfg
cfg = ft_checkconfig(cfg, 'trackconfig', 'off', 'checksize', 'yes');
% add version information to the configuration
cfg.version.name = mfilename('fullpath');
cfg.version.id = '$Id: ft_freqbaseline.m 3710 2011-06-16 14:04:19Z eelspa $';
% add information about the Matlab version used to the configuration
cfg.callinfo.matlab = version();
% add information about the function call to the configuration
cfg.callinfo.proctime = toc(ftFuncTimer);
cfg.callinfo.calltime = ftFuncClock;
cfg.callinfo.user = getusername();
% remember the configuration details of the input data
if isfield(freq, 'cfg'),
cfg.previous = freq.cfg;
end
% remember the exact configuration details in the output
freqOut.cfg = cfg;
% the output data should be saved to a MATLAB file
if ~isempty(cfg.outputfile)
savevar(cfg.outputfile, 'freq', freqOut); % use the variable name "freq" in the output file
end
%% Helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% subfunction that actually performs the normalization on an arbitrary
% quantity
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function data = performNormalization(timeVec, data, baseline, baselinetype)
baselineTimes = (timeVec >= baseline(1) & timeVec <= baseline(2));
if length(size(data)) ~= 3,
error('time-frequency matrix should have three dimensions (chan,freq,time)');
end
% compute mean of time/frequency quantity in the baseline interval,
% ignoring NaNs, and replicate this over time dimension
meanVals = repmat(nanmean(data(:,:,baselineTimes), 3), [1 1 size(data, 3)]);
if (strcmp(baselinetype, 'absolute'))
data = data - meanVals;
elseif (strcmp(baselinetype, 'relative'))
data = data ./ meanVals;
elseif (strcmp(baselinetype, 'relchange'))
data = (data - meanVals) ./ meanVals;
else
error('unsupported method for baseline normalization: %s', baselinetype);
end
end
end % end of top-level function
|
github
|
philippboehmsturm/antx-master
|
ft_spike_psth.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_spike_psth.m
| 12,255 |
utf_8
|
df3235e096d34b7c5dab6c7fe244a8a1
|
function [psth] = ft_spike_psth(cfg,spike)
% FT_SPIKE_PSTH computes the peristimulus histogram of spiketrains.
%
% Use as
% [PSTH] = FT_SPIKE_PSTH(CFG,SPIKE)
%
% The input SPIKE should be organised as:
% The SPIKE datatype, obtained from FT_SPIKE_DATA2SPIKE or
% FT_SPIKE_MAKETRIALS.
%
% Configurations options:
%
% cfg.binsize = [binsize] in sec (default = 0.025 sec);
% cfg.outputunit = - 'rate' (default) If 'rate', we convert the
% output per bin to firing rates (spikes/sec).
% - 'spike': we count the number spikes per bin.
% cfg.spikechannel = See FT_CHANNELSELECTION for details.
% cfg.trials = - vector of indices (e.g., 1:2:10)
% - logical selection of trials (e.g., [1010101010])
% - 'all' (default), selects all trials
% cfg.vartriallen = - 'yes' (default)
% Accept variable trial lengths and use all available
% trials and the samples in every trial. Missing values will be
% ignored in the computation of the average and the variance and
% stored as NaNs in the output PSTH.TRIAL.
% - 'no'
% Only select those trials that fully cover the window as specified
% by cfg.latency and discard those trials that do not.
% cfg.latency = - [begin end] in seconds
% - 'maxperiod' (default), i.e., maximum period available
% - 'minperiod', i.e., the minimal period all trials share
% - 'prestim' (all t<=0)
% - 'poststim' (all t>=0).
% cfg.keeptrials = 'yes' or 'no' (default).
%
% Outputs:
% Psth is a structure similar to FT_TIMELOCKANALYSIS or FT_SPIKE_DENSITY.
% Psth.time = center histogram bin points
% Psth.fsample = 1/binsize;
% Psth.avg = contains average PSTH per unit
% Psth.trial = contains PSTH per unit per trial
% Psth.var = contains variance of PSTH per unit across trials
%
% PSTH can be fed into FT_TIMELOCKSTATISTICS, into FT_SPIKE_PLOT_PSTH (for
% plotting the PSTH), into FT_SPIKE_JPSTH (calculating the joint psth), into
% FT_SPIKE_PLOT_RASTER as cfg.topdata, in which we plot it above a rasterplot.
%
% Copyright (C) 2010, Martin Vinck
% TO ADD: binsize should be optimally determined based on
% standard techniques to compute binsize based on bandwidth. Same for FT_SPIKE_DENSITY
if nargin~=2, error('ft:spike_psth:nargin','Two input arguments required'), end
% check configuration inputs and enter the defaults, should be standardized within fieldtrip
defaults.binsize = {0.025}; % sec
defaults.outputunit = {'rate' 'spikecount'};
defaults.spikechannel = {'all'};
defaults.trials = {'all'};
defaults.latency = {'maxperiod'};
defaults.vartriallen = {'yes' 'no'};
defaults.keeptrials = {'yes' 'no'};
cfg = ft_spike_sub_defaultcfg(cfg,defaults);
% detect whether the format of spike is correct,
% should - when the spike format solidifies, in the end be done with checkdata in fieldtrip
hasAllFields = all(isfield(spike, {'trial', 'time', 'trialtime' 'label'}));
if ~hasAllFields, error('ft:spike_psth:wrongStructInput',...
'input SPIKE should be structure with .trial, .time, .trialtime .label fields')
end
% check whether all are of right format
correctInp = iscell(spike.time) && iscell(spike.trial) && iscell(spike.label) && isrealmat(spike.trialtime) ...
&& size(spike.trialtime,2)==2;
if ~correctInp, error('ft:spike_psth:wrongStructInput',...
'.time, .trial and .label should be cell arrays, .trialtime should be nTrials-by-2 matrix')
end
% get the number of trials or change DATA according to cfg.trials
cfg = trialselection(cfg,spike);
% select the unit - this should be done with channelselection function
cfg.channel = ft_channelselection(cfg.spikechannel, spike.label);
spikesel = match_str(spike.label, cfg.channel);
nUnits = length(spikesel);
if nUnits==0, error('ft:spike_psth:cfg:spikechannel:noSpikeChanSelected',...
'No spikechannel selected by means of cfg.spikechannel');
end
% determine the duration of each trial - we assume N by 2, see error check before
begTrialLatency = spike.trialtime(cfg.trials,1); % remember: already selected on trial here
endTrialLatency = spike.trialtime(cfg.trials,2);
trialDur = endTrialLatency - begTrialLatency;
% while we could simply deselect trials with trialtime field messed up, this may detect bugs
if any(trialDur<0), error('MATLAB:spike_psth:SPIKE.time:reversedOrder',...
'SPIKE.time(:,1) should preceed SPIKE.time(:,2), your SPIKE.time field is messed up');
end
% select the latencies, use the same modular function in all the scripts
cfg = latencyselection(cfg,begTrialLatency,endTrialLatency);
% do some error checking on the binsize
if cfg.binsize<=0 || cfg.binsize>(cfg.latency(2)-cfg.latency(1)),
error('ft:spike_psth:cfg:binsize:wrongInput',...
'cfg.binsize should be greater than zero and not exceed the trialduration');
end
% end of trial should be late enough, beginning should be early enough
fullDur = trialDur>=cfg.binsize; % trials which have full duration
overlaps = endTrialLatency>=(cfg.latency(1)+cfg.binsize) & begTrialLatency<=(cfg.latency(2)-cfg.binsize);
if strcmp(cfg.vartriallen,'no') % only select trials that fully cover our latency window
startsLater = single(begTrialLatency)>single(cfg.latency(1));
endsEarlier = single(endTrialLatency)<single(cfg.latency(2));
hasWindow = ~(startsLater | endsEarlier); % it should not start later or end earlier
else
hasWindow = ones(1,length(cfg.trials));
end
trialSel = fullDur(:) & overlaps(:) & hasWindow(:);
cfg.trials = cfg.trials(trialSel); % note that endTrialLatency was of length cfg.trials
if isempty(cfg.trials), % it should be explicitly tested that selecting no trial gives no error here
warning('ft:spike_psth:cfg:trials','No trials were selected after latency selection');
end
nTrials = length(cfg.trials);
begTrialLatency = begTrialLatency(trialSel); % note that begTrialLatency was of length cfg.trials here
endTrialLatency = endTrialLatency(trialSel);
% create the bins, this might harbour some inaccuracy if the latency window is not an
% integer multiple; we start arbitrarily at cfg.latency(1)
bins = cfg.latency(1) : cfg.binsize : cfg.latency(end);
nBins = length(bins);
% preallocate before computing the psth, otherwise, compute stuff 'on the run'
if strcmp(cfg.keeptrials,'yes'), singleTrials = NaN(nTrials,nUnits,nBins-1); end
[s,ss] = deal(zeros(nUnits, nBins-1)); %sum, and sum of squared in the loop, to get mean & var
% preallocate and compute degrees of freedom
allStartEarlier = all(begTrialLatency<=cfg.latency(1));
allEndLater = all(endTrialLatency>=cfg.latency(2));
if ~ (allStartEarlier && allEndLater),
dof = zeros(1,nBins-1);
else
dof = ones(1,nBins-1)*nTrials; % if all exceed latency, then this is dof
end
% compute the peristimulus histogram, different algorithms per data type
for iTrial = 1:nTrials % nTrials redefined on line 149, only the selected trials
origTrial = cfg.trials(iTrial);
if ~ (allStartEarlier && allEndLater) % select bins and count dof + 1
binSel = begTrialLatency(iTrial)<=bins(1:end-1) & endTrialLatency(iTrial)>=bins(2:end);
dof(binSel) = dof(binSel) + 1;
else
binSel = 1:(nBins-1); % always deselect the last bin
end
for iUnit = 1:nUnits
unitIndx = spikesel(iUnit); % select the unit
spikesInTrial = (spike.trial{unitIndx}==origTrial); % get spikes in trial
spikeTimes = spike.time{unitIndx}(spikesInTrial);
% compute the psth
trialPsth = histc(spikeTimes(:), bins); % we deselect the last bin per default
trialPsth = trialPsth(:)'; % force into row vec
if isempty(trialPsth), trialPsth = zeros(1,length(bins)); end
% convert to firing rates if requested, with spikecount do nothing
if strcmp(cfg.outputunit,'rate'), trialPsth = trialPsth/cfg.binsize; end
% compute the sum and the sum of squares for the var and the mean on the fly
s(iUnit,binSel) = s(iUnit,binSel) + trialPsth(binSel); % last bin is single value
ss(iUnit,binSel) = ss(iUnit,binSel) + trialPsth(binSel).^2;
if strcmp(cfg.keeptrials,'yes'),
singleTrials(iTrial,iUnit,binSel) = trialPsth(binSel);
end
end
end
% get the results
dof = dof(ones(nUnits,1),:);
psth.avg = s ./ dof;
psth.var = (ss - s.^2./dof)./(dof-1); % since sumPsth.^2 ./ dof = dof .* (sumPsth/dof).^2
psth.dof = dof; % combined with psth.var we can get SEM
psth.fsample = 1/(cfg.binsize); % might be more compatible with feeding psth in other funcs
psth.time = bins(1:end-1) + 0.5*cfg.binsize; % use .time name
psth.label = spike.label(spikesel);
if (strcmp(cfg.keeptrials,'yes'))
psth.trial = singleTrials;
psth.dimord = 'rpt_chan_time'; % perhaps we need two dimords here, what's the FT convention?
else
psth.dimord = 'chan_time';
end
% add version information to the configuration
try
% get the full name of the function
cfg.version.name = mfilename('fullpath');
catch
% required for compatibility with Matlab versions prior to release 13 (6.5)
[st, i] = dbstack;
cfg.version.name = st(i);
end
% remember the configuration details of the input data
if isfield(spike,'cfg'),cfg.previous = spike.cfg; end
% remember the exact configuration details in the output
psth.cfg = cfg;
%%%%%%%%% SUB FUNCTIONS %%%%%%%%%
function [cfg] = latencyselection(cfg,begTrialLatency,endTrialLatency)
if strcmp(cfg.latency,'minperiod')
cfg.latency = [max(begTrialLatency) min(endTrialLatency)];
elseif strcmp(cfg.latency,'maxperiod')
cfg.latency = [min(begTrialLatency) max(endTrialLatency)];
elseif strcmp(cfg.latency,'prestim')
cfg.latency = [min(begTrialLatency) 0];
elseif strcmp(cfg.latency,'poststim')
cfg.latency = [0 max(endTrialLatency)];
elseif ~isrealvec(cfg.latency)||length(cfg.latency)~=2
error('ft:spike_psth:cfg:latency:unknownOption',...
'cfg.latency should be "maxperiod", "minperiod", "prestim", "poststim" or 1-by-2 numerical vector');
end
if cfg.latency(1)>=cfg.latency(2), % check if it is ordered vector
error('ft:spike_psth:cfg:latency:decreasingLatencyVector',...
'cfg.latency should be ascending vector, such that cfg.latency(2)>cfg.latency(1)');
end
% check whether the time window fits with the data
if (cfg.latency(1) < min(begTrialLatency)), cfg.latency(1) = min(begTrialLatency);
warning('ft:spike_psth:cfg:latencyBegBeforeTrialBeg',...
'Correcting begin latency because it is before all trial beginnings');
end
if (cfg.latency(2) > max(endTrialLatency)), cfg.latency(2) = max(endTrialLatency);
warning('ft:spike_psth:cfg:latencyEndAfterTrialEnd',...
'Correcting end latency because it is after all trial ends');
end
%%%
function [cfg] = trialselection(cfg,spike)
% get the number of trials or change DATA according to cfg.trials
nTrials = size(spike.trialtime,1);
if strcmp(cfg.trials,'all')
cfg.trials = 1:nTrials;
elseif islogical(cfg.trials)
cfg.trials = find(cfg.trials);
elseif ~isrealvec(cfg.trials);
error('ft:spike_psth:cfg:trials:unknownOption',...
'cfg.trials should be logical or numerical selection or string "all"');
end
cfg.trials = sort(cfg.trials(:));
if max(cfg.trials)>nTrials, error('ft:spike_psth:cfg:trials:maxExceeded',...
'maximum trial number in cfg.trials should not exceed length of DATA.trial')
end
if isempty(cfg.trials), error('ft:spike_psth:cfg:trials:noneSelected',...
'No trials were selected by you, rien ne va plus');
end
|
github
|
philippboehmsturm/antx-master
|
ft_sourceinterpolate.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_sourceinterpolate.m
| 18,752 |
utf_8
|
19e7fac5cb7784e717324357e8b95815
|
function [interp] = ft_sourceinterpolate(cfg, functional, anatomical)
% FT_SOURCEINTERPOLATE reslices and interpolates a source reconstruction
% or a statistical distribution as an overlay onto an anatomical MRI.
%
% Both the functional data and the anatomical data can either describe a
% 3-dimensional volume, an arbitrary cloud of points, or a triangulated
% mesh.
%
% The following scenarios are possible:
%
% -The functional data is defined on a low resolution 2-dimensional triangulated
% mesh, the vertices being a subset of the high resolution 2-dimensional
% triangulated anatomical mesh. This allows for mesh based interpolation. The
% algorithm currently implemented is so-called 'smudging' as it is also
% applied by the MNE-suite software.
%
% -Both the functional and the anatomical data are defined on an irregular
% point cloud (can be a 2D triangulated mesh).
%
% -The functional data is defined on an irregular point cloud (can be a 2D
% triangulated mesh), and the anatomical data is a volumetric image.
%
% -The functional data is defined on a 3D regular grid of source positions
% and the anatomical data is defined on an irregular point cloud (can be a
% 2D triangulated mesh).
%
% -The functional data is defined on a 3D regular grid of source positions
% and the anatomical data is a volumetric image.
%
% The functional and anatomical data should be expressed in the same
% coordinate sytem, i.e. either both in CTF coordinates (NAS/LPA/RPA)
% or both in SPM coordinates (AC/PC).
%
% The output data will contain a description of the functional data at the
% locations at which the anatomical data are defined. For example, if the
% anatomical data was volumetric, the output data is a volume-structure,
% containing the resliced source and the anatomical volume that can be
% plotted together, using FT_SOURCEPLOT or FT_SLICEINTERP,
% or that can be written to file using FT_SOURCEWRITE.
%
% Use as
% [interp] = ft_sourceinterpolate(cfg, source, mri) or
% [interp] = ft_sourceinterpolate(cfg, stat, mri)
% where
% source is the output of FT_SOURCEANALYSIS
% stat is the output of FT_SOURCESTATISTICS
% mri is the output of FT_READ_MRI or the filename of a MRI,
% or
% the output of FT_READ_HEADSHAPE or the filename of a file
% containing the description of a cortical sheet.
% and cfg is a structure with any of the following fields
% cfg.parameter = string, default is 'all'
% cfg.interpmethod = 'linear', 'cubic', 'nearest' or 'spline' when
% interpolating two 3D volumes onto each other
% cfg.interpmethod = 'nearest', 'sphere_avg' or 'smudge' when
% interpolating a point cloud onto a 3D volume, a
% 3D volume onto a point cloud, or a point cloud
% with another point cloud
% cfg.downsample = integer number (default = 1, i.e. no downsampling)
%
% To facilitate data-handling and distributed computing with the peer-to-peer
% module, this function has the following options:
% cfg.inputfile = ...
% cfg.outputfile = ...
% If you specify one of these (or both) the input data will be read from a *.mat
% file on disk and/or the output data will be written to a *.mat file. These mat
% files should contain only a single variable, corresponding with the
% input/output structure.
%
% See also FT_SOURCEANALYSIS, FT_SOURCESTATISTICS, FT_READ_MRI,
% FT_READ_HEADSHAPE
% Undocumented options
% cfg.voxelcoord = 'yes' (default) or 'no' determines whether the
% downsampled output anatomical MRI will have the x/y/zgrid converted or
% the homogeneous transformation matrix
% Copyright (C) 2003-2007, Robert Oostenveld
% Copyright (C) 2011, Jan-Mathijs Schoffelen
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_sourceinterpolate.m 3710 2011-06-16 14:04:19Z eelspa $
ft_defaults
% record start time and total processing time
ftFuncTimer = tic();
ftFuncClock = clock();
%% ft_checkdata see below!!! %%
% check if the input cfg is valid for this function
cfg = ft_checkconfig(cfg, 'trackconfig', 'on');
cfg = ft_checkconfig(cfg, 'unused', {'keepinside'});
cfg = ft_checkconfig(cfg, 'deprecated', {'sourceunits', 'mriunits'});
% set the defaults
if ~isfield(cfg, 'parameter'), cfg.parameter = 'all'; end
if ~isfield(cfg, 'sphereradius'), cfg.sphereradius = []; end
if ~isfield(cfg, 'downsample'); cfg.downsample = 1; end
if ~isfield(cfg, 'voxelcoord'), cfg.voxelcoord = 'yes'; end
if ~isfield(cfg, 'feedback'), cfg.feedback = 'text'; end
if ~isfield(cfg, 'inputfile'), cfg.inputfile = []; end
if ~isfield(cfg, 'outputfile'), cfg.outputfile = []; end
hasdata = (nargin>1);
hasinputfile = ~isempty(cfg.inputfile);
if hasdata && hasinputfile
error('cfg.inputfile should not be used in conjunction with giving input data to this function');
end
% load optional given *.mat inputfile as data
if hasinputfile
functional = loadvar(cfg.inputfile{1});
anatomical = loadvar(cfg.inputfile{2});
end
% read the anatomical MRI or cortical mesh from file
if ischar(anatomical)
try
fprintf('trying to read anatomical MRI from file\n');
anatomical = ft_read_mri(anatomical);
catch
fprintf('anatomical file does not seem to be an anatomical MRI\n');
end
end % if ischar
if ischar(anatomical)
try
fprintf('trying to read cortical mesh from file\n');
anatomical = ft_read_headshape(anatomical);
catch
fprintf('anatomical file does not seem to be a cortical mesh\n');
end
end % if ischar
if ischar(anatomical)
% if it ends up here, it means that all previous attempts failed
error('the anatomical file does not seem to contain an anatomical MRI, nor a cortical mesh');
end % if ischar
if isfield(anatomical, 'pnt')
% anatomical data consists of a mesh, but no smudging possible
is2Dana = 1;
elseif isfield(anatomical, 'transform') && isfield(anatomical, 'dim')
is2Dana = 0;
end
if isfield(functional, 'dim') && numel(functional.dim)==3
is2Dfun = 0;
else
is2Dfun = 1;
end
if is2Dfun && is2Dana && isfield(anatomical, 'orig') && isfield(anatomical.orig, 'pnt') && isfield(anatomical.orig, 'tri'),
% anatomical data consists of a decimated triangulated mesh, containing
% the original description, allowing for smudging. The coordinate systems
% do not necessarily have to align. Should this be imposed?
dosmudge = 1;
else
dosmudge = 0;
end
if dosmudge && is2Dana && is2Dfun
% smudge the low resolution functional data according to the strategy in
% MNE-suite (chapter 8.3 of the manual)
% hmmmm, if the input data contains a time dimension, then the output
% may be terribly blown up; most convenient would be to output only the
% smudging matrix, and project the data when plotting
if ~isfield(anatomical, 'orig')
error('this is not yet implemented');
end
interpmat = interp_ungridded(anatomical.pnt, anatomical.orig.pnt, 'projmethod', 'smudge', 'triout', anatomical.orig.tri);
interp = [];
interp.pos = anatomical.orig.pnt;
interp.tri = anatomical.orig.tri;
if isfield(interp, 'dim'),
interp = rmfield(interp, 'dim');
end
interp.inside = (1:size(interp.pos,1))';
interp.outside = [];
for k = 1:numel(cfg.parameter)
interp = setsubfield(interp, cfg.parameter{k}, interpmat*getsubfield(functional, cfg.parameter{k}));
end
elseif is2Dana && is2Dfun
% 'interp_ungridded'
error('not yet implemented');
elseif ~is2Dana && is2Dfun
cfg.interpmethod = ft_getopt(cfg, 'interpmethod', 'nearest');
% interpolate onto a 3D volume, ensure that the anatomical is indeed a
% volume
anatomical = ft_checkdata(anatomical, 'datatype', 'volume', 'inside', 'logical', 'feedback', 'yes', 'hasunits', 'yes');
functional = ft_convert_units(functional, anatomical.unit);
% get voxel indices and use interp_ungridded
dim = anatomical.dim;
[X, Y, Z] = ndgrid(1:dim(1), 1:dim(2), 1:dim(3));
interpmat = interp_ungridded(functional.pos, warp_apply(anatomical.transform, [X(:) Y(:) Z(:)]), ...
'projmethod', cfg.interpmethod, 'sphereradius', cfg.sphereradius); %FIXME include other key-value pairs as well
clear X Y Z;
interp = [];
interp.dim = dim;
interp.transform = anatomical.transform;
interp.inside = anatomical.inside;
interpmat(~anatomical.inside(:), :) = 0;
for k = 1:numel(cfg.parameter)
interp = setsubfield(interp, cfg.parameter{k}, reshape(interpmat*getsubfield(functional, cfg.parameter{k}),dim));
end
elseif is2Dana && ~is2Dfun
cfg.interpmethod = ft_getopt(cfg, 'interpmethod', 'nearest');
% interpolate the 3D volume onto the anatomy
anatomical = ft_convert_units(anatomical);
functional = ft_checkdata(functional, 'datatype', 'volume', 'inside', 'logical', 'feedback', 'yes', 'hasunits', 'yes');
functional = ft_convert_units(functional, anatomical.unit);
% get voxel indices and use interp_ungridded
dim = functional.dim;
[X, Y, Z] = ndgrid(1:dim(1), 1:dim(2), 1:dim(3));
interpmat = interp_ungridded([X(:) Y(:) Z(:)], warp_apply(inv(functional.transform), anatomical.pnt), ...,
'projmethod', cfg.interpmethod, 'sphereradius', cfg.sphereradius);
clear X Y Z;
interp = [];
interp.pos = anatomical.pnt;
interp.inside = (1:size(anatomical.pnt,1))';
interp.outside = [];
if isfield(anatomical, 'tri'), interp.tri = anatomical.tri; end
for k = 1:numel(cfg.parameter)
tmp = getsubfield(functional, cfg.parameter{k});
interp = setsubfield(interp, cfg.parameter{k}, interpmat*reshape(tmp, [prod(dim) numel(tmp)./prod(dim)]));
end
elseif ~is2Dana && ~is2Dfun
cfg.interpmethod = ft_getopt(cfg, 'interpmethod', 'linear');
% original implementation interpolate a 3D volume onto another 3D volume
% check if the input data is valid for this function and ensure that the structures correctly describes a volume
functional = ft_checkdata(functional, 'datatype', 'volume', 'inside', 'logical', 'feedback', 'yes', 'hasunits', 'yes');
anatomical = ft_checkdata(anatomical, 'datatype', 'volume', 'inside', 'logical', 'feedback', 'yes', 'hasunits', 'yes');
% ensure that the functional data has the same unit as the anatomical
% data
functional = ft_convert_units(functional, anatomical.unit);
% select the parameters that should be interpolated
cfg.parameter = parameterselection(cfg.parameter, functional);
cfg.parameter = setdiff(cfg.parameter, 'inside'); % inside is handled separately
if ~isequal(cfg.downsample, 1)
% downsample the anatomical volume
tmpcfg = [];
tmpcfg.downsample = cfg.downsample;
tmpcfg.parameter = 'anatomy';
anatomical = ft_volumedownsample(tmpcfg, anatomical);
end
% collect the functional volumes that should be converted
vol_name = {};
vol_data = {};
for i=1:length(cfg.parameter)
if ~iscell(getsubfield(functional, cfg.parameter{i}))
vol_name{end+1} = cfg.parameter{i};
vol_data{end+1} = getsubfield(functional, cfg.parameter{i});
else
fprintf('not interpolating %s, since it is not a scalar field\n', cfg.parameter{i});
end
end
% remember the coordinate trandsformation for both
transform_ana = anatomical.transform;
transform_fun = functional.transform;
% convert the anatomical voxel positions into voxel indices into the functional volume
anatomical.transform = functional.transform \ anatomical.transform;
functional.transform = eye(4);
[fx, fy, fz] = voxelcoords(functional);
[ax, ay, az] = voxelcoords(anatomical);
% estimate the subvolume of the anatomy that is spanned by the functional volume
minfx = 1;
minfy = 1;
minfz = 1;
maxfx = functional.dim(1);
maxfy = functional.dim(2);
maxfz = functional.dim(3);
sel = ax(:)>=minfx & ...
ax(:)<=maxfx & ...
ay(:)>=minfy & ...
ay(:)<=maxfy & ...
az(:)>=minfz & ...
az(:)<=maxfz;
fprintf('selecting subvolume of %.1f%%\n', 100*sum(sel)./prod(anatomical.dim));
% start with an empty output structure
interp = [];
dimf = [functional.dim 1 1];
allav = zeros([anatomical.dim dimf(4:end)]);
functional.inside = functional.inside(:,:,:,1,1);
if all(functional.inside(:))
% keep all voxels marked as inside
interp.inside = true(anatomical.dim);
else
% reslice and interpolate inside
interp.inside = zeros(anatomical.dim);
% interpolate with method nearest
interp.inside( sel) = my_interpn(double(functional.inside), ax(sel), ay(sel), az(sel), 'nearest', cfg.feedback);
interp.inside(~sel) = 0;
interp.inside = logical(interp.inside);
end
% prepare the grid that is used in the interpolation
fg = [fx(:) fy(:) fz(:)];
clear fx fy fz
% reslice and interpolate all functional volumes
for i=1:length(vol_name)
fprintf('reslicing and interpolating %s\n', vol_name{i});
for k=1:dimf(4)
for m=1:dimf(5)
fv = vol_data{i}(:,:,:,k,m);
if ~isa(fv, 'double')
% only convert if needed, this saves memory
fv = double(fv);
end
av = zeros(anatomical.dim);
% av( sel) = my_interpn(fx, fy, fz, fv, ax(sel), ay(sel), az(sel), cfg.interpmethod, cfg.feedback);
if islogical(vol_data{i})
% interpolate always with method nearest
av( sel) = my_interpn(fv, ax(sel), ay(sel), az(sel), 'nearest', cfg.feedback);
av = logical(av);
else
if ~all(functional.inside(:))
% extrapolate the outside of the functional volumes for better interpolation at the edges
fv(~functional.inside) = griddatan(fg(functional.inside(:), :), fv(functional.inside(:)), fg(~functional.inside(:), :), 'nearest');
end
% interpolate functional onto anatomical grid
av( sel) = my_interpn(fv, ax(sel), ay(sel), az(sel), cfg.interpmethod, cfg.feedback);
clear fv
av(~sel) = nan;
av(~interp.inside) = nan;
end
allav(:,:,:,k,m) = av;
clear av
end
end
interp = setsubfield(interp, vol_name{i}, allav);
end
% add the other parameters to the output
interp.dim = anatomical.dim;
interp.transform = transform_ana; % the original coordinate system
if ~any(strcmp(cfg.parameter, 'anatomy'))
% copy the anatomy into the functional data
interp.anatomy = anatomical.anatomy;
end
end
% these stay the same as the input anatomical MRI
if isfield(anatomical, 'coordsys')
interp.coordsys = anatomical.coordsys;
end
if isfield(anatomical, 'unit')
interp.unit = anatomical.unit;
end
% accessing this field here is needed for the configuration tracking
% by accessing it once, it will not be removed from the output cfg
cfg.outputfile;
% get the output cfg
cfg = ft_checkconfig(cfg, 'trackconfig', 'off', 'checksize', 'yes');
% add version information to the configuration
cfg.version.name = mfilename('fullpath');
cfg.version.id = '$Id: ft_sourceinterpolate.m 3710 2011-06-16 14:04:19Z eelspa $';
% add information about the Matlab version used to the configuration
cfg.callinfo.matlab = version();
% add information about the function call to the configuration
cfg.callinfo.proctime = toc(ftFuncTimer);
cfg.callinfo.calltime = ftFuncClock;
cfg.callinfo.user = getusername();
% remember the configuration details of the input data
cfg.previous = [];
if isfield(functional, 'cfg'), cfg.previous{1} = functional.cfg; end
if isfield(anatomical, 'cfg'), cfg.previous{2} = anatomical.cfg; end
% remember the exact configuration details in the output
interp.cfg = cfg;
% the output data should be saved to a MATLAB file
if ~isempty(cfg.outputfile)
savevar(cfg.outputfile, 'data', interp); % use the variable name "data" in the output file
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION this function computes the location of all voxels in head
% coordinates in a memory efficient manner
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [x, y, z] = voxelcoords(volume)
dim = volume.dim;
transform = volume.transform;
if isfield(volume, 'xgrid')
xgrid = volume.xgrid;
ygrid = volume.ygrid;
zgrid = volume.zgrid;
else
xgrid = 1:dim(1);
ygrid = 1:dim(2);
zgrid = 1:dim(3);
end
npix = prod(dim(1:2)); % number of voxels in a single slice
x = zeros(dim);
y = zeros(dim);
z = zeros(dim);
X = zeros(1,npix);
Y = zeros(1,npix);
Z = zeros(1,npix);
E = ones(1,npix);
% determine the voxel locations per slice
for i=1:dim(3)
[X(:), Y(:), Z(:)] = ndgrid(xgrid, ygrid, zgrid(i));
tmp = transform*[X; Y; Z; E];
x((1:npix)+(i-1)*npix) = tmp(1,:);
y((1:npix)+(i-1)*npix) = tmp(2,:);
z((1:npix)+(i-1)*npix) = tmp(3,:);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION for memory efficient interpolation
% the only reason for this function is that it does the interpolation in smaller chuncks
% this prevents memory problems that I often encountered here
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% function [av] = my_interpn(fx, fy, fz, fv, ax, ay, az, interpmethod, feedback);
function [av] = my_interpn(fv, ax, ay, az, interpmethod, feedback)
num = numel(ax); % total number of voxels
blocksize = floor(num/20); % number of voxels to interpolate at once, split it into 20 chuncks
lastblock = 0; % boolean flag for while loop
sel = 1:blocksize; % selection of voxels that are interpolated, this is the first chunck
av = zeros(size(ax));
ft_progress('init', feedback, 'interpolating');
while (1)
ft_progress(sel(1)/num, 'interpolating %.1f%%\n', 100*sel(1)/num);
if sel(end)>num
sel = sel(1):num;
lastblock = 1;
end
av(sel) = interpn(fv, ax(sel), ay(sel), az(sel), interpmethod);
if lastblock
break
end
sel = sel + blocksize;
end
ft_progress('close');
|
github
|
philippboehmsturm/antx-master
|
ft_megplanar.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_megplanar.m
| 13,770 |
utf_8
|
a0374c6a05ac11b0542b63351812b05c
|
function [interp] = ft_megplanar(cfg, data)
% FT_MEGPLANAR computes planar MEG gradients gradients for raw data
% obtained from FT_PREPROCESSING or an average ERF that was computed using
% FT_TIMELOCKANALYSIS. It can also work on data in the frequency domain,
% obtained with FREQANALYSIS. Prerequisite for this is that the data contain
% complex-valued fourierspectra.
%
% Use as
% [interp] = ft_megplanar(cfg, data)
%
% The configuration should contain
% cfg.planarmethod = 'orig' | 'sincos' | 'fitplane' | 'sourceproject'
% cfg.channel = Nx1 cell-array with selection of channels (default = 'MEG'),
% see FT_CHANNELSELECTION for details
% cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all')
%
% The methods orig, sincos and fitplane are all based on a neighbourhood
% interpolation. For these methods you need to specify
% cfg.neighbours = neighbourhood structure, see FT_NEIGHBOURSELECTION
%
% In the 'sourceproject' method a minumum current estimate is done using a
% large number of dipoles that are placed in the upper layer of the brain
% surface, followed by a forward computation towards a planar gradiometer
% array. This requires the specification of a volume conduction model of
% the head and of a source model. The 'sourceproject' method is not supported for
% frequency domain data.
%
% A head model must be specified with
% cfg.hdmfile = string, file containing the volume conduction model
% or alternatively manually using
% cfg.vol.r = radius of sphere
% cfg.vol.o = [x, y, z] position of origin
%
% A dipole layer representing the brain surface must be specified with
% cfg.inwardshift = depth of the source layer relative to the head model surface (default = 2.5, which is adequate for a skin-based head model)
% cfg.spheremesh = number of dipoles in the source layer (default = 642)
% cfg.pruneratio = for singular values, default is 1e-3
% cfg.headshape = a filename containing headshape, a structure containing a
% single triangulated boundary, or a Nx3 matrix with surface
% points
% If no headshape is specified, the dipole layer will be based on the inner compartment
% of the volume conduction model.
%
% To facilitate data-handling and distributed computing with the peer-to-peer
% module, this function has the following options:
% cfg.inputfile = ...
% cfg.outputfile = ...
% If you specify one of these (or both) the input data will be read from a *.mat
% file on disk and/or the output data will be written to a *.mat file. These mat
% files should contain only a single variable, corresponding with the
% input/output structure.
%
% See also FT_COMBINEPLANAR, FT_NEIGHBOURSELECTION
% This function depends on FT_PREPARE_BRAIN_SURFACE which has the following options:
% cfg.headshape (default set in FT_MEGPLANAR: cfg.headshape = 'headmodel'), documented
% cfg.inwardshift (default set in FT_MEGPLANAR: cfg.inwardshift = 2.5), documented
% cfg.spheremesh (default set in FT_MEGPLANAR: cfg.spheremesh = 642), documented
%
% This function depends on FT_PREPARE_VOL_SENS which has the following options:
% cfg.channel
% cfg.elec
% cfg.elecfile
% cfg.grad
% cfg.gradfile
% cfg.hdmfile, documented
% cfg.order
% cfg.vol, documented
% Copyright (C) 2004, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_megplanar.m 3876 2011-07-20 08:04:29Z jorhor $
ft_defaults
% record start time and total processing time
ftFuncTimer = tic();
ftFuncClock = clock();
cfg = ft_checkconfig(cfg, 'trackconfig', 'on');
% set defaults
if ~isfield(cfg, 'inputfile'), cfg.inputfile = []; end
if ~isfield(cfg, 'outputfile'), cfg.outputfile = []; end
cfg = ft_checkconfig(cfg, 'required', {'neighbours'});
if iscell(cfg.neighbours)
warning('Neighbourstructure is in old format - converting to structure array');
cfg.neighbours = fixneighbours(cfg.neighbours);
end
% load optional given inputfile as data
hasdata = (nargin>1);
if ~isempty(cfg.inputfile)
% the input data should be read from file
if hasdata
error('cfg.inputfile should not be used in conjunction with giving input data to this function');
else
data = loadvar(cfg.inputfile, 'data');
end
end
isfreq = ft_datatype(data, 'freq');
israw = ft_datatype(data, 'raw');
istlck = ft_datatype(data, 'timelock'); % this will be temporary converted into raw
% check if the input data is valid for this function
data = ft_checkdata(data, 'datatype', {'raw' 'freq'}, 'feedback', 'yes', 'hassampleinfo', 'yes', 'ismeg', 'yes', 'senstype', {'ctf151', 'ctf275', 'bti148', 'bti248', 'itab153', 'yokogawa160', 'yokogawa64'});
if istlck
% the timelocked data has just been converted to a raw representation
% and will be converted back to timelocked at the end of this function
israw = true;
end
if isfreq,
if ~isfield(data, 'fourierspctrm'), error('freq data should contain Fourier spectra'); end
end
% set the default configuration
if ~isfield(cfg, 'channel'), cfg.channel = 'MEG'; end
if ~isfield(cfg, 'trials'), cfg.trials = 'all'; end
if ~isfield(cfg, 'planarmethod'), cfg.planarmethod = 'sincos'; end
if strcmp(cfg.planarmethod, 'sourceproject')
if ~isfield(cfg, 'headshape'), cfg.headshape = []; end % empty will result in the vol being used
if ~isfield(cfg, 'inwardshift'), cfg.inwardshift = 2.5; end
if ~isfield(cfg, 'pruneratio'), cfg.pruneratio = 1e-3; end
if ~isfield(cfg, 'spheremesh'), cfg.spheremesh = 642; end
end
if isfield(cfg, 'headshape') && isa(cfg.headshape, 'config')
% convert the nested config-object back into a normal structure
cfg.headshape = struct(cfg.headshape);
end
% put the low-level options pertaining to the dipole grid in their own field
cfg = ft_checkconfig(cfg, 'createsubcfg', {'grid'});
cfg = ft_checkconfig(cfg, 'renamedvalue', {'headshape', 'headmodel', []});
% select trials of interest
if ~strcmp(cfg.trials, 'all')
fprintf('selecting %d trials\n', length(cfg.trials));
data = ft_selectdata(data, 'rpt', cfg.trials);
end
if strcmp(cfg.planarmethod, 'sourceproject')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Do an inverse computation with a simplified distributed source model
% and compute forward again with the axial gradiometer array replaced by
% a planar one.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if isfreq
error('the method ''sourceproject'' is not supported for frequency data as input');
end
Nchan = length(data.label);
Ntrials = length(data.trial);
% FT_PREPARE_VOL_SENS will match the data labels, the gradiometer labels and the
% volume model labels (in case of a multisphere model) and result in a gradiometer
% definition that only contains the gradiometers that are present in the data.
[vol, axial.grad, cfg] = prepare_headmodel(cfg, data);
% determine the dipole layer that represents the surface of the brain
if isempty(cfg.headshape)
% construct from the inner layer of the volume conduction model
pos = headsurface(vol, axial.grad, 'surface', 'cortex', 'inwardshift', cfg.inwardshift, 'npnt', cfg.spheremesh);
else
% get the surface describing the head shape
if isstruct(cfg.headshape) && isfield(cfg.headshape, 'pnt')
% use the headshape surface specified in the configuration
headshape = cfg.headshape;
elseif isnumeric(cfg.headshape) && size(cfg.headshape,2)==3
% use the headshape points specified in the configuration
headshape.pnt = cfg.headshape;
elseif ischar(cfg.headshape)
% read the headshape from file
headshape = ft_read_headshape(cfg.headshape);
else
error('cfg.headshape is not specified correctly')
end
if ~isfield(headshape, 'tri')
% generate a closed triangulation from the surface points
headshape.pnt = unique(headshape.pnt, 'rows');
headshape.tri = projecttri(headshape.pnt);
end
% construct from the head surface
pos = headsurface([], [], 'headshape', headshape, 'inwardshift', cfg.inwardshift, 'npnt', cfg.spheremesh);
end
% compute the forward model for the axial gradiometers
fprintf('computing forward model for %d dipoles\n', size(pos,1));
lfold = ft_compute_leadfield(pos, axial.grad, vol);
% construct the planar gradient definition and compute its forward model
% this will not work for a multisphere model, compute_leadfield will catch
% the error
planar.grad = constructplanargrad([], axial.grad);
lfnew = ft_compute_leadfield(pos, planar.grad, vol);
% compute the interpolation matrix
transform = lfnew * prunedinv(lfold, cfg.pruneratio);
% interpolate the data towards the planar gradiometers
for i=1:Ntrials
fprintf('interpolating trial %d to planar gradiometer\n', i);
interp.trial{i} = transform * data.trial{i}(dataindx,:);
end % for Ntrials
% all planar gradiometer channels are included in the output
interp.grad = planar.grad;
interp.label = planar.grad.label;
% copy the non-gradiometer channels back into the output data
other = setdiff(1:Nchan, dataindx);
for i=other
interp.label{end+1} = data.label{i};
for j=1:Ntrials
interp.trial{j}(end+1,:) = data.trial{j}(i,:);
end
end
else
% generically call megplanar_orig megplanar_sincos or megplanar_fitplante
fun = ['megplanar_' cfg.planarmethod];
if ~exist(fun, 'file')
error('unknown method for computation of planar gradient');
end
[sens.pnt, sens.ori, sens.label] = channelposition(data.grad);
cfg.channel = ft_channelselection(cfg.channel, sens.label);
cfg.neighbsel = channelconnectivity(cfg);
% determine
fprintf('average number of neighbours is %.2f\n', mean(sum(cfg.neighbsel)));
Ngrad = length(sens.label);
cfg.distance = zeros(Ngrad,Ngrad);
for i=1:Ngrad
j=find(cfg.neighbsel(i, :));
d = sqrt(sum((sens.pnt(j,:) - repmat(sens.pnt(i, :), numel(j), 1)).^2, 2));
cfg.distance(i,j) = d;
cfg.distance(j,i) = d;
end
fprintf('minimum distance between neighbours is %6.2f %s\n', min(cfg.distance(cfg.distance~=0)), data.grad.unit);
fprintf('maximum distance between gradiometers is %6.2f %s\n', max(cfg.distance(cfg.distance~=0)), data.grad.unit);
montage = eval([fun '(cfg, data.grad)']);
% apply the linear transformation to the data
interp = ft_apply_montage(data, montage, 'keepunused', 'yes');
% also apply the linear transformation to the gradiometer definition
interp.grad = ft_apply_montage(data.grad, montage, 'balancename', 'planar', 'keepunused', 'yes');
% ensure that the old sensor type does not stick around, because it is now invalid
% the sensor type is added in FT_PREPARE_VOL_SENS but is not used in external fieldtrip code
if isfield(interp.grad, 'type')
interp.grad = rmfield(interp.grad, 'type');
end
end
if istlck
% convert the raw structure back into a timelock structure
interp = ft_checkdata(interp, 'datatype', 'timelock');
israw = false;
end
% accessing this field here is needed for the configuration tracking
% by accessing it once, it will not be removed from the output cfg
cfg.outputfile;
% get the output cfg
cfg = ft_checkconfig(cfg, 'trackconfig', 'off', 'checksize', 'yes');
% store the configuration of this function call, including that of the previous function call
cfg.version.name = mfilename('fullpath');
cfg.version.id = '$Id: ft_megplanar.m 3876 2011-07-20 08:04:29Z jorhor $';
% add information about the Matlab version used to the configuration
cfg.callinfo.matlab = version();
% add information about the function call to the configuration
cfg.callinfo.proctime = toc(ftFuncTimer);
cfg.callinfo.calltime = ftFuncClock;
cfg.callinfo.user = getusername();
% remember the configuration details of the input data
try cfg.previous = data.cfg; end
% remember the exact configuration details in the output
interp.cfg = cfg;
% copy the trial specific information into the output
if isfield(data, 'trialinfo')
interp.trialinfo = data.trialinfo;
end
% copy the sampleinfo field as well
if isfield(data, 'sampleinfo')
interp.sampleinfo = data.sampleinfo;
end
% the output data should be saved to a MATLAB file
if ~isempty(cfg.outputfile)
savevar(cfg.outputfile, 'data', interp); % use the variable name "data" in the output file
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION that computes the inverse using a pruned SVD
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [lfi] = prunedinv(lf, r)
[u, s, v] = svd(lf);
p = find(s<(s(1,1)*r) & s~=0);
fprintf('pruning %d out of %d singular values\n', length(p), min(size(s)));
s(p) = 0;
s(find(s~=0)) = 1./s(find(s~=0));
lfi = v * s' * u';
|
github
|
philippboehmsturm/antx-master
|
ft_volumerealign.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_volumerealign.m
| 20,951 |
utf_8
|
d1ad8363bae8b0ea6ebc4bad08d6d197
|
function [mri] = ft_volumerealign(cfg, mri)
% FT_VOLUMEREALIGN spatially aligns an anatomical MRI with head coordinates based on
% external fiducials or anatomical landmarks. This function does not change the
% volume itself, but adjusts the homogeneous transformation matrix that describes
% the coordinate system.
%
% This function only changes the coordinate system of an anatomical
% MRI, it does not change the MRI as such. For spatial normalisation
% (warping) of an MRI to a template brain you should use the
% FT_VOLUMENORMALISE function.
%
% Use as
% [mri] = ft_volumerealign(cfg, mri)
% where mri is an anatomical volume (i.e. MRI) or a functional
% volume (i.e. source recunstruction that has been interpolated on
% an MRI).
%
% The configuration can contain the following options
% cfg.clim = [min max], scaling of the anatomy color (default
% is to adjust to the minimum and maximum)
% cfg.method = different methods for aligning the volume
% 'fiducial' realign the volume to the fiducials,
% using 'ALS_CTF' convention, i.e.
% the origin is exactly between lpa and rpa
% the X-axis goes towards nas
% the Y-axis goes approximately towards lpa,
% orthogonal to X and in the plane spanned
% by the fiducials
% the Z-axis goes approximately towards the vertex,
% orthogonal to X and Y
% 'landmark' realign the volume to anatomical landmarks,
% using RAS_Tal convention, i.e.
% the origin corresponds with the anterior commissure
% the Y-axis is along the line from the posterior
% commissure to the anterior commissure
% the Z-axis is towards the vertex, in between the
% hemispheres
% the X-axis is orthogonal to the YZ-plane,
% positive to the right
% 'interactive' manually using graphical user interface
%
% For realigning to the fiducials, you should specify the position of the
% fiducials in voxel indices.
% cfg.fiducial.nas = [i j k], position of nasion
% cfg.fiducial.lpa = [i j k], position of LPA
% cfg.fiducial.rpa = [i j k], position of RPA
%
% For realigning to the landmarks, you should specify the position of the
% landmarks in voxel indices.
% cfg.landmark.ac = [i j k], position of anterior commissure
% cfg.landmark.pc = [i j k], position of posterior commissure
% cfg.landmark.xzpoint = [i j k], point on the midsagittal-plane with positive Z-coordinate,
% i.e. interhemispheric point above ac and pc
%
% To facilitate data-handling and distributed computing with the peer-to-peer
% module, this function has the following options:
% cfg.inputfile = ...
% cfg.outputfile = ...
% If you specify one of these (or both) the input data will be read from a *.mat
% file on disk and/or the output data will be written to a *.mat file. These mat
% files should contain only a single variable, corresponding with the
% input/output structure.
%
% See also FT_READ_MRI, FT_ELECTRODEREALIGN
% Undocumented option
% cfg.coordsys, works for interactive and fiducial
% Copyright (C) 2006-2009, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_volumerealign.m 3888 2011-07-20 14:25:23Z jansch $
ft_defaults
% record start time and total processing time
ftFuncTimer = tic();
ftFuncClock = clock();
cfg = ft_checkconfig(cfg, 'renamedval', {'method', 'realignfiducial', 'fiducial'});
cfg = ft_checkconfig(cfg, 'trackconfig', 'on');
cfg = ft_checkconfig(cfg, 'required', 'method');
% set the defaults
if ~isfield(cfg, 'fiducial'), cfg.fiducial = []; end
if ~isfield(cfg, 'landmark'), cfg.landmark = []; end
if ~isfield(cfg, 'parameter'), cfg.parameter = 'anatomy'; end
if ~isfield(cfg, 'clim'), cfg.clim = []; end
if ~isfield(cfg, 'inputfile'), cfg.inputfile = []; end
if ~isfield(cfg, 'outputfile'),cfg.outputfile = []; end
if ~isfield(cfg, 'coordsys') && (strcmp(cfg.method, 'interactive') || strcmp(cfg.method, 'fiducial'))
cfg.coordsys = 'ctf';
end
hasdata = (nargin>1);
if ~isempty(cfg.inputfile)
% the input data should be read from file
if hasdata
error('cfg.inputfile should not be used in conjunction with giving input data to this function');
else
mri = loadvar(cfg.inputfile, 'mri');
end
end
% check if the input data is valid for this function
mri = ft_checkdata(mri, 'datatype', 'volume', 'feedback', 'yes');
if ~isfield(cfg, 'method')
if ~isempty(cfg.fiducial)
cfg.method = 'fiducial';
basedonfid = 1;
basedonmrk = 0;
elseif ~isempty(cfg.landmark)
cfg.method = 'landmark';
basedonfid = 0;
basedonmrk = 1;
else
cfg.method = 'interactive';
end
end
if strcmp(cfg.method, 'interactive')
basedonfid = 0;
basedonmrk = 0;
elseif strcmp(cfg.method, 'fiducial')
basedonfid = 1;
basedonmrk = 0;
elseif strcmp(cfg.method, 'landmark')
basedonfid = 0;
basedonmrk = 1;
end
% select the parameter that should be displayed
cfg.parameter = parameterselection(cfg.parameter, mri);
if iscell(cfg.parameter)
cfg.parameter = cfg.parameter{1};
end
h1 = subplot('position',[0.02 0.55 0.44 0.44]);%subplot(2,2,1);
h2 = subplot('position',[0.52 0.55 0.44 0.44]);%subplot(2,2,2);
h3 = subplot('position',[0.02 0.05 0.44 0.44]);%subplot(2,2,3);
handles = {h1 h2 h3};
switch cfg.method
case 'fiducial'
% do nothing
case 'landmark'
% do nothing
case 'interactive'
showcrosshair = true;
showmarkers = true;
dat = mri.(cfg.parameter);
nas = [];
lpa = [];
rpa = [];
antcomm = [];
pstcomm = [];
xzpoint = [];
x = 1:mri.dim(1);
y = 1:mri.dim(2);
z = 1:mri.dim(3);
xc = round(mri.dim(1)/2);
yc = round(mri.dim(2)/2);
zc = round(mri.dim(3)/2);
updatepanel = [1 2 3];
pnt = zeros(0,3);
markerpos = zeros(0,3);
markerlabel = {};
markercolor = {};
while true % break when 'q' is pressed
fprintf('click with mouse button to reslice the display to a new position\n');
fprintf('press n/l/r on keyboard to record the current position as fiducial location\n');
fprintf('press a/p/z on keyboard to record the current position as anatomical landmark\n');
fprintf('press the arrow keys on the keyboard to increment or decrement the slice number by one\n');
fprintf('press c or C on the keyboard to show or hide the crosshair\n');
fprintf('press q on keyboard to quit interactive mode\n');
xc = round(xc); xc = max(1,xc); xc = min(mri.dim(1),xc);
yc = round(yc); yc = max(1,yc); yc = min(mri.dim(2),yc);
zc = round(zc); zc = max(1,zc); zc = min(mri.dim(3),zc);
markers = {markerpos markerlabel markercolor};
[h1, h2, h3] = volplot(x, y, z, dat, [xc yc zc], cfg.clim, showcrosshair, updatepanel, handles, showmarkers, markers);
drawnow;
try, [d1, d2, key] = ginput(1); catch, key='q'; end
switch key
case 113 % 'q'
break;
case 108 % 'l'
lpa = [xc yc zc];
case 114 % 'r'
rpa = [xc yc zc];
case 110 % 'n'
nas = [xc yc zc];
case 97 % 'a'
antcomm = [xc yc zc];
case 112 % 'p'
pstcomm = [xc yc zc];
case 122 % 'z'
xzpoint = [xc yc zc];
case 99 % 'c'
showcrosshair = true;
case 67 % 'C'
showcrosshair = false;
case 1 % left mouse click
% update the view to a new position
l1 = get(get(gca, 'xlabel'), 'string');
l2 = get(get(gca, 'ylabel'), 'string');
switch l1,
case 'i'
xc = d1;
case 'j'
yc = d1;
case 'k'
zc = d1;
otherwise
continue;
end
switch l2,
case 'i'
xc = d2;
case 'j'
yc = d2;
case 'k'
zc = d2;
otherwise
continue;
end
if l1=='i' && l2=='j'
updatepanel = [1 2 3];
elseif l1=='i' && l2=='k'
updatepanel = [2 3 1];
elseif l1=='j' && l2=='k'
updatepanel = [3 1 2];
end
case 3 % right mouse click
% add point to a list
l1 = get(get(gca, 'xlabel'), 'string');
l2 = get(get(gca, 'ylabel'), 'string');
switch l1,
case 'i'
xc = d1;
case 'j'
yc = d1;
case 'k'
zc = d1;
end
switch l2,
case 'i'
xc = d2;
case 'j'
yc = d2;
case 'k'
zc = d2;
end
pnt = [pnt; xc yc zc];
if l1=='i' && l2=='j'
updatepanel = [1 2 3];
elseif l1=='i' && l2=='k'
updatepanel = [2 3 1];
elseif l1=='j' && l2=='k'
updatepanel = [3 1 2];
end
case 2 % middle mouse click
l1 = get(get(gca, 'xlabel'), 'string');
l2 = get(get(gca, 'ylabel'), 'string');
% remove the previous point
if size(pnt,1)>0
pnt(end,:) = [];
end
if l1=='i' && l2=='j'
updatepanel = [1 2 3];
elseif l1=='i' && l2=='k'
updatepanel = [2 3 1];
elseif l1=='j' && l2=='k'
updatepanel = [3 1 2];
end
case 28 % arrow left
% update the coordinates
l1 = get(get(gca, 'xlabel'), 'string');
l2 = get(get(gca, 'ylabel'), 'string');
if l1=='i' && l2=='j'
xc = xc-1; updatepanel = [1 2 3];
elseif l1=='i' && l2=='k'
xc = xc-1; updatepanel = [2 3 1];
elseif l1=='j' && l2=='k'
yc = yc-1; updatepanel = [3 1 2];
end
case 30 % arrow up
% update the coordinates
l1 = get(get(gca, 'xlabel'), 'string');
l2 = get(get(gca, 'ylabel'), 'string');
if l1=='i' && l2=='j'
yc = yc+1; updatepanel = [1 2 3];
elseif l1=='i' && l2=='k'
zc = zc+1; updatepanel = [2 3 1];
elseif l1=='j' && l2=='k'
zc = zc+1; updatepanel = [3 1 2];
end
case 29 % arrow right
% update the coordinates
l1 = get(get(gca, 'xlabel'), 'string');
l2 = get(get(gca, 'ylabel'), 'string');
if l1=='i' && l2=='j'
xc = xc+1; updatepanel = [1 2 3];
elseif l1=='i' && l2=='k'
xc = xc+1; updatepanel = [2 3 1];
elseif l1=='j' && l2=='k'
yc = yc+1; updatepanel = [3 1 2];
end
case 31 % arrow down
% update the coordinates
l1 = get(get(gca, 'xlabel'), 'string');
l2 = get(get(gca, 'ylabel'), 'string');
if l1=='i' && l2=='j'
yc = yc-1; updatepanel = [1 2 3];
elseif l1=='i' && l2=='k'
zc = zc-1; updatepanel = [2 3 1];
elseif l1=='j' && l2=='k'
zc = zc-1; updatepanel = [3 1 2];
end
otherwise
% do nothing
end
fprintf('============================================================\n');
if all(round([xc yc zc])<=mri.dim)
str = sprintf('voxel %d, indices [%d %d %d]', sub2ind(mri.dim(1:3), round(xc), round(yc), round(zc)), round([xc yc zc]));
if isfield(mri, 'coordsys') && isfield(mri, 'unit')
str = sprintf('%s, %s coordinates [%.1f %.1f %.1f] %s', str, mri.coordsys, warp_apply(mri.transform, [xc yc zc]), mri.unit);
elseif ~isfield(mri, 'coordsys') && isfield(mri, 'unit')
str = sprintf('%s, location [%.1f %.1f %.1f] %s', str, warp_apply(mri.transform, [xc yc zc]), mri.unit);
elseif isfield(mri, 'coordsys') && ~isfield(mri, 'unit')
str = sprintf('%s, %s coordinates [%.1f %.1f %.1f]', str, mri.coordsys, warp_apply(mri.transform, [xc yc zc]));
elseif ~isfield(mri, 'coordsys') && ~isfield(mri, 'unis')
str = sprintf('%s, location [%.1f %.1f %.1f]', str, warp_apply(mri.transform, [xc yc zc]));
end
fprintf('%s\n', str);
% fprintf('cur_voxel = [%f %f %f], cur_head = [%f %f %f]\n', [xc yc zc], warp_apply(mri.transform, [xc yc zc]));
end
markerpos = zeros(0,3);
markerlabel = {};
markercolor = {};
if ~isempty(nas),
fprintf('nas_voxel = [%f %f %f], nas_head = [%f %f %f]\n', nas, warp_apply(mri.transform, nas));
markerpos = [markerpos; nas];
markerlabel = [markerlabel; {'nas'}];
markercolor = [markercolor; {'b'}];
end
if ~isempty(lpa),
fprintf('lpa_voxel = [%f %f %f], lpa_head = [%f %f %f]\n', lpa, warp_apply(mri.transform, lpa));
markerpos = [markerpos; lpa];
markerlabel = [markerlabel; {'lpa'}];
markercolor = [markercolor; {'g'}];
end
if ~isempty(rpa),
fprintf('rpa_voxel = [%f %f %f], rpa_head = [%f %f %f]\n', rpa, warp_apply(mri.transform, rpa));
markerpos = [markerpos; rpa];
markerlabel = [markerlabel; {'rpa'}];
markercolor = [markercolor; {'r'}];
end
if ~isempty(antcomm),
fprintf('antcomm_voxel = [%f %f %f], antcomm_head = [%f %f %f]\n', antcomm, warp_apply(mri.transform, antcomm));
markerpos = [markerpos; antcomm];
markerlabel = [markerlabel; {'antcomm'}];
markercolor = [markercolor; {'b'}];
end
if ~isempty(pstcomm),
fprintf('pstcomm_voxel = [%f %f %f], pstcomm_head = [%f %f %f]\n', pstcomm, warp_apply(mri.transform, pstcomm));
markerpos = [markerpos; pstcomm];
markerlabel = [markerlabel; {'pstcomm'}];
markercolor = [markercolor; {'g'}];
end
if ~isempty(xzpoint),
fprintf('xzpoint_voxel = [%f %f %f], xzpoint_head = [%f %f %f]\n', xzpoint, warp_apply(mri.transform, xzpoint));
markerpos = [markerpos; xzpoint];
markerlabel = [markerlabel; {'xzpoint'}];
markercolor = [markercolor; {'r'}];
end
if ~isempty(pnt)
fprintf('%f extra points selected\n', size(pnt,1));
markerpos = [markerpos; pnt];
markerlabel = [markerlabel; repmat({''}, size(pnt,1), 1)];
markercolor = [markercolor; repmat({'m'}, size(pnt,1), 1)];
end
end % while true
cfg.fiducial.nas = nas;
cfg.fiducial.lpa = lpa;
cfg.fiducial.rpa = rpa;
cfg.landmark.ac = antcomm;
cfg.landmark.pc = pstcomm;
cfg.landmark.xzpoint = xzpoint;
if ~isempty(nas) && ~isempty(lpa) && ~isempty(rpa)
basedonfid = 1;
end
if ~isempty(antcomm) && ~isempty(pstcomm) && ~isempty(xzpoint)
basedonmrk = 1;
end
otherwise
error('unsupported method');
end
if basedonfid && basedonmrk
basedonmrk = 0;
warning('both fiducials and anatomical landmarks have been defined interactively: using the fiducials for realignment');
end
if basedonfid
% the fiducial locations are now specified in voxels, convert them to head
% coordinates according to the existing transform matrix
nas_head = warp_apply(mri.transform, cfg.fiducial.nas);
lpa_head = warp_apply(mri.transform, cfg.fiducial.lpa);
rpa_head = warp_apply(mri.transform, cfg.fiducial.rpa);
% compute the homogenous transformation matrix describing the new coordinate system
[realign, coordsys] = headcoordinates(nas_head, lpa_head, rpa_head, cfg.coordsys);
elseif basedonmrk
% the fiducial locations are now specified in voxels, convert them to head
% coordinates according to the existing transform matrix
ac = warp_apply(mri.transform, cfg.landmark.ac);
pc = warp_apply(mri.transform, cfg.landmark.pc);
xzpoint= warp_apply(mri.transform, cfg.landmark.xzpoint);
% compute the homogenous transformation matrix describing the new coordinate system
[realign, coordsys] = headcoordinates(ac, pc, xzpoint, 'spm');
else
realign = [];
end
if ~isempty(realign)
% combine the additional transformation with the original one
mri.transformorig = mri.transform;
mri.transform = realign * mri.transform;
mri.coordsys = coordsys;
else
warning('no coordinate system realignment has been done');
end
if exist('pnt', 'var')
mri.pnt = pnt;
end
% accessing this field here is needed for the configuration tracking
% by accessing it once, it will not be removed from the output cfg
cfg.outputfile;
% get the output cfg
cfg = ft_checkconfig(cfg, 'trackconfig', 'off', 'checksize', 'yes');
% add version information to the configuration
cfg.version.name = mfilename('fullpath');
cfg.version.id = '$Id: ft_volumerealign.m 3888 2011-07-20 14:25:23Z jansch $';
% add information about the Matlab version used to the configuration
cfg.version.matlab = version();
% add information about the function call to the configuration
cfg.callinfo.proctime = toc(ftFuncTimer);
cfg.callinfo.calltime = ftFuncClock;
cfg.callinfo.user = getusername();
if isfield(mri, 'cfg'), cfg.previous = mri.cfg; end
% remember the configuration
mri.cfg = cfg;
% the output data should be saved to a MATLAB file
if ~isempty(cfg.outputfile)
savevar(cfg.outputfile, 'mri', mri); % use the variable name "data" in the output file
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function to show three orthogonal slices
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [h1, h2, h3] = volplot(x, y, z, dat, c, cscale, showcrosshair, updatepanel, handles, showmarkers, markers)
xi = c(1);
yi = c(2);
zi = c(3);
% manual color scaling of anatomy data is usefull in case of some pixel noise
if nargin<6 || isempty(cscale)
cmin = min(dat(:));
cmax = max(dat(:));
else
cmin = cscale(1);
cmax = cscale(2);
end
if nargin<8
updatepanel = [1 2 3];
end
if nargin<9
h1 = [];
h2 = [];
h3 = [];
else
h1 = handles{1};
h2 = handles{2};
h3 = handles{3};
end
if showmarkers
markerpos = round(markers{1});
markercolor = markers{3};
sel1 = find(markerpos(:,2)==repmat(c(2),size(markerpos,1),1));
sel2 = find(markerpos(:,1)==repmat(c(1),size(markerpos,1),1));
sel3 = find(markerpos(:,3)==repmat(c(3),size(markerpos,1),1));
end
for k = 1:numel(updatepanel)
update = updatepanel(k);
if update==1
subplot(h1);
imagesc(x, z, squeeze(dat(:,yi,:))'); set(gca, 'ydir', 'normal')
axis equal; axis tight;
xlabel('i'); ylabel('k');
caxis([cmin cmax]);
if showcrosshair
crosshair([x(xi) z(zi)], 'color', 'yellow');
end
if showmarkers && numel(sel1)>0
hold on;
for kk = 1:numel(sel1)
plot(markerpos(sel1(kk),1), markerpos(sel1(kk),3), 'marker', '.', 'color', markercolor{sel1(kk)});
end
hold off;
end
end
if update==2
subplot(h2);
imagesc(y, z, squeeze(dat(xi,:,:))'); set(gca, 'ydir', 'normal')
axis equal; axis tight;
xlabel('j'); ylabel('k');
caxis([cmin cmax]);
if showcrosshair
crosshair([y(yi) z(zi)], 'color', 'yellow');
end
if showmarkers && numel(sel2)>0
hold on;
for kk = 1:numel(sel2)
plot(markerpos(sel2(kk),2), markerpos(sel2(kk),3), 'marker', '.', 'color', markercolor{sel2(kk)});
end
hold off;
end
end
if update==3
subplot(h3);
imagesc(x, y, squeeze(dat(:,:,zi))'); set(gca, 'ydir', 'normal')
axis equal; axis tight;
xlabel('i'); ylabel('j');
caxis([cmin cmax]);
if showcrosshair
crosshair([x(xi) y(yi)], 'color', 'yellow');
end
if showmarkers && numel(sel3)>0
hold on;
for kk = 1:numel(sel3)
plot(markerpos(sel3(kk),1), markerpos(sel3(kk),2), 'marker', '.', 'color', markercolor{sel3(kk)});
end
hold off;
end
end
end
colormap gray
h = gca;
|
github
|
philippboehmsturm/antx-master
|
ft_qualitycheck.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_qualitycheck.m
| 26,394 |
utf_8
|
9352272d7862a9702b7cf92f071cf8c0
|
function [varargout] = ft_qualitycheck(cfg)
% FT_QUALITYCHECK facilitates quality inspection of a dataset. 1) The data is
% analyzed, quantified, and stored in a .mat file in a timelock- and
% freq- like fashion. 2) The quantifications are visualized and exported to
% a .PNG and .PDF file.
%
% In case the data is MEG data recorded with a CTF system, the output contains
% the headpositions.
%
% Use as:
% [info, timelock, freq, summary, headpos] = ft_qualitycheck(cfg)
%
% The configuration should contain:
% cfg.dataset = a string (e.g. 'dataset.ds')
%
% The following parameters can be used:
% cfg.analyze = 'yes' or 'no' to analyze the dataset (default = 'yes')
% cfg.savemat = 'yes' or 'no' to save the analysis (default = 'yes')
% cfg.matfile = a string (e.g. 'previousoutput.mat'), preferably in combination
% with analyze = 'no'
% cfg.visualize = 'yes' or 'no' to visualize the analysis (default = 'yes')
% cfg.saveplot = 'yes' or 'no' to save the visualization (default = 'yes')
% Copyright (C) 2010-2011, Arjen Stolk, Bram Daams, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
ft_defaults
% record start time and total processing time
ftFuncTimer = tic();
ftFuncClock = clock();
% defaults
if ~isfield(cfg,'analyze'), cfg.analyze = 'yes'; end
if ~isfield(cfg,'savemat'), cfg.savemat = 'yes'; end
if ~isfield(cfg,'matfile'), cfg.matfile = []; end
if ~isfield(cfg,'visualize'), cfg.visualize = 'yes'; end
if ~isfield(cfg,'saveplot'), cfg.saveplot = 'yes'; end
%% ANALYSIS
if strcmp(cfg.analyze,'yes')
tic
% checks
cfg = ft_checkconfig(cfg, 'dataset2files', 'yes'); % translate into datafile+headerfile
% these will be replaced by more appropriate values
info.datasetname = 'unknown';
info.starttime = 'unknown';
info.startdate = 'unknown';
info.stoptime = 'unknown';
info.stopdate = 'unknown';
% the exportname is also used in the cron job
exportname = qualitycheck_exportname(cfg.dataset);
[iseeg, ismeg, isctf, fltp] = filetyper(cfg.dataset);
if isctf
try
% update the info fields
info = read_ctf_hist(cfg.dataset);
end
end
% add info
info.event = ft_read_event(cfg.dataset);
info.hdr = ft_read_header(cfg.dataset);
info.filetype = fltp;
% trial definition
cfgdef = [];
cfgdef.dataset = cfg.dataset;
cfgdef.trialdef.triallength = 10;
%cfgdef.trialdef.ntrials = 3;
cfgdef.continuous = 'yes';
cfgdef = ft_definetrial(cfgdef);
ntrials = size(cfgdef.trl,1)-1; % remove last trial
timeunit = cfgdef.trialdef.triallength;
% channelselection for jump detection (all) and for FFT (brain)
if ismeg
allchans = ft_channelselection({'MEG','MEGREF'}, info.hdr.label);
chans = ft_channelselection('MEG', info.hdr.label); % brain
allchanindx = match_str(info.hdr.label, allchans);
chanindx = match_str(chans, allchans);
jumpthreshold = 1e-10;
elseif iseeg
allchans = ft_channelselection('EEG', info.hdr.label);
chans = allchans; % brain
allchanindx = match_str(info.hdr.label, allchans);
chanindx = match_str(chans, allchans);
jumpthreshold = 1e4;
end
% find headcoil channels
if isctf % this fails for older CTF data sets
try
Nx = strmatch('HLC0011', info.hdr.label); % x nasion coil
Ny = strmatch('HLC0012', info.hdr.label); % y nasion
Nz = strmatch('HLC0013', info.hdr.label); % z nasion
Lx = strmatch('HLC0021', info.hdr.label); % x left coil
Ly = strmatch('HLC0022', info.hdr.label); % y left
Lz = strmatch('HLC0023', info.hdr.label); % z left
Rx = strmatch('HLC0031', info.hdr.label); % x right coil
Ry = strmatch('HLC0032', info.hdr.label); % y right
Rz = strmatch('HLC0033', info.hdr.label); % z right
hasheadpos = true;
headpos.dimord = 'chan_time';
headpos.time = [timeunit-timeunit/2:timeunit:timeunit*ntrials-timeunit/2];
headpos.label = {'Nx';'Ny';'Nz';'Lx';'Ly';'Lz';'Rx';'Ry';'Rz'};
headpos.avg = NaN(length(headpos.label), ntrials);
headpos.grad = info.hdr.grad;
end % try
end % if
% analysis settings
cfgredef = [];
cfgredef.length = 1;
cfgredef.overlap = 0;
cfgfreq = [];
cfgfreq.output = 'pow';
cfgfreq.channel = allchans;
cfgfreq.method = 'mtmfft';
cfgfreq.taper = 'hanning';
cfgfreq.keeptrials = 'no';
cfgfreq.foilim = [0 min(info.hdr.Fs/2, 400)];
% output variables
timelock.dimord = 'chan_time';
timelock.label = allchans;
timelock.time = [timeunit-timeunit/2:timeunit:timeunit*ntrials-timeunit/2];
timelock.avg = NaN(length(allchans), ntrials); % updated in loop
timelock.median = NaN(length(allchans), ntrials); % updated in loop
timelock.jumps = NaN(length(allchans), ntrials); % updated in loop
timelock.range = NaN(length(allchans), ntrials); % updated in loop
timelock.min = NaN(length(allchans), ntrials); % updated in loop
timelock.max = NaN(length(allchans), ntrials); % updated in loop
freq.dimord = 'chan_freq_time';
freq.label = allchans;
freq.freq = [cfgfreq.foilim(1):cfgfreq.foilim(2)];
freq.time = [timeunit-timeunit/2:timeunit:timeunit*ntrials-timeunit/2];
freq.powspctrm = NaN(length(allchans), length(freq.freq), ntrials); % updated in loop
summary.dimord = 'chan_time';
summary.time = [timeunit-timeunit/2:timeunit:timeunit*ntrials-timeunit/2];
summary.label = {'Mean';'Median';'Min';'Max';'Range';'HmotionN';'HmotionL';'HmotionR';'LowFreqPower';'LineFreqPower';'Jumps'};
summary.avg = NaN(length(summary.label), ntrials); % updated in loop
% try add gradiometer info
try
timelock.grad = info.hdr.grad;
freq.grad = info.hdr.grad;
summary.grad = info.hdr.grad;
end
% process trial by trial
for t = 1:ntrials
fprintf('analyzing trial %s of %s \n', num2str(t), num2str(ntrials));
% preprocess
cfgpreproc = cfgdef;
cfgpreproc.trl = cfgdef.trl(t,:);
data = ft_preprocessing(cfgpreproc); clear cfgpreproc;
% determine headposition
if isctf && hasheadpos
headpos.avg(1,t) = mean(data.trial{1,1}(Nx,:) * 100); % meter to cm
headpos.avg(2,t) = mean(data.trial{1,1}(Ny,:) * 100);
headpos.avg(3,t) = mean(data.trial{1,1}(Nz,:) * 100);
headpos.avg(4,t) = mean(data.trial{1,1}(Lx,:) * 100);
headpos.avg(5,t) = mean(data.trial{1,1}(Ly,:) * 100);
headpos.avg(6,t) = mean(data.trial{1,1}(Lz,:) * 100);
headpos.avg(7,t) = mean(data.trial{1,1}(Rx,:) * 100);
headpos.avg(8,t) = mean(data.trial{1,1}(Ry,:) * 100);
headpos.avg(9,t) = mean(data.trial{1,1}(Rz,:) * 100);
end
% update values
timelock.avg(:,t) = mean(data.trial{1}(allchanindx,:),2);
timelock.median(:,t) = median(data.trial{1}(allchanindx,:),2);
timelock.range(:,t) = max(data.trial{1}(allchanindx,:),[],2) - min(data.trial{1}(allchanindx,:),[],2);
timelock.min(:,t) = min(data.trial{1}(allchanindx,:),[],2);
timelock.max(:,t) = max(data.trial{1}(allchanindx,:),[],2);
% detect jumps
for c = 1:size(data.trial{1}(allchanindx,:),1)
timelock.jumps(c,t) = length(find(diff(data.trial{1,1}(allchanindx(c),:)) > jumpthreshold));
end
% FFT and noise estimation
redef = ft_redefinetrial(cfgredef, data); clear data;
FFT = ft_freqanalysis(cfgfreq, redef); clear redef;
freq.powspctrm(:,:,t) = FFT.powspctrm;
summary.avg(9,t) = mean(mean(findpower(0, 2, FFT, chanindx))); % Low Freq Power
summary.avg(10,t) = mean(mean(findpower(49, 51, FFT, chanindx))); clear FFT; % Line Freq Power
toc
end % end of trial loop
% determine headmotion: distance from initial trial (in cm)
if isctf && hasheadpos
summary.avg(6,:) = sqrt(sum((headpos.avg(1:3,:)-repmat(headpos.avg(1:3,1),1,size(headpos.avg,2))).^2,1)); % N
summary.avg(7,:) = sqrt(sum((headpos.avg(4:6,:)-repmat(headpos.avg(4:6,1),1,size(headpos.avg,2))).^2,1)); % L
summary.avg(8,:) = sqrt(sum((headpos.avg(7:9,:)-repmat(headpos.avg(7:9,1),1,size(headpos.avg,2))).^2,1)); % R
end
% summarize/mean and store variables of brain info only
summary.avg(1,:) = mean(timelock.avg(chanindx,:),1);
summary.avg(2,:) = mean(timelock.median(chanindx,:),1);
summary.avg(3,:) = mean(timelock.min(chanindx,:),1);
summary.avg(4,:) = mean(timelock.max(chanindx,:),1);
summary.avg(5,:) = mean(timelock.range(chanindx,:),1);
summary.avg(11,:) = mean(timelock.jumps(chanindx,:),1);
% add the version details of this function call to the configuration
cfg.version.name = mfilename('fullpath');
cfg.version.id = '$Id: ft_qualitycheck.m 3710 2011-06-16 14:04:19Z eelspa $';
cfg.callinfo.matlab = version();
% add information about the function call to the configuration
cfg.callinfo.proctime = toc(ftFuncTimer);
cfg.callinfo.calltime = ftFuncClock;
cfg.callinfo.user = getusername(); % Matlab version used
% add the cfg to the output variables
timelock.cfg = cfg;
freq.cfg = cfg;
summary.cfg = cfg;
% save to .mat
if strcmp(cfg.savemat, 'yes')
if isctf && hasheadpos
headpos.cfg = cfg;
save(exportname, 'info','timelock','freq','summary','headpos');
else
save(exportname, 'info','timelock','freq','summary');
end
end
end % end of analysis
%% VISUALIZATION
if strcmp(cfg.visualize, 'yes')
% load data
if strcmp(cfg.analyze, 'no')
if ~isempty(cfg.matfile)
exportname = cfg.matfile;
else
exportname = qualitycheck_exportname(cfg.dataset);
end
fprintf('loading %s \n', exportname);
load(exportname);
end
% determine number of 1-hour plots to be made
nplots = ceil(length(freq.time)/(3600/10));
% create GUI-like figure(s)
for p = 1:nplots
fprintf('visualizing %s of %s \n', num2str(p), num2str(nplots));
toi = [p*3600-3595 p*3600-5]; % select 1-hour chunks
if exist('headpos','var')
temp_timelock = ft_selectdata(timelock, 'toilim', toi);
temp_freq = ft_selectdata(freq, 'toilim', toi);
temp_summary = ft_selectdata(summary, 'toilim', toi);
temp_headpos = ft_selectdata(headpos, 'toilim', toi);
draw_figure(info, temp_timelock, temp_freq, temp_summary, temp_headpos, toi);
clear temp_timelock; clear temp_freq; clear temp_summary; clear temp_headpos; clear toi;
else
temp_timelock = ft_selectdata(timelock, 'toilim', toi);
temp_freq = ft_selectdata(freq, 'toilim', toi);
temp_summary = ft_selectdata(summary, 'toilim', toi);
draw_figure(info, temp_timelock, temp_freq, temp_summary, toi);
clear temp_timelock; clear temp_freq; clear temp_summary; clear toi;
end
% export to .PNG and .PDF
if strcmp(cfg.saveplot, 'yes')
[pathstr,name,extr,versn] = fileparts(exportname);
if p == 1
exportfilename = name;
else
exportfilename = strcat(name,'_pt',num2str(p));
end
fprintf('exporting %s of %s \n', num2str(p), num2str(nplots));
set(gcf, 'PaperType', 'a4');
print(gcf, '-dpng', strcat(exportfilename,'.png'));
orient landscape;
print(gcf, '-dpdf', strcat(exportfilename,'.pdf'));
close
end
end % end of nplots
end % end of visualization
%% VARARGOUT
if nargout>0
mOutputArgs{1} = info;
mOutputArgs{2} = timelock;
mOutputArgs{3} = freq;
mOutputArgs{4} = summary;
try
mOutputArgs{5} = headpos;
end
[varargout{1:nargout}] = mOutputArgs{:};
clearvars -except varargout
else
clear
end
%%%%%%%%%%%%%%%%%%%%%%%% SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%
function [x] = clipat(x, v, v2)
v = [v v2]; % clip between value v and v2
if length(v) == 1
x(find(x>v)) = v;
elseif length(v) == 2
x(find(x<v(1))) = v(1);
x(find(x>v(2))) = v(2);
end
%%%%%%%%%%%%%%%%%%%%%%%% SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%
function [iseeg, ismeg, isctf, fltp] = filetyper(dataset)
fltp = ft_filetype(dataset);
iseeg = ft_filetype(dataset,'brainvision_eeg') | ...
ft_filetype(dataset,'ns_eeg') | ...
ft_filetype(dataset,'bci2000_dat') | ...
ft_filetype(dataset,'neuroprax_eeg') | ...
ft_filetype(dataset,'egi_sbin') | ...
ft_filetype(dataset,'biosemi_bdf');
ismeg = ft_filetype(dataset,'ctf_ds') | ...
ft_filetype(dataset,'4d') | ...
ft_filetype(dataset,'neuromag_fif') | ...
ft_filetype(dataset,'itab_raw');
isctf = ft_filetype(dataset, 'ctf_ds');
if ~ismeg && ~iseeg % if none found, try less strict checks
[p, f, ext] = fileparts(dataset);
if strcmp(ext, '.eeg')
fltp = 'brainvision_eeg';
iseeg = 1;
elseif strcmp(ext, '.bdf')
fltp = 'biosemi_bdf';
iseeg = 1;
elseif strcmp(ext, '.ds')
fltp = 'ctf_ds';
ismeg = 1;
else % otherwise use eeg settings for stability reasons
iseeg = 1;
end
end
%%%%%%%%%%%%%%%%%%%%%%%% SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%
function [power, freq] = findpower(low, high, freqinput, chans)
% replace value with the index of the nearest bin
xmin = nearest(getsubfield(freqinput, 'freq'), low);
xmax = nearest(getsubfield(freqinput, 'freq'), high);
% select the freq range
power = freqinput.powspctrm(chans, xmin:xmax);
freq = freqinput.freq(:, xmin:xmax);
%%%%%%%%%%%%%%%%%%%%%%%% SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%
function draw_figure(varargin)
% deal with input
if nargin == 6
info = varargin{1};
timelock = varargin{2};
freq = varargin{3};
summary = varargin{4};
headpos = varargin{5};
toi = varargin{6};
elseif nargin == 5
info = varargin{1};
timelock = varargin{2};
freq = varargin{3};
summary = varargin{4};
toi = varargin{5};
end
% determine whether it is EEG or MEG
[iseeg, ismeg, isctf, fltp] = filetyper(timelock.cfg.dataset);
if ismeg
scaling = 1e15; % assuming data is in T and needs to become fT
powscaling = scaling^2;
ylab = 'fT';
elseif iseeg
scaling = 1e0; % assuming data is in muV already
powscaling = scaling^2;
ylab = '\muV';
end
% PARENT FIGURE
h.MainFigure = figure(...
'MenuBar','none',...
'Name','ft_qualitycheck',...
'Units','normalized',...
'color','white',...
'Position',[0.01 0.01 .99 .99]); % nearly fullscreen
if strcmp(info.startdate,'unknown')
tmp = 'unknown';
else
[d,w] = weekday(info.startdate);
tmp = [w ' ' info.startdate];
end
h.MainText = uicontrol(...
'Parent',h.MainFigure,...
'Style','text',...
'Units','normalized',...
'FontSize',10,...
'String',tmp,...
'Backgroundcolor','white',...
'Position',[.06 .96 .15 .02]);
h.MainText2 = uicontrol(...
'Parent',h.MainFigure,...
'Style','text',...
'Units','normalized',...
'FontSize',10,...
'String','Jump artefacts',...
'Backgroundcolor','white',...
'Position',[.08 .46 .12 .02]);
h.MainText3 = uicontrol(...
'Parent',h.MainFigure,...
'Style','text',...
'Units','normalized',...
'FontSize',10,...
'String','Mean powerspectrum',...
'Backgroundcolor','white',...
'Position',[.4 .3 .15 .02]);
h.MainText4 = uicontrol(...
'Parent',h.MainFigure,...
'Style','text',...
'Units','normalized',...
'FontSize',10,...
'String','Timecourses',...
'Backgroundcolor','white',...
'Position',[.5 .96 .11 .02]);
h.MainText5 = uicontrol(...
'Parent',h.MainFigure,...
'Style','text',...
'Units','normalized',...
'FontSize',10,...
'String','Events',...
'Backgroundcolor','white',...
'Position',[.81 .3 .06 .02]);
% HEADMOTION PANEL
h.HmotionPanel = uipanel(...
'Parent',h.MainFigure,...
'Units','normalized',...
'Backgroundcolor','white',...
'Position',[.01 .5 .25 .47]);
h.DataText = uicontrol(...
'Parent',h.HmotionPanel,...
'Style','text',...
'Units','normalized',...
'FontSize',10,...
'String',info.datasetname,...
'Backgroundcolor','white',...
'Position',[.01 .85 .99 .1]);
h.TimeText = uicontrol(...
'Parent',h.HmotionPanel,...
'Style','text',...
'Units','normalized',...
'FontSize',10,...
'String',[info.starttime ' - ' info.stoptime],...
'Backgroundcolor','white',...
'Position',[.01 .78 .99 .1]);
if ismeg
allchans = ft_senslabel('ctf275');
misschans = setdiff(ft_channelselection('MEG', info.hdr.label), allchans);
nchans = num2str(size(ft_channelselection('MEG', info.hdr.label),1));
else
misschans = '';
nchans = num2str(size(ft_channelselection('EEG', info.hdr.label),1));
end
h.DataText2 = uicontrol(...
'Parent',h.HmotionPanel,...
'Style','text',...
'Units','normalized',...
'FontSize',10,...
'String',[fltp ', fs: ' num2str(info.hdr.Fs) ', nchans: ' nchans],...
'Backgroundcolor','white',...
'Position',[.01 .71 .99 .1]);
h.DataText3 = uicontrol(...
'Parent',h.HmotionPanel,...
'Style','text',...
'Units','normalized',...
'FontSize',10,...
'String',['missing chans: ' misschans'],...
'Backgroundcolor','white',...
'Position',[.01 .64 .99 .1]);
% boxplot headmotion (*10; cm-> mm) per coil
if exist('headpos','var')
h.HmotionAxes = axes(...
'Parent',h.HmotionPanel,...
'Units','normalized',...
'color','white',...
'Position',[.05 .08 .9 .52]);
hmotions = ([summary.avg(8,:)' summary.avg(7,:)' summary.avg(6,:)'])*10;
boxplot(h.HmotionAxes, hmotions, 'orientation', 'horizontal', 'notch', 'on');
set(h.HmotionAxes,'YTick',[1:3]);
set(h.HmotionAxes,'YTickLabel',{'R','L','N'});
xlim(h.HmotionAxes, [0 10]);
xlabel(h.HmotionAxes, 'Headmotion from start [mm]');
end
% TIMECOURSE PANEL
h.SignalPanel = uipanel(...
'Parent',h.MainFigure,...
'Units','normalized',...
'Backgroundcolor','white',...
'Position',[.28 .34 .71 .63]);
h.SignalAxes = axes(...
'Parent',h.SignalPanel,...
'Units','normalized',...
'color','white',...
'Position',[.08 .36 .89 .3]);
h.LinenoiseAxes = axes(...
'Parent',h.SignalPanel,...
'Units','normalized',...
'color','white',...
'Position',[.08 .23 .89 .1]);
h.LowfreqnoiseAxes = axes(...
'Parent',h.SignalPanel,...
'Units','normalized',...
'color','white',...
'Position',[.08 .1 .89 .1]);
% plot hmotion timecourses per coil (*10; cm-> mm)
if exist('headpos','var')
h.HmotionTimecourseAxes = axes(...
'Parent',h.SignalPanel,...
'Units','normalized',...
'color','white',...
'Position',[.08 .73 .89 .22]);
plot(h.HmotionTimecourseAxes, summary.time, clipat(summary.avg(6,:)*10, 0, 10), ...
summary.time, clipat(summary.avg(7,:)*10, 0, 10), ...
summary.time, clipat(summary.avg(8,:)*10, 0, 10), 'LineWidth',2);
ylim(h.HmotionTimecourseAxes,[0 10]);
ylabel(h.HmotionTimecourseAxes, 'Coil distance [mm]');
xlim(h.HmotionTimecourseAxes,[toi]);
grid(h.HmotionTimecourseAxes,'on');
legend(h.HmotionTimecourseAxes, 'N','L','R');
end
% plot mean and range of the raw signal
plot(h.SignalAxes, summary.time, summary.avg(5,:)*scaling, summary.time, summary.avg(1,:)*scaling, 'LineWidth', 2);
set(h.SignalAxes,'Nextplot','add');
plot(h.SignalAxes, summary.time, summary.avg(3,:)*scaling, summary.time, summary.avg(4,:)*scaling, 'LineWidth', 1, 'Color', [255/255 127/255 39/255]);
grid(h.SignalAxes,'on');
ylabel(h.SignalAxes, ['Amplitude [' ylab ']']);
xlim(h.SignalAxes,[toi]);
legend(h.SignalAxes,'Range','Mean','Min','Max');
set(h.SignalAxes,'XTickLabel','');
% plot linenoise
semilogy(h.LinenoiseAxes, summary.time, clipat(summary.avg(10,:)*powscaling, 1e2, 1e4), 'LineWidth',2);
grid(h.LinenoiseAxes,'on');
legend(h.LinenoiseAxes, ['LineFreq [' ylab '^2/Hz]']);
set(h.LinenoiseAxes,'XTickLabel','');
xlim(h.LinenoiseAxes,[toi]);
ylim(h.LinenoiseAxes,[1e2 1e4]); % before april 28th this was 1e0 - 1e3
% plot lowfreqnoise
semilogy(h.LowfreqnoiseAxes, summary.time, clipat(summary.avg(9,:)*powscaling, 1e10, 1e12), 'LineWidth',2);
grid(h.LowfreqnoiseAxes,'on');
xlim(h.LowfreqnoiseAxes,[toi]);
ylim(h.LowfreqnoiseAxes,[1e10 1e12]);
legend(h.LowfreqnoiseAxes, ['LowFreq [' ylab '^2/Hz]']);
xlabel(h.LowfreqnoiseAxes, 'Time [seconds]'); % before april 28th this was 1e0 - 1e10
% EVENT PANEL
h.EventPanel = uipanel(...
'Parent',h.MainFigure,...
'Units','normalized',...
'Backgroundcolor','white',...
'Position',[.7 .01 .29 .3]);
% event details
[a,b,c] = unique({info.event.type});
eventtypes = {};
eventtriggers = {};
eventvalues = {};
for j=1:length(a)
eventtypes{j,1} = a{j};
eventtriggers{j,1} = sum(c==j);
eventvalues{j,1} = length(unique([info.event(c==j).value]));
end
if isempty(eventtypes)
eventtypes{1,1} = 'no triggers found';
end
h.EventText = uicontrol(...
'Parent',h.EventPanel,...
'Style','text',...
'Units','normalized',...
'FontSize',10,...
'String',['Types'; ' '; eventtypes],...
'Backgroundcolor','white',...
'Position',[.05 .05 .4 .85]);
h.EventText2 = uicontrol(...
'Parent',h.EventPanel,...
'Style','text',...
'Units','normalized',...
'FontSize',10,...
'String',['Triggers'; ' '; eventtriggers],...
'Backgroundcolor','white',...
'Position',[.55 .05 .2 .85]);
h.EventText3 = uicontrol(...
'Parent',h.EventPanel,...
'Style','text',...
'Units','normalized',...
'FontSize',10,...
'String',['Values'; ' '; eventvalues],...
'Backgroundcolor','white',...
'Position',[.8 .05 .15 .85]);
% POWERSPECTRUM PANEL
h.SpectrumPanel = uipanel(...
'Parent',h.MainFigure,...
'Units','normalized',...
'Backgroundcolor','white',...
'Position',[.28 .01 .4 .3]);
h.SpectrumAxes = axes(...
'Parent',h.SpectrumPanel,...
'Units','normalized',...
'color','white',...
'Position',[.15 .2 .8 .7]);
% plot powerspectrum
loglog(h.SpectrumAxes, freq.freq, squeeze(mean(mean(freq.powspctrm,1),3))*powscaling,'r','LineWidth',2);
xlabel(h.SpectrumAxes, 'Frequency [Hz]');
ylabel(h.SpectrumAxes, ['Power [' ylab '^2/Hz]']);
% ARTEFACT PANEL
h.JumpPanel = uipanel(...
'Parent',h.MainFigure,...
'Units','normalized',...
'Backgroundcolor','white',...
'Position',[.01 .01 .25 .46]);
% jump details
jumpchans = {};
jumpcounts = {};
[jumps,i] = find(timelock.jumps>0); % find all jumps
[a,b,c] = unique(jumps);
for j=1:length(a)
jumpchans{j,1} = timelock.label{a(j)};
jumpcounts{j,1} = sum(c==j);
end
if isempty(jumpchans)
jumpchans{1,1} = 'no jumps detected';
end
h.JumpText = uicontrol(...
'Parent',h.JumpPanel,...
'Style','text',...
'Units','normalized',...
'FontSize',10,...
'String',[jumpchans],...
'Backgroundcolor','white',...
'Position',[.15 .5 .25 .4]);
h.JumpText2 = uicontrol(...
'Parent',h.JumpPanel,...
'Style','text',...
'Units','normalized',...
'FontSize',10,...
'String',[jumpcounts],...
'Backgroundcolor','white',...
'Position',[.65 .5 .2 .4]);
% plot jumps on the dewar sensors
if ismeg
h.TopoMEG = axes(...
'Parent',h.JumpPanel,...
'color','white',...
'Units','normalized',...
'Position',[0.4 0.05 0.55 0.4]);
MEGchans = ft_channelselection('MEG', timelock.label);
MEGchanindx = match_str(timelock.label, MEGchans);
cfgtopo = [];
cfgtopo.marker = 'off';
cfgtopo.colorbar = 'no';
cfgtopo.comment = 'no';
cfgtopo.style = 'blank';
cfgtopo.layout = ft_prepare_layout(timelock);
cfgtopo.highlight = 'on';
cfgtopo.highlightsymbol = '.';
cfgtopo.highlightsize = [14];
cfgtopo.highlightchannel = [find(sum(timelock.jumps(MEGchanindx,:),2)>0)];
data.label = MEGchans;
data.powspctrm = sum(timelock.jumps(MEGchanindx,:),2);
data.dimord = 'chan_freq';
data.freq = 1;
axes(h.TopoMEG);
ft_topoplotTFR(cfgtopo, data); clear data;
end
|
github
|
philippboehmsturm/antx-master
|
ft_denoise_pca.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_denoise_pca.m
| 16,221 |
utf_8
|
ca602a310a7e0a8f6d90d988eef7ee81
|
function [data, pca, stdpre, stdpst] = ft_denoise_pca(cfg, varargin)
% DENOISE_PCA performs a pca on specified reference channels and subtracts
% the projection of the data of interest onto this orthogonal basis from
% the data of interest. This is the algorithm which is applied by 4D to
% compute noise cancellation weights on a dataset of interest.
%
% Use as
% [data] = ft_denoise_pca(cfg, data) or [data] = ft_denoise_pca(cfg, data, refdata)
%
% The configuration should be according to
% cfg.refchannel = the channels used as reference signal (default = 'MEGREF')
% cfg.channel = the channels to be denoised (default = 'MEG')
% cfg.truncate = optional truncation of the singular value spectrum
% cfg.zscore = standardise reference data prior to PCA (default = 'no')
% if cfg.truncate is integer n > 1, n will be the number of singular values kept.
% if 0 < cfg.truncate < 1, the singular value spectrum will be thresholded at the
% fraction cfg.truncate of the largest singular value.
% (default = 'no');
% Copyright (c) 2008-2009, Jan-Mathijs Schoffelen, CCNi Glasgow
% Copyright (c) 2010, Jan-Mathijs Schoffelen, DCCN Nijmegen
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_denoise_pca.m 3710 2011-06-16 14:04:19Z eelspa $
ft_defaults
% record start time and total processing time
ftFuncTimer = tic();
ftFuncClock = clock();
cfg = ft_checkconfig(cfg, 'trackconfig', 'on');
cfg = ft_checkconfig(cfg, 'renamed', {'blc', 'demean'});
if ~isfield(cfg, 'truncate'), cfg.truncate = 'no'; end;
if ~isfield(cfg, 'channel'), cfg.channel = 'MEG'; end;
if ~isfield(cfg, 'refchannel'), cfg.refchannel = 'MEGREF'; end;
if ~isfield(cfg, 'trials'), cfg.trials = 'all'; end;
if ~isfield(cfg, 'zscore'), cfg.zscore = 'no'; end;
if ~isfield(cfg, 'demean'), cfg.demean = 'yes'; end;
if ~isfield(cfg, 'pertrial'), cfg.pertrial = 'no'; end
if strcmp(cfg.pertrial, 'yes'),
tmpcfg = cfg;
tmpcfg.pertrial = 'no';
tmp = cell(numel(varargin{1}.trial));
for k = 1:numel(varargin{1}.trial)
tmpcfg.trials = k;
tmp{k,1} = ft_denoise_pca(tmpcfg, varargin{:});
end
data = ft_appenddata([], tmp{:});
return;
end
computeweights = ~isfield(cfg, 'pca');
%overrule insensible user specifications
if ~strcmp(cfg.demean, 'yes'),
cfg.demean = 'yes';
end
if length(varargin)==1,
data = varargin{1};
megchan = ft_channelselection(cfg.channel, data.label);
refchan = ft_channelselection(cfg.refchannel, data.label);
%split data into data and refdata
tmpcfg = [];
tmpcfg.channel = refchan;
refdata = ft_preprocessing(tmpcfg, data);
tmpcfg.channel = megchan;
data = ft_preprocessing(tmpcfg, data);
else
data = varargin{1};
refdata = varargin{2};
megchan = ft_channelselection(cfg.channel, data.label);
refchan = ft_channelselection(cfg.refchannel, refdata.label);
%split data into data and refdata
tmpcfg = [];
tmpcfg.channel = refchan;
refdata = ft_preprocessing(tmpcfg, refdata);
tmpcfg.channel = megchan;
data = ft_preprocessing(tmpcfg, data);
%FIXME do compatibility check on data vs refdata with respect to dimensions (time-trials)
end
% select trials of interest
if ~isfield(cfg, 'trials'), cfg.trials = 'all'; end % set the default
if ~strcmp(cfg.trials, 'all')
fprintf('selecting %d trials\n', length(cfg.trials));
data = ft_selectdata(data, 'rpt', cfg.trials);
refdata = ft_selectdata(refdata, 'rpt', cfg.trials);
end
refchan = ft_channelselection(cfg.refchannel, refdata.label);
refindx = match_str(refdata.label, refchan);
megchan = ft_channelselection(cfg.channel, data.label);
megindx = match_str(data.label, megchan);
if ~computeweights
%check whether the weight table contains the specified references
%ensure the ordering of the meg-data to be consistent with the weights
%ensure the ordering of the ref-data to be consistent with the weights
[i1,i2] = match_str(refchan, cfg.pca.reflabel);
[i3,i4] = match_str(megchan, cfg.pca.label);
if length(i2)~=length(cfg.pca.reflabel),
error('you specified fewer references to use as there are in the precomputed weight table');
end
refindx = refindx(i1);
megindx = megindx(i3);
cfg.pca.w = cfg.pca.w(i4,i2);
cfg.pca.label = cfg.pca.label(i4);
cfg.pca.reflabel= cfg.pca.reflabel(i2);
if isfield(cfg.pca, 'rotmat'),
cfg.pca = rmfield(cfg.pca, 'rotmat'); %dont know
end
else
%do nothing
end
nmeg = length(megindx);
nref = length(refindx);
if ischar(cfg.truncate) && strcmp(cfg.truncate, 'no'),
cfg.truncate = length(refindx);
elseif ischar(cfg.truncate) || (cfg.truncate>1 && cfg.truncate/round(cfg.truncate)~=1) || ...
cfg.truncate>length(refindx),
error('cfg.truncate should be either ''no'', an integer number <= the number of references, or a number between 0 and 1');
%FIXME the default truncation applied by 4D is 1x10^-8
end
ntrl = length(data.trial);
nchan = length(data.label);
nsmp = cellfun('size', data.trial, 2);
%compute and remove mean from data
if strcmp(cfg.demean, 'yes'),
m = cellmean(data.trial, 2);
data.trial = cellvecadd(data.trial, -m);
m = cellmean(refdata.trial, 2);
refdata.trial = cellvecadd(refdata.trial, -m);
end
%compute std of data before
stdpre = cellstd(data.trial, 2);
if computeweights,
%zscore
if strcmp(cfg.zscore, 'yes'),
[refdata.trial, sdref] = cellzscore(refdata.trial, 2, 0); %forced demeaned already
else
sdref = ones(nref,1);
end
%compute covariance of refchannels and do svd
crefdat = cellcov(refdata.trial, [], 2, 0);
[u,s,v] = svd(crefdat);
%determine the truncation and rotation
if cfg.truncate<1
%keep all singular vectors with singular values >= cfg.truncate*s(1,1)
s1 = s./max(s(:));
keep = find(diag(s1)>cfg.truncate);
else
keep = 1:cfg.truncate;
end
rotmat = u(:, keep)';
%rotate the refdata
refdata.trial = cellfun(@mtimes, repmat({rotmat}, 1, ntrl), refdata.trial, 'UniformOutput', 0);
%project megdata onto the orthogonal basis
nom = cellcov(data.trial, refdata.trial, 2, 0);
denom = cellcov(refdata.trial, [], 2, 0);
rw = (pinv(denom)*nom')';
%subtract projected data
for k = 1:ntrl
data.trial{k} = data.trial{k} - rw*refdata.trial{k};
end
%rotate back and 'unscale'
pca.w = rw*rotmat*diag(1./sdref);
pca.label = data.label;
pca.reflabel = refdata.label;
pca.rotmat = rotmat;
cfg.pca = pca;
else
fprintf('applying precomputed weights to the data\n');
pca = cfg.pca;
for k = 1:ntrl
data.trial{k} = data.trial{k} - pca.w*refdata.trial{k};
end
end
%compute std of data after
stdpst = cellstd(data.trial, 2);
%demean
if strcmp(cfg.demean, 'yes'),
m = cellmean(data.trial, 2);
data.trial = cellvecadd(data.trial, -m);
end
%apply weights to the gradiometer-array
if isfield(data, 'grad')
montage = [];
labelnew = pca.label;
nlabelnew = length(labelnew);
%add columns of refchannels not yet present in labelnew
%[id, i1] = setdiff(pca.reflabel, labelnew);
%labelorg = [labelnew; pca.reflabel(sort(i1))];
labelorg = data.grad.label;
nlabelorg = length(labelorg);
%start with identity
montage.tra = eye(nlabelorg);
%subtract weights
[i1, i2] = match_str(labelorg, pca.reflabel);
[i3, i4] = match_str(labelorg, pca.label);
montage.tra(i3,i1) = montage.tra(i3,i1) - pca.w(i4,i2);
montage.labelorg = labelorg;
montage.labelnew = labelorg;
if isfield(data.grad, 'balance'),
mnt = fieldnames(data.grad.balance);
sel = strmatch('pca', mnt);
if isempty(sel),
sel = zeros(0,1);
end
bname = ['pca',num2str(length(sel)+1)];
else
bname = 'pca1';
end
data.grad = ft_apply_montage(data.grad, montage, 'keepunused', 'yes', 'balancename', bname);
% order the fields
fnames = fieldnames(data.grad.balance);
for k = 1:numel(fnames)
tmp(k) = isstruct(data.grad.balance.(fnames{k}));
end
[srt, ix] = sort(tmp,'descend');
data.grad.balance = orderfields(data.grad.balance, fnames(ix));
else
warning('weights have been applied to the data only, not to the sensors');
end
% get the output cfg
cfg = ft_checkconfig(cfg, 'trackconfig', 'off', 'checksize', 'yes');
% add the version details of this function call to the configuration
cfg.version.name = mfilename('fullpath');
cfg.version.id = '$Id: ft_denoise_pca.m 3710 2011-06-16 14:04:19Z eelspa $';
% add information about the Matlab version used to the configuration
cfg.callinfo.matlab = version();
% add information about the function call to the configuration
cfg.callinfo.proctime = toc(ftFuncTimer);
cfg.callinfo.calltime = ftFuncClock;
cfg.callinfo.user = getusername();
% remember the configuration details of the input data
cfg.previous = [];
for i=1:numel(varargin)
try, cfg.previous{i} = varargin{i}.cfg; end
end
%-----cellcov
function [c] = cellcov(x, y, dim, flag)
% [C] = CELLCOV(X, DIM) computes the covariance, across all cells in x along
% the dimension dim. When there are three inputs, covariance is computed between
% all cells in x and y
%
% X (and Y) should be linear cell-array(s) of matrices for which the size in at
% least one of the dimensions should be the same for all cells
if nargin==2,
flag = 1;
dim = y;
y = [];
elseif nargin==3,
flag = 1;
end
nx = size(x);
if ~iscell(x) || length(nx)>2 || all(nx>1),
error('incorrect input for cellmean');
end
if nargin==1,
scx1 = cellfun('size', x, 1);
scx2 = cellfun('size', x, 2);
if all(scx2==scx2(1)), dim = 2; %let second dimension prevail
elseif all(scx1==scx1(1)), dim = 1;
else error('no dimension to compute covariance for');
end
end
if flag,
mx = cellmean(x, 2);
x = cellvecadd(x, -mx);
if ~isempty(y),
my = cellmean(y, 2);
y = cellvecadd(y, -my);
end
end
nx = max(nx);
nsmp = cellfun('size', x, dim);
if isempty(y),
csmp = cellfun(@covc, x, repmat({dim},1,nx), 'UniformOutput', 0);
else
csmp = cellfun(@covc, x, y, repmat({dim},1,nx), 'UniformOutput', 0);
end
nc = size(csmp{1});
c = sum(reshape(cell2mat(csmp), [nc(1) nc(2) nx]), 3)./sum(nsmp);
function [c] = covc(x, y, dim)
if nargin==2,
dim = y;
y = x;
end
if dim==1,
c = x'*y;
elseif dim==2,
c = x*y';
end
%-----cellmean
function [m] = cellmean(x, dim)
% [M] = CELLMEAN(X, DIM) computes the mean, across all cells in x along
% the dimension dim.
%
% X should be an linear cell-array of matrices for which the size in at
% least one of the dimensions should be the same for all cells
nx = size(x);
if ~iscell(x) || length(nx)>2 || all(nx>1),
error('incorrect input for cellmean');
end
if nargin==1,
scx1 = cellfun('size', x, 1);
scx2 = cellfun('size', x, 2);
if all(scx2==scx2(1)), dim = 2; %let second dimension prevail
elseif all(scx1==scx1(1)), dim = 1;
else error('no dimension to compute mean for');
end
end
nx = max(nx);
nsmp = cellfun('size', x, dim);
ssmp = cellfun(@sum, x, repmat({dim},1,nx), 'UniformOutput', 0);
m = sum(cell2mat(ssmp), dim)./sum(nsmp);
%-----cellstd
function [sd] = cellstd(x, dim, flag)
% [M] = CELLSTD(X, DIM, FLAG) computes the standard deviation, across all cells in x along
% the dimension dim, normalising by the total number of samples
%
% X should be an linear cell-array of matrices for which the size in at
% least one of the dimensions should be the same for all cells. If flag==1, the mean will
% be subtracted first (default behaviour, but to save time on already demeaned data, it
% can be set to 0).
nx = size(x);
if ~iscell(x) || length(nx)>2 || all(nx>1),
error('incorrect input for cellstd');
end
if nargin<2,
scx1 = cellfun('size', x, 1);
scx2 = cellfun('size', x, 2);
if all(scx2==scx2(1)), dim = 2; %let second dimension prevail
elseif all(scx1==scx1(1)), dim = 1;
else error('no dimension to compute mean for');
end
elseif nargin==2,
flag = 1;
end
if flag,
m = cellmean(x, dim);
x = cellvecadd(x, -m);
end
nx = max(nx);
nsmp = cellfun('size', x, dim);
ssmp = cellfun(@sumsq, x, repmat({dim},1,nx), 'UniformOutput', 0);
sd = sqrt(sum(cell2mat(ssmp), dim)./sum(nsmp));
function [s] = sumsq(x, dim)
s = sum(x.^2, dim);
%-----cellvecadd
function [y] = cellvecadd(x, v)
% [Y]= CELLVECADD(X, V) - add vector to all rows or columns of each matrix
% in cell-array X
% check once and for all to save time
persistent bsxfun_exists;
if isempty(bsxfun_exists);
bsxfun_exists=(exist('bsxfun')==5);
if ~bsxfun_exists;
error('bsxfun not found.');
end
end
nx = size(x);
if ~iscell(x) || length(nx)>2 || all(nx>1),
error('incorrect input for cellmean');
end
if ~iscell(v),
v = repmat({v}, nx);
end
sx1 = cellfun('size', x, 1);
sx2 = cellfun('size', x, 2);
sv1 = cellfun('size', v, 1);
sv2 = cellfun('size', v, 2);
if all(sx1==sv1) && all(sv2==1),
dim = mat2cell([ones(length(sx2),1) sx2(:)]', repmat(2,nx(1),1), repmat(1,nx(2),1));
elseif all(sx2==sv2) && all(sv1==1),
dim = mat2cell([sx1(:) ones(length(sx1),1)]', repmat(2,nx(1),1), repmat(1,nx(2),1));
elseif all(sv1==1) && all(sv2==1),
dim = mat2cell([sx1(:) sx2(:)]'', nx(1), nx(2));
else error('inconsistent input');
end
y = cellfun(@bsxfun, repmat({@plus}, nx), x, v, 'UniformOutput', 0);
%y = cellfun(@vplus, x, v, dim, 'UniformOutput', 0);
function y = vplus(x, v, dim)
y = x + repmat(v, dim);
%-----cellvecmult
function [y] = cellvecmult(x, v)
% [Y]= CELLVECMULT(X, V) - multiply vectors in cell-array V
% to all rows or columns of each matrix in cell-array X
% V can be a vector or a cell-array of vectors
% check once and for all to save time
persistent bsxfun_exists;
if isempty(bsxfun_exists);
bsxfun_exists=(exist('bsxfun')==5);
if ~bsxfun_exists;
error('bsxfun not found.');
end
end
nx = size(x);
if ~iscell(x) || length(nx)>2 || all(nx>1),
error('incorrect input for cellmean');
end
if ~iscell(v),
v = repmat({v}, nx);
end
sx1 = cellfun('size', x, 1);
sx2 = cellfun('size', x, 2);
sv1 = cellfun('size', v, 1);
sv2 = cellfun('size', v, 2);
if all(sx1==sv1) && all(sv2==1),
elseif all(sx2==sv2) && all(sv1==1),
elseif all(sv1==1) && all(sv2==1),
else error('inconsistent input');
end
y = cellfun(@bsxfun, repmat({@times}, nx), x, v, 'UniformOutput', 0);
%-----cellzscore
function [z, sd, m] = cellzscore(x, dim, flag)
% [Z, SD] = CELLZSCORE(X, DIM, FLAG) computes the zscore, across all cells in x along
% the dimension dim, normalising by the total number of samples
%
% X should be an linear cell-array of matrices for which the size in at
% least one of the dimensions should be the same for all cells. If flag==1, the mean will
% be subtracted first (default behaviour, but to save time on already demeaned data, it
% can be set to 0). SD is a vector containing the standard deviations, used for the normalisation.
nx = size(x);
if ~iscell(x) || length(nx)>2 || all(nx>1),
error('incorrect input for cellstd');
end
if nargin<2,
scx1 = cellfun('size', x, 1);
scx2 = cellfun('size', x, 2);
if all(scx2==scx2(1)), dim = 2; %let second dimension prevail
elseif all(scx1==scx1(1)), dim = 1;
else error('no dimension to compute mean for');
end
elseif nargin==2,
flag = 1;
end
if flag,
m = cellmean(x, dim);
x = cellvecadd(x, -m);
end
sd = cellstd(x, dim, 0);
z = cellvecmult(x, 1./sd);
|
github
|
philippboehmsturm/antx-master
|
ft_sensorrealign.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_sensorrealign.m
| 31,808 |
utf_8
|
d579e892f804b2535ec8664491e736c5
|
function [elec_realigned] = ft_sensorrealign(cfg, elec_original)
% FT_SENSORREALIGN rotates and translates electrode and gradiometer
% sensor positions to template electrode positions or towards the head
% surface. It can either perform a rigid body transformation, in which only
% the coordinate system is changed, or it can apply additional deformations
% to the input sensors. Different methods for aligning the input electrodes
% to the subjects head are implemented, which are described in detail
% below.
%
% FIDUCIAL - You can apply a rigid body realignment based on three fiducial
% locations. After realigning, the fiducials in the input electrode set
% (typically nose, left and right ear) are along the same axes as the
% fiducials in the template electrode set.
%
% TEMPLATE - You can apply a spatial transformation/deformation that
% automatically minimizes the distance between the electrodes or
% gradiometers and a template or sensor array. The warping methods use a
% non-linear search to minimize the distance between the input sensor
% positions and the corresponding template sensors.
%
% HEADSHAPE - You can apply a spatial transformation/deformation that
% automatically minimizes the distance between the electrodes and the head
% surface. The warping methods use a non-linear search to minimize the
% distance between the input sensor positions and the projection of the
% electrodes on the head surface.
%
% INTERACTIVE - You can display the skin surface together with the
% electrode or gradiometer positions, and manually (using the graphical
% user interface) adjust the rotation, translation and scaling parameters,
% so that the electrodes correspond with the skin.
%
% MANUAL - You can display the skin surface and manually determine the
% electrode positions by clicking on the skin surface.
%
% Use as
% [sensor] = ft_sensorrealign(cfg) or
% [sensor] = ft_sensorrealign(cfg, sensor)
% where you specify the electrodes or gradiometers in the configuration
% structure (see below) or as the second input argument.
%
% The configuration can contain the following options
% cfg.method = string representing the method for aligning or placing the electrodes
% 'fiducial' realign using three fiducials (e.g. NAS, LPA and RPA)
% 'template' realign the sensors to match a template set
% 'headshape' realign the sensors to fit the head surface
% 'interactive' realign manually using a graphical user interface
% 'manual' manual positioning of the electrodes by clicking in a graphical user interface
% cfg.warp = string describing the spatial transformation for the template method
% 'rigidbody' apply a rigid-body warp (default)
% 'globalrescale' apply a rigid-body warp with global rescaling
% 'traditional' apply a rigid-body warp with individual axes rescaling
% 'nonlin1' apply a 1st order non-linear warp
% 'nonlin2' apply a 2nd order non-linear warp
% 'nonlin3' apply a 3rd order non-linear warp
% 'nonlin4' apply a 4th order non-linear warp
% 'nonlin5' apply a 5th order non-linear warp
% cfg.channel = Nx1 cell-array with selection of channels (default = 'all'),
% see FT_CHANNELSELECTION for details
% cfg.fiducial = cell-array with the name of three fiducials used for
% realigning (default = {'nasion', 'lpa', 'rpa'})
% cfg.casesensitive = 'yes' or 'no', determines whether string comparisons
% between electrode labels are case sensitive (default = 'yes')
% cfg.feedback = 'yes' or 'no' (default = 'no')
%
% The electrodes or the gradiometers that will be realigned can be
% specified in the second input argument, or optionally as
% cfg.elecfile = string with filename, or alternatively
% cfg.elec = structure with electrode definition
% cfg.gradfile = string with filename, or alternatively
% cfg.grad = structure with gradiometer definition
%
% To realign the sensors using the fiducials, the target has to contain the
% three template fiducials, e.g.
% cfg.target.pnt(1,:) = [110 0 0] % location of the nose
% cfg.target.pnt(2,:) = [0 90 0] % location of the left ear
% cfg.target.pnt(3,:) = [0 -90 0] % location of the right ear
% cfg.target.label = {'NAS', 'LPA', 'RPA'}
%
% To align the sensors to a single template set or to multiple electrode
% sets (which will be averaged), you should specify the target as
% cfg.target = single electrode or gradiometer set that serves as standard
% or
% cfg.target(1..N) = list of electrode or gradiometer sets that are averaged into the standard
% The target electrode or gradiometer sets can be specified either as
% structures (i.e. when they are already read in memory) or as file names.
%
% To align existing electrodes to the head surface, or to manually position
% new electrodes using the head surface, you should specify
% cfg.headshape = a filename containing headshape, a structure containing a
% single triangulated boundary, or a Nx3 matrix with surface
% points
%
% See also FT_READ_SENS, FT_VOLUMEREALIGN, FT_INTERACTIVEREALIGN
% Copyright (C) 2005-2011, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_sensorrealign.m 3710 2011-06-16 14:04:19Z eelspa $
ft_defaults
% record start time and total processing time
ftFuncTimer = tic();
ftFuncClock = clock();
% this is used for feedback of the lower-level functions
global fb
% the interactive method uses a global variable to get the data from the figure when it is closed
global norm
% set the defaults
if ~isfield(cfg, 'channel'), cfg.channel = 'all'; end
if ~isfield(cfg, 'coordsys'), cfg.coordsys = []; end
if ~isfield(cfg, 'feedback'), cfg.feedback = 'no'; end
if ~isfield(cfg, 'casesensitive'), cfg.casesensitive = 'yes'; end
if ~isfield(cfg, 'warp'), cfg.warp = 'rigidbody'; end
if ~isfield(cfg, 'label'), cfg.label = 'off'; end
cfg = ft_checkconfig(cfg, 'renamed', {'template', 'target'});
cfg = ft_checkconfig(cfg, 'renamedval', {'method', 'realignfiducials', 'fiducial'});
cfg = ft_checkconfig(cfg, 'renamedval', {'method', 'realignfiducial', 'fiducial'});
cfg = ft_checkconfig(cfg, 'renamedval', {'warp', 'homogenous', 'rigidbody'});
cfg = ft_checkconfig(cfg, 'forbidden', 'outline');
if isfield(cfg, 'headshape') && isa(cfg.headshape, 'config')
% convert the nested config-object back into a normal structure
cfg.headshape = struct(cfg.headshape);
end
if ~isempty(cfg.coordsys)
switch lower(cfg.coordsys)
case 'ctf'
cfg.target = [];
cfg.target.pnt(1,:) = [100 0 0];
cfg.target.pnt(2,:) = [0 80 0];
cfg.target.pnt(3,:) = [0 -80 0];
cfg.target.label{1} = 'NAS';
cfg.target.label{2} = 'LPA';
cfg.target.label{3} = 'RPA';
otherwise
error('the %s coordinate system is not automatically supported, please specify the details in cfg.target')
end
end
% ensure that the right cfg options have been set corresponding to the method
switch cfg.method
case 'template' % realign the sensors to match a template set
cfg = ft_checkconfig(cfg, 'required', 'target', 'forbidden', 'headshape');
case 'headshape' % realign the sensors to fit the head surface
cfg = ft_checkconfig(cfg, 'required', 'headshape', 'forbidden', 'target');
case 'fiducial' % realign using the NAS, LPA and RPA fiducials
cfg = ft_checkconfig(cfg, 'required', 'target', 'forbidden', 'headshape');
case 'interactive' % realign manually using a graphical user interface
cfg = ft_checkconfig(cfg, 'required', 'headshape');
case 'manual' % manual positioning of the electrodes by clicking in a graphical user interface
cfg = ft_checkconfig(cfg, 'required', 'headshape', 'forbidden', 'target');
end % switch cfg.method
if strcmp(cfg.feedback, 'yes')
% use the global fb field to tell the warping toolbox to print feedback
fb = 1;
else
fb = 0;
end
% get the electrode definition that should be warped
if isfield(cfg, 'elec')
elec_original = cfg.elec;
elseif isfield(cfg, 'elecfile')
elec_original = ft_read_sens(cfg.elecfile);
elseif isfield(cfg, 'grad')
elec_original = cfg.grad;
elseif isfield(cfg, 'gradfile')
elec_original = ft_read_sens(cfg.gradfile);
elseif nargin>1
% the input electrodes were specified as second input argument
else
% start with an empty set of electrodes, this is usefull for manual positioning
elec_original = [];
elec_original.pnt = zeros(0,3);
elec_original.label = cell(0,1);
elec_original.unit = 'mm';
end
% ensure that the units are specified
elec_original = ft_convert_units(elec_original);
% remember the original electrode locations and labels and do all the work
% with a temporary copy, this involves channel selection and changing to
% lower case
elec = elec_original;
if strcmp(cfg.method, 'fiducial') && isfield(elec, 'fid')
% instead of working with all sensors, only work with the fiducials
% this is useful for gradiometer structures
fprintf('using the fiducials instead of the sensor positions\n');
elec.fid.unit = elec.unit;
elec = elec.fid;
end
usetemplate = isfield(cfg, 'target') && ~isempty(cfg.target);
useheadshape = isfield(cfg, 'headshape') && ~isempty(cfg.headshape);
if usetemplate
% get the template electrode definitions
if ~iscell(cfg.target)
cfg.target = {cfg.target};
end
Ntemplate = length(cfg.target);
for i=1:Ntemplate
if isstruct(cfg.target{i})
template(i) = cfg.target{i};
else
template(i) = ft_read_sens(cfg.target{i});
end
end
clear tmp
for i=1:Ntemplate
tmp(i) = ft_convert_units(template(i), elec.unit); % ensure that the units are consistent with the electrodes
end
template = tmp;
end
if useheadshape
% get the surface describing the head shape
if isstruct(cfg.headshape) && isfield(cfg.headshape, 'pnt')
% use the headshape surface specified in the configuration
headshape = cfg.headshape;
elseif isnumeric(cfg.headshape) && size(cfg.headshape,2)==3
% use the headshape points specified in the configuration
headshape.pnt = cfg.headshape;
elseif ischar(cfg.headshape)
% read the headshape from file
headshape = ft_read_headshape(cfg.headshape);
else
error('cfg.headshape is not specified correctly')
end
if ~isfield(headshape, 'tri')
% generate a closed triangulation from the surface points
headshape.pnt = unique(headshape.pnt, 'rows');
headshape.tri = projecttri(headshape.pnt);
end
headshape = ft_convert_units(headshape, elec.unit); % ensure that the units are consistent with the electrodes
end
% convert all labels to lower case for string comparisons
% this has to be done AFTER keeping the original labels and positions
if strcmp(cfg.casesensitive, 'no')
for i=1:length(elec.label)
elec.label{i} = lower(elec.label{i});
end
for j=1:length(template)
for i=1:length(template(j).label)
template(j).label{i} = lower(template(j).label{i});
end
end
end
if strcmp(cfg.feedback, 'yes')
% create an empty figure, continued below...
figure
axis equal
axis vis3d
hold on
xlabel('x')
ylabel('y')
zlabel('z')
end
% start with an empty structure, this will be returned at the end
norm = [];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if strcmp(cfg.method, 'template')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% determine electrode selection and overlapping subset for warping
cfg.channel = ft_channelselection(cfg.channel, elec.label);
for i=1:Ntemplate
cfg.channel = ft_channelselection(cfg.channel, template(i).label);
end
% make consistent subselection of electrodes
[cfgsel, datsel] = match_str(cfg.channel, elec.label);
elec.label = elec.label(datsel);
elec.pnt = elec.pnt(datsel,:);
for i=1:Ntemplate
[cfgsel, datsel] = match_str(cfg.channel, template(i).label);
template(i).label = template(i).label(datsel);
template(i).pnt = template(i).pnt(datsel,:);
end
% compute the average of the template electrode positions
average = ft_average_sens(template);
fprintf('warping electrodes to average template... '); % the newline comes later
[norm.pnt, norm.m] = warp_optim(elec.pnt, average.pnt, cfg.warp);
norm.label = elec.label;
dpre = mean(sqrt(sum((average.pnt - elec.pnt).^2, 2)));
dpost = mean(sqrt(sum((average.pnt - norm.pnt).^2, 2)));
fprintf('mean distance prior to warping %f, after warping %f\n', dpre, dpost);
if strcmp(cfg.feedback, 'yes')
% plot all electrodes before warping
ft_plot_sens(elec, 'r*');
% plot all electrodes after warping
ft_plot_sens(norm, 'm.', 'label', 'label');
% plot the template electrode locations
ft_plot_sens(average, 'b.');
% plot lines connecting the input and the realigned electrode locations with the template locations
my_line3(elec.pnt, average.pnt, 'color', 'r');
my_line3(norm.pnt, average.pnt, 'color', 'm');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif strcmp(cfg.method, 'headshape')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% determine electrode selection and overlapping subset for warping
cfg.channel = ft_channelselection(cfg.channel, elec.label);
% make subselection of electrodes
[cfgsel, datsel] = match_str(cfg.channel, elec.label);
elec.label = elec.label(datsel);
elec.pnt = elec.pnt(datsel,:);
fprintf('warping electrodes to skin surface... '); % the newline comes later
[norm.pnt, norm.m] = warp_optim(elec.pnt, headshape, cfg.warp);
norm.label = elec.label;
dpre = warp_error([], elec.pnt, headshape, cfg.warp);
dpost = warp_error(norm.m, elec.pnt, headshape, cfg.warp);
fprintf('mean distance prior to warping %f, after warping %f\n', dpre, dpost);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif strcmp(cfg.method, 'fiducial')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% the fiducials have to be present in the electrodes and in the template set
label = intersect(lower(elec.label), lower(template.label));
if ~isfield(cfg, 'fiducial') || isempty(cfg.fiducial)
% try to determine the names of the fiducials automatically
option1 = {'nasion' 'left' 'right'};
option2 = {'nasion' 'lpa' 'rpa'};
option3 = {'nz' 'left' 'right'};
option4 = {'nz' 'lpa' 'rpa'};
option5 = {'nas' 'left' 'right'};
option6 = {'nas' 'lpa' 'rpa'};
if length(match_str(label, option1))==3
cfg.fiducial = option1;
elseif length(match_str(label, option2))==3
cfg.fiducial = option2;
elseif length(match_str(label, option3))==3
cfg.fiducial = option3;
elseif length(match_str(label, option4))==3
cfg.fiducial = option4;
elseif length(match_str(label, option5))==3
cfg.fiducial = option5;
elseif length(match_str(label, option6))==3
cfg.fiducial = option6;
else
error('could not determine consistent fiducials in the input and the target, please specify cfg.fiducial or cfg.coordsys')
end
end
fprintf('matching fiducials {''%s'', ''%s'', ''%s''}\n', cfg.fiducial{1}, cfg.fiducial{2}, cfg.fiducial{3});
% determine electrode selection
cfg.channel = ft_channelselection(cfg.channel, elec.label);
[cfgsel, datsel] = match_str(cfg.channel, elec.label);
elec.label = elec.label(datsel);
elec.pnt = elec.pnt(datsel,:);
if length(cfg.fiducial)~=3
error('you must specify three fiducials');
end
% do case-insensitive search for fiducial locations
nas_indx = match_str(lower(elec.label), lower(cfg.fiducial{1}));
lpa_indx = match_str(lower(elec.label), lower(cfg.fiducial{2}));
rpa_indx = match_str(lower(elec.label), lower(cfg.fiducial{3}));
if length(nas_indx)~=1 || length(lpa_indx)~=1 || length(rpa_indx)~=1
error('not all fiducials were found in the electrode set');
end
elec_nas = elec.pnt(nas_indx,:);
elec_lpa = elec.pnt(lpa_indx,:);
elec_rpa = elec.pnt(rpa_indx,:);
% FIXME change the flow in the remainder
% if one or more template electrode sets are specified, then align to the average of those
% if no template is specified, then align so that the fiducials are along the axis
% find the matching fiducials in the template and average them
templ_nas = nan(Ntemplate,3);
templ_lpa = nan(Ntemplate,3);
templ_rpa = nan(Ntemplate,3);
for i=1:Ntemplate
nas_indx = match_str(lower(template(i).label), lower(cfg.fiducial{1}));
lpa_indx = match_str(lower(template(i).label), lower(cfg.fiducial{2}));
rpa_indx = match_str(lower(template(i).label), lower(cfg.fiducial{3}));
if length(nas_indx)~=1 || length(lpa_indx)~=1 || length(rpa_indx)~=1
error(sprintf('not all fiducials were found in template %d', i));
end
templ_nas(i,:) = template(i).pnt(nas_indx,:);
templ_lpa(i,:) = template(i).pnt(lpa_indx,:);
templ_rpa(i,:) = template(i).pnt(rpa_indx,:);
end
templ_nas = mean(templ_nas,1);
templ_lpa = mean(templ_lpa,1);
templ_rpa = mean(templ_rpa,1);
% realign both to a common coordinate system
elec2common = headcoordinates(elec_nas, elec_lpa, elec_rpa);
templ2common = headcoordinates(templ_nas, templ_lpa, templ_rpa);
% compute the combined transform and realign the electrodes to the template
norm = [];
norm.m = elec2common * inv(templ2common);
norm.pnt = warp_apply(norm.m, elec.pnt, 'homogeneous');
norm.label = elec.label;
nas_indx = match_str(lower(elec.label), lower(cfg.fiducial{1}));
lpa_indx = match_str(lower(elec.label), lower(cfg.fiducial{2}));
rpa_indx = match_str(lower(elec.label), lower(cfg.fiducial{3}));
dpre = mean(sqrt(sum((elec.pnt([nas_indx lpa_indx rpa_indx],:) - [templ_nas; templ_lpa; templ_rpa]).^2, 2)));
nas_indx = match_str(lower(norm.label), lower(cfg.fiducial{1}));
lpa_indx = match_str(lower(norm.label), lower(cfg.fiducial{2}));
rpa_indx = match_str(lower(norm.label), lower(cfg.fiducial{3}));
dpost = mean(sqrt(sum((norm.pnt([nas_indx lpa_indx rpa_indx],:) - [templ_nas; templ_lpa; templ_rpa]).^2, 2)));
fprintf('mean distance between fiducials prior to realignment %f, after realignment %f\n', dpre, dpost);
if strcmp(cfg.feedback, 'yes')
% plot the first three electrodes before transformation
my_plot3(elec.pnt(1,:), 'r*');
my_plot3(elec.pnt(2,:), 'r*');
my_plot3(elec.pnt(3,:), 'r*');
my_text3(elec.pnt(1,:), elec.label{1}, 'color', 'r');
my_text3(elec.pnt(2,:), elec.label{2}, 'color', 'r');
my_text3(elec.pnt(3,:), elec.label{3}, 'color', 'r');
% plot the template fiducials
my_plot3(templ_nas, 'b*');
my_plot3(templ_lpa, 'b*');
my_plot3(templ_rpa, 'b*');
my_text3(templ_nas, ' nas', 'color', 'b');
my_text3(templ_lpa, ' lpa', 'color', 'b');
my_text3(templ_rpa, ' rpa', 'color', 'b');
% plot all electrodes after transformation
my_plot3(norm.pnt, 'm.');
my_plot3(norm.pnt(1,:), 'm*');
my_plot3(norm.pnt(2,:), 'm*');
my_plot3(norm.pnt(3,:), 'm*');
my_text3(norm.pnt(1,:), norm.label{1}, 'color', 'm');
my_text3(norm.pnt(2,:), norm.label{2}, 'color', 'm');
my_text3(norm.pnt(3,:), norm.label{3}, 'color', 'm');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif strcmp(cfg.method, 'interactive')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% give the user instructions
disp('Use the mouse to rotate the head and the electrodes around, and click "redisplay"');
disp('Close the figure when you are done');
% open a figure
fig = figure;
% add the data to the figure
set(fig, 'CloseRequestFcn', @cb_close);
setappdata(fig, 'elec', elec);
setappdata(fig, 'transform', eye(4));
if useheadshape
setappdata(fig, 'headshape', headshape);
end
if usetemplate
% FIXME interactive realigning to template electrodes is not yet supported
% this requires a consistent handling of channel selection etc.
setappdata(fig, 'template', template);
end
% add the GUI elements
cb_creategui(gca);
cb_redraw(gca);
rotate3d on
waitfor(fig);
% get the data from the figure that was left behind as global variable
tmp = norm;
clear global norm
norm = tmp;
clear tmp
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif strcmp(cfg.method, 'manual')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% give the user instructions
disp('Use the mouse to click on the desired electrode positions');
disp('Afterwards you manually have to assign the electrode names to "elec.label"');
disp('Close the figure or press "q" when you are done');
% open a figure
figure;
% plot the faces of the 2D or 3D triangulation
skin = [255 213 119]/255;
ft_plot_mesh(headshape,'facecolor', skin,'EdgeColor','none','facealpha',0.7);
lighting gouraud
material shiny
camlight
% rotate3d on
xyz = ft_select_point3d(headshape, 'multiple', true);
norm.pnt = xyz;
for i=1:size(norm.pnt,1)
norm.label{i,1} = sprintf('%d', i);
end
else
error('unknown method');
end
% apply the spatial transformation to all electrodes, and replace the
% electrode labels by their case-sensitive original values
switch cfg.method
case {'template', 'headshape'}
try
% convert the vector with fitted parameters into a 4x4 homogenous transformation
% apply the transformation to the original complete set of sensors
elec_realigned = ft_transform_sens(feval(cfg.warp, norm.m), elec_original);
catch
% the previous section will fail for nonlinear transformations
elec_realigned.label = elec_original.label;
elec_realigned.pnt = warp_apply(norm.m, elec_original.pnt, cfg.warp);
end
% remember the transformation
elec_realigned.(cfg.warp) = norm.m;
case {'fiducial', 'interactive'}
% the transformation is a 4x4 homogenous matrix
homogenous = norm.m;
% apply the transformation to the original complete set of sensors
elec_realigned = ft_transform_sens(homogenous, elec_original);
% remember the transformation
elec_realigned.homogenous = norm.m;
case 'manual'
% the positions are already assigned in correspondence with the mesh
elec_realigned = norm;
otherwise
error('unknown method');
end
% add version information to the configuration
cfg.version.name = mfilename('fullpath');
cfg.version.id = '$Id: ft_sensorrealign.m 3710 2011-06-16 14:04:19Z eelspa $';
% add information about the Matlab version used to the configuration
cfg.callinfo.matlab = version();
% add information about the function call to the configuration
cfg.callinfo.proctime = toc(ftFuncTimer);
cfg.callinfo.calltime = ftFuncClock;
cfg.callinfo.user = getusername();
% remember the exact configuration details in the output
elec_realigned.cfg = cfg;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% some simple SUBFUNCTIONs that facilitate 3D plotting
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function h = my_plot3(xyz, varargin)
h = plot3(xyz(:,1), xyz(:,2), xyz(:,3), varargin{:});
function h = my_text3(xyz, varargin)
h = text(xyz(:,1), xyz(:,2), xyz(:,3), varargin{:});
function my_line3(xyzB, xyzE, varargin)
for i=1:size(xyzB,1)
line([xyzB(i,1) xyzE(i,1)], [xyzB(i,2) xyzE(i,2)], [xyzB(i,3) xyzE(i,3)], varargin{:})
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION to layout a moderately complex graphical user interface
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function h = layoutgui(fig, geometry, position, style, string, value, tag, callback)
horipos = geometry(1); % lower left corner of the GUI part in the figure
vertpos = geometry(2); % lower left corner of the GUI part in the figure
width = geometry(3); % width of the GUI part in the figure
height = geometry(4); % height of the GUI part in the figure
horidist = 0.05;
vertdist = 0.05;
options = {'units', 'normalized', 'HorizontalAlignment', 'center'}; % 'VerticalAlignment', 'middle'
Nrow = size(position,1);
h = cell(Nrow,1);
for i=1:Nrow
if isempty(position{i})
continue;
end
position{i} = position{i} ./ sum(position{i});
Ncol = size(position{i},2);
ybeg = (Nrow-i )/Nrow + vertdist/2;
yend = (Nrow-i+1)/Nrow - vertdist/2;
for j=1:Ncol
xbeg = sum(position{i}(1:(j-1))) + horidist/2;
xend = sum(position{i}(1:(j ))) - horidist/2;
pos(1) = xbeg*width + horipos;
pos(2) = ybeg*height + vertpos;
pos(3) = (xend-xbeg)*width;
pos(4) = (yend-ybeg)*height;
h{i}{j} = uicontrol(fig, ...
options{:}, ...
'position', pos, ...
'style', style{i}{j}, ...
'string', string{i}{j}, ...
'tag', tag{i}{j}, ...
'value', value{i}{j}, ...
'callback', callback{i}{j} ...
);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_creategui(hObject, eventdata, handles)
% define the position of each GUI element
position = {
[2 1 1 1]
[2 1 1 1]
[2 1 1 1]
[1]
[1]
[1]
[1]
[1 1]
};
% define the style of each GUI element
style = {
{'text' 'edit' 'edit' 'edit'}
{'text' 'edit' 'edit' 'edit'}
{'text' 'edit' 'edit' 'edit'}
{'pushbutton'}
{'pushbutton'}
{'toggle'}
{'toggle'}
{'text' 'edit'}
};
% define the descriptive string of each GUI element
string = {
{'rotate' 0 0 0}
{'translate' 0 0 0}
{'scale' 1 1 1}
{'redisplay'}
{'apply'}
{'toggle labels'}
{'toggle axes'}
{'opacity' 0.7}
};
% define the value of each GUI element
value = {
{[] [] [] []}
{[] [] [] []}
{[] [] [] []}
{[]}
{[]}
{0}
{0}
{[] []}
};
% define a tag for each GUI element
tag = {
{'' 'rx' 'ry' 'rz'}
{'' 'tx' 'ty' 'tz'}
{'' 'sx' 'sy' 'sz'}
{''}
{''}
{'toggle labels'}
{'toggle axes'}
{'' 'alpha'}
};
% define the callback function of each GUI element
callback = {
{[] @cb_redraw @cb_redraw @cb_redraw}
{[] @cb_redraw @cb_redraw @cb_redraw}
{[] @cb_redraw @cb_redraw @cb_redraw}
{@cb_redraw}
{@cb_apply}
{@cb_redraw}
{@cb_redraw}
{[] @cb_redraw}
};
fig = get(hObject, 'parent');
layoutgui(fig, [0.7 0.05 0.25 0.50], position, style, string, value, tag, callback);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_redraw(hObject, eventdata, handles)
fig = get(hObject, 'parent');
headshape = getappdata(fig, 'headshape');
elec = getappdata(fig, 'elec');
template = getappdata(fig, 'template');
% get the transformation details
rx = str2num(get(findobj(fig, 'tag', 'rx'), 'string'));
ry = str2num(get(findobj(fig, 'tag', 'ry'), 'string'));
rz = str2num(get(findobj(fig, 'tag', 'rz'), 'string'));
tx = str2num(get(findobj(fig, 'tag', 'tx'), 'string'));
ty = str2num(get(findobj(fig, 'tag', 'ty'), 'string'));
tz = str2num(get(findobj(fig, 'tag', 'tz'), 'string'));
sx = str2num(get(findobj(fig, 'tag', 'sx'), 'string'));
sy = str2num(get(findobj(fig, 'tag', 'sy'), 'string'));
sz = str2num(get(findobj(fig, 'tag', 'sz'), 'string'));
R = rotate ([rx ry rz]);
T = translate([tx ty tz]);
S = scale ([sx sy sz]);
H = S * T * R;
elec = ft_transform_sens(H, elec);
axis vis3d; cla
xlabel('x')
ylabel('y')
zlabel('z')
if ~isempty(template)
disp('Plotting the template electrodes in blue');
if size(template.pnt, 2)==2
hs = plot(template.pnt(:,1), template.pnt(:,2), 'b.', 'MarkerSize', 20);
else
hs = plot3(template.pnt(:,1), template.pnt(:,2), template.pnt(:,3), 'b.', 'MarkerSize', 20);
end
end
if ~isempty(headshape)
% plot the faces of the 2D or 3D triangulation
skin = [255 213 119]/255;
ft_plot_mesh(headshape,'facecolor', skin,'EdgeColor','none','facealpha',0.7);
lighting gouraud
material shiny
camlight
end
if isfield(elec, 'fid') && ~isempty(elec.fid.pnt)
disp('Plotting the fiducials in red');
ft_plot_sens(elec.fid,'style', 'r*');
end
if get(findobj(fig, 'tag', 'toggle axes'), 'value')
axis on
grid on
else
axis off
grid on
end
hold on
if get(findobj(fig, 'tag', 'toggle labels'), 'value')
ft_plot_sens(elec,'label', 'on');
else
ft_plot_sens(elec,'label', 'off');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_apply(hObject, eventdata, handles)
fig = get(hObject, 'parent');
elec = getappdata(fig, 'elec');
transform = getappdata(fig, 'transform');
% get the transformation details
rx = str2num(get(findobj(fig, 'tag', 'rx'), 'string'));
ry = str2num(get(findobj(fig, 'tag', 'ry'), 'string'));
rz = str2num(get(findobj(fig, 'tag', 'rz'), 'string'));
tx = str2num(get(findobj(fig, 'tag', 'tx'), 'string'));
ty = str2num(get(findobj(fig, 'tag', 'ty'), 'string'));
tz = str2num(get(findobj(fig, 'tag', 'tz'), 'string'));
sx = str2num(get(findobj(fig, 'tag', 'sx'), 'string'));
sy = str2num(get(findobj(fig, 'tag', 'sy'), 'string'));
sz = str2num(get(findobj(fig, 'tag', 'sz'), 'string'));
R = rotate ([rx ry rz]);
T = translate([tx ty tz]);
S = scale ([sx sy sz]);
H = S * T * R;
elec = ft_transform_headshape(H, elec);
transform = H * transform;
set(findobj(fig, 'tag', 'rx'), 'string', 0);
set(findobj(fig, 'tag', 'ry'), 'string', 0);
set(findobj(fig, 'tag', 'rz'), 'string', 0);
set(findobj(fig, 'tag', 'tx'), 'string', 0);
set(findobj(fig, 'tag', 'ty'), 'string', 0);
set(findobj(fig, 'tag', 'tz'), 'string', 0);
set(findobj(fig, 'tag', 'sx'), 'string', 1);
set(findobj(fig, 'tag', 'sy'), 'string', 1);
set(findobj(fig, 'tag', 'sz'), 'string', 1);
setappdata(fig, 'elec', elec);
setappdata(fig, 'transform', transform);
cb_redraw(hObject);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_close(hObject, eventdata, handles)
% make the current transformation permanent and subsequently allow deleting the figure
cb_apply(gca);
% get the updated electrode from the figure
fig = hObject;
% hmmm, this is ugly
global norm
norm = getappdata(fig, 'elec');
norm.m = getappdata(fig, 'transform');
set(fig, 'CloseRequestFcn', @delete);
delete(fig);
|
github
|
philippboehmsturm/antx-master
|
ft_spike_data2spike.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_spike_data2spike.m
| 4,689 |
utf_8
|
1519e77ecd52978f98a93437ee57a7d2
|
function [spike] = ft_spike_data2spike(cfg,data)
% FT_SPIKE_DATA2SPIKE converts a continuous spikestation DATA structure to a point
% representation of the data in a spikestation SPIKE structure.
%
% Configurations options (CFG):
%
% Configuration options related to selection of spike channel and trials:
%
% cfg.spikechannel = string or index of single spike channel to trigger on
% (default = 'all'). See FT_CHANNELSELECTION for details
% Martin Vinck 2010 (C).
if nargin~=2, error('MATLAB:ft_spike_data2spike:data2spike:nargin','Two input arguments required'), end
% put the defaults and check whether there are ununsed fields
defaults.spikechannel = {'all'};
cfg = ft_spike_sub_defaultcfg(cfg,defaults);
% check if the input data is valid for this function, should be done with CHECKDATA
hasAllFields = all(isfield(data,{'time','trial', 'label'}));
if ~hasAllFields, error('MATLAB:ft_spike_data2spike:data2spike:wrongInput',...
'DATA should contain .time, .trial, .label');
end
% spike channel selection, avoid check on max number of spikes here, since we may use spike format
% for events as well
cfg.channel = ft_channelselection(cfg.spikechannel, data.label);
spikesel = match_str(data.label, cfg.channel);
nUnits = length(spikesel); % number of units
if nUnits==0, error('MATLAB:ft_spike_data2spike:cfg:spikechannel:noChanSelected',...
'No spikechannel selected by means of cfg.spikechannel');
end
% do the conversion
nTrials = length(data.trial);
trialTimes = zeros(nTrials,2);
for iUnit = 1:nUnits
unitIndx = spikesel(iUnit);
spikeTimes = []; % we dont know how large it will be, so use concatenation inside loop
trialInds = [];
for iTrial = 1:nTrials
% read in the spike times
[spikeTimesTrial] = getspiketimes(data, iTrial, unitIndx);
nSpikes = length(spikeTimesTrial);
spikeTimes = [spikeTimes; spikeTimesTrial(:)];
trialInds = [trialInds; ones(nSpikes,1)*iTrial];
% get the begs and ends of trials
if iUnit==1, trialTimes(iTrial,:) = data.time{iTrial}([1 end]); end
end
spike.label{iUnit} = data.label{unitIndx};
spike.waveform{iUnit} = [];
spike.time{iUnit} = spikeTimes;
spike.trial{iUnit} = trialInds;
if iUnit==1, spike.trialtime = trialTimes; end
end
% add version information to the configuration
try
% get the full name of the function
cfg.version.name = mfilename('fullpath');
catch
% required for compatibility with Matlab versions prior to release 13 (6.5)
[st, i] = dbstack;
cfg.version.name = st(i);
end
% remember the configuration details of the input data
try, cfg.previous = data.cfg; end
% remember the exact configuration details in the output
spike.cfg = cfg;
%%%%%%%%%% SUB FUNCTION %%%%%%%%%%
function [spikeTimes spikeIndx] = getspiketimes(data,trial,unit)
% GETSPIKETIMES extracts the spike times and spike samples from a continuous fieldtrip
% DATA structure in a selected trial for a selected unit.
%
% Inputs:
% DATA is a contiuous fieldtrip data structure
%
% TRIAL is a natural number indicating which trial is selected
% UNIT is a natural number indicating which channel is selected
%
% Outputs:
% SPIKETIMES contains the spike times, sampled at frequency data.fsample;
% SPIKEINDX contains the samples in data.trial{trial}(unit,:) at which we find the
% spikes.
spikeIndx = logical(data.trial{trial}(unit,:));
spikeCount = data.trial{trial}(unit,spikeIndx);
spikeTimes = data.time{trial}(spikeIndx);
multiSpikes = find(spikeCount>1);
% preallocate the additional times that we get from the double spikes
nMultiSpikes = sum(spikeCount(multiSpikes));
[addTimes,addSamples] = deal(zeros(nMultiSpikes,1));
binWidth = 1/data.fsample; % the width of each bin
halfBinWidth = binWidth/2;
% get the additional samples and spike times, we need only loop through the bins
n = 1;
for iBin = multiSpikes(:)' % looping over row vector
nSpikesInBin = spikeCount(iBin);
addTimes(n : n+nSpikesInBin-1) = ones(1,nSpikesInBin)*spikeTimes(iBin);
addSamples(n : n+nSpikesInBin-1) = ones(1,nSpikesInBin)*spikeIndx(iBin);
n = n + nSpikesInBin;
end
% before adding these times, first remove the old ones
spikeTimes(multiSpikes) = [];
spikeIndx(multiSpikes) = [];
spikeTimes = sort([spikeTimes(:); addTimes(:)]);
spikeIndx = sort([spikeIndx(:) ; addSamples(:)]);
|
github
|
philippboehmsturm/antx-master
|
ft_databrowser.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_databrowser.m
| 51,564 |
utf_8
|
bbe291a12d02c5fbf5eb26906a44cbe5
|
function [cfg] = ft_databrowser(cfg, data)
% FT_DATABROWSER can be used for visual inspection of data. Artifacts that were detected
% by artifact functions (see FT_ARTIFACT_xxx functions where xxx is the type of artifact)
% are marked. Additionally data pieces can be marked and unmarked as artifact by
% manual selection. The output cfg contains the updated artifactdef field.
%
% Use as
% cfg = ft_databrowser(cfg)
% required configuration options:
% with the cfg.dataset or cfg.headerfile and cfg.datafile option, or use as
% cfg = ft_databrowser(cfg, data)
% where the input data is a structure as obtained from FT_PREPROCESSING or FT_COMPONENTANALYSIS.
%
% The following configuration options are supported:
% cfg.ylim = vertical scaling, can be 'maxmin', 'maxabs' or [ymin ymax] (default = 'maxabs')
% cfg.blocksize = duration in seconds for cutting the data up, only aplicable for continuous data
% cfg.trl = structure that defines the data segments of interest, only applicable for trial-based data
% cfg.continuous = 'yes' or 'no' whether the data should be interpreted as continuous or trial-based
% cfg.channel = cell-array with channel labels, see FT_CHANNELSELECTION
% cfg.viewmode = string, 'butterfly', 'vertical', 'component' for visualizing components e.g. from an ICA (default is 'butterfly')
% cfg.artfctdef.xxx.artifact = Nx2 matrix with artifact segments see FT_ARTIFACT_xxx functions
% cfg.selectfeature = string, name of feature to be selected/added (default = 'visual')
% cfg.selectmode = string, what to do with a selection, can be 'mark', or 'eval' (default = 'mark')
% 'mark': artfctdef field is updated, 'eval': the function defined in
% cfg.selfun is evaluated f.i. browse_movieplotER calls movieplotER which makes
% a movie of the selected data
% cfg.colorgroups = 'sequential' 'labelcharx' (x = xth character in label), 'chantype' or
% vector with length(data/hdr.label) defining groups (default = 'sequential')
% cfg.channelcolormap = COLORMAP (default = customized lines map with 15 colors)
% cfg.selfun = string, name of function which is evaluated if selectmode is set to 'eval'.
% The selected data and the selcfg are passed on to this function.
% cfg.selcfg = configuration options for selfun
% cfg.eegscale = number, scaling to apply to the EEG channels prior to display
% cfg.eogscale = number, scaling to apply to the EOG channels prior to display
% cfg.ecgscale = number, scaling to apply to the ECG channels prior to display
% cfg.emgscale = number, scaling to apply to the EMG channels prior to display
% cfg.megscale = number, scaling to apply to the MEG channels prior to display
% cfg.gradscale = number, scaling to apply to the MEG gradiometer channels prior to display (in addition to the cfg.megscale factor)
% cfg.magscale = number, scaling to apply to the MEG magnetometer channels prior to display (in addition to the cfg.megscale factor)
%
% The scaling to the EEG, EOG, ECG, EMG and MEG channels is optional and can
% be used to bring the absolute numbers of the different channel types in
% the same range (e.g. fT and uV). The channel types are determined from
% the input data using FT_CHANNELSELECTION.
%
% The "artifact" field in the output cfg is a Nx2 matrix comparable to the
% "trl" matrix of FT_DEFINETRIAL. The first column of which specifying the
% beginsamples of an artifact period, the second column contains the
% endsamples of the artifactperiods.
%
% NOTE for debugging: in case the databrowser crashes, use delete(gcf) to kill the figure.
%
% See also FT_PREPROCESSING, FT_REJECTARTIFACT, FT_ARTIFACT_EOG, FT_ARTIFACT_MUSCLE,
% FT_ARTIFACT_JUMP, FT_ARTIFACT_MANUAL, FT_ARTIFACT_THRESHOLD,
% FT_ARTIFACT_CLIP, FT_ARTIFACT_ECG, FT_COMPONENTANALYIS
% Copyright (C) 2009-2011, Robert Oostenveld, Ingrid Niewenhuis
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_databrowser.m 3862 2011-07-14 13:41:01Z jorhor $
% FIXME these should be removed
% FIXME document these
% cfg.preproc
% cfg.channelcolormap
% cfg.colorgroups
ft_defaults
% record start time and total processing time
ftFuncTimer = tic();
ftFuncClock = clock();
hasdata = (nargin>1);
hascomp = hasdata && ft_datatype(data, 'comp');
% for backward compatibility
cfg = ft_checkconfig(cfg, 'unused', {'comps', 'inputfile', 'outputfile'});
cfg = ft_checkconfig(cfg, 'renamed', {'zscale', 'ylim'});
cfg = ft_checkconfig(cfg, 'renamedval', {'ylim', 'auto', 'maxabs'});
% set the defaults
if ~isfield(cfg, 'ylim'), cfg.ylim = 'maxabs'; end
if ~isfield(cfg, 'artfctdef'), cfg.artfctdef = struct; end
if ~isfield(cfg, 'selectfeature'), cfg.selectfeature = 'visual'; end % string or cell-array
if ~isfield(cfg, 'selectmode'), cfg.selectmode = 'mark'; end
if ~isfield(cfg, 'blocksize'), cfg.blocksize = 1; end % only for segmenting continuous data, i.e. one long trial
if ~isfield(cfg, 'preproc'), cfg.preproc = []; end % see preproc for options
if ~isfield(cfg, 'selfun'), cfg.selfun = 'browse_multiplotER'; end
if ~isfield(cfg, 'selcfg'), cfg.selcfg = []; end
if ~isfield(cfg, 'colorgroups'), cfg.colorgroups = 'sequential'; end
if ~isfield(cfg, 'channelcolormap'), cfg.channelcolormap = [0.75 0 0;0 0 1;0 1 0;0.44 0.19 0.63;0 0.13 0.38;0.5 0.5 0.5;1 0.75 0;1 0 0;0.89 0.42 0.04;0.85 0.59 0.58;0.57 0.82 0.31;0 0.69 0.94;1 0 0.4;0 0.69 0.31;0 0.44 0.75]; end
if ~isfield(cfg, 'eegscale'), cfg.eegscale = []; end
if ~isfield(cfg, 'eogscale'), cfg.eogscale = []; end
if ~isfield(cfg, 'ecgscale'), cfg.ecgscale = []; end
if ~isfield(cfg, 'emgscale'), cfg.emgscale = []; end
if ~isfield(cfg, 'megscale'), cfg.megscale = []; end
if ~isfield(cfg, 'magscale'), cfg.magscale = []; end
if ~isfield(cfg, 'gradscale'), cfg.gradscale = []; end
if ~isfield(cfg, 'layout'), cfg.layout = []; end
if ~isfield(cfg, 'event'), cfg.event = []; end % this only exists for backward compatibility and should not be documented
if ~isfield(cfg, 'continuous'), cfg.continuous = []; end % the default is set further down in the code, conditional on the input data
if ~isfield(cfg, 'viewmode')
% butterfly, vertical, component
if hascomp
cfg.viewmode = 'component';
else
cfg.viewmode = 'butterfly';
end
end
if ~isfield(cfg, 'channel'),
if hascomp
cfg.channel = 1:10;
else
cfg.channel = 'all';
end
end
if strcmp(cfg.viewmode, 'component')
% read or create the layout that will be used for the topoplots
tmpcfg = [];
tmpcfg.layout = cfg.layout;
if isfield(data, 'grad')
tmpcfg.grad = data.grad;
elseif isfield(data, 'elec')
tmpcfg.elec = data.elec;
end
cfg.layout = ft_prepare_layout(tmpcfg);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% set the defaults and do some preparation
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if hasdata
% check if the input data is valid for this function
data = ft_checkdata(data, 'datatype', {'raw', 'comp'}, 'feedback', 'yes', 'hassampleinfo', 'yes');
% fetch the header from the data structure in memory
hdr = ft_fetch_header(data);
if isfield(data, 'cfg') && ~isempty(ft_findcfg(data.cfg, 'origfs'))
% don't use the events in case the data has been resampled
event = [];
elseif ~isempty(cfg.event)
% use the events that the user passed in the configuration
event = cfg.event;
else
% fetch the events from the data structure in memory
event = ft_fetch_event(data);
end
cfg.channel = ft_channelselection(cfg.channel, hdr.label);
chansel = match_str(data.label, cfg.channel);
Nchans = length(chansel);
if isempty(cfg.continuous)
if length(data.trial) == 1
cfg.continuous = 'yes';
else
cfg.continuous = 'no';
end
end
% this is how the input data is segmented
trlorg = zeros(numel(data.trial), 3);
trlorg(:,[1 2]) = data.sampleinfo;
% recreate offset vector (databrowser depends on this for visualisation)
for ntrl = 1:numel(data.trial)
trlorg(ntrl,3) = time2offset(data.time{ntrl}, data.fsample);
end
Ntrials = size(trlorg, 1);
else
% check if the input cfg is valid for this function
cfg = ft_checkconfig(cfg, 'dataset2files', {'yes'});
cfg = ft_checkconfig(cfg, 'required', {'headerfile', 'datafile'});
cfg = ft_checkconfig(cfg, 'renamed', {'datatype', 'continuous'});
cfg = ft_checkconfig(cfg, 'renamedval', {'continuous', 'continuous', 'yes'});
% read the header from file
hdr = ft_read_header(cfg.headerfile, 'headerformat', cfg.headerformat);
if isempty(cfg.continuous)
if hdr.nTrials==1
cfg.continuous = 'yes';
else
cfg.continuous = 'no';
end
end
if ~isempty(cfg.event)
% use the events that the user passed in the configuration
event = cfg.event;
else
% read the events from file
event = ft_read_event(cfg.dataset);
end
cfg.channel = ft_channelselection(cfg.channel, hdr.label);
chansel = match_str(hdr.label, cfg.channel);
Nchans = length(chansel);
if strcmp(cfg.continuous, 'yes')
Ntrials = 1;
else
Ntrials = hdr.nTrials;
end
% FIXME in case of continuous=yes the trl should be [1 hdr.nSamples*nTrials 0]
% and a scrollbar should be used
% construct trl-matrix for data from file on disk
trlorg = zeros(Ntrials,3);
for k = 1:Ntrials
trlorg(k,[1 2]) = [1 hdr.nSamples] + [hdr.nSamples hdr.nSamples] .* (k-1);
end
end % if hasdata
% FIXME make a check for the consistency of cfg.continous, cfg.blocksize, cfg.trl and the data header
if Nchans == 0
error('no channels to display');
end
if Ntrials == 0
error('no trials to display');
end
if ischar(cfg.selectfeature)
% ensure that it is a cell array
cfg.selectfeature = {cfg.selectfeature};
end
if ~isempty(cfg.selectfeature)
for i=1:length(cfg.selectfeature)
if ~isfield(cfg.artfctdef, cfg.selectfeature{i})
cfg.artfctdef.(cfg.selectfeature{i}) = [];
cfg.artfctdef.(cfg.selectfeature{i}).artifact = zeros(0,2);
end
end
end
% determine the vertical scaling
if ischar(cfg.ylim)
if hasdata
% the first trial is used to determine the vertical scaling
dat = data.trial{1}(chansel,:);
else
% one second of data is read from file to determine the vertical scaling
dat = ft_read_data(cfg.datafile, 'header', hdr, 'begsample', 1, 'endsample', round(hdr.Fs), 'chanindx', chansel, 'checkboundary', strcmp(cfg.continuous, 'no'), 'dataformat', cfg.dataformat, 'headerformat', cfg.headerformat);
end % if hasdata
minval = min(dat(:));
maxval = max(dat(:));
switch cfg.ylim
case 'maxabs'
cfg.ylim = [-max(abs([minval maxval])) max(abs([minval maxval]))];
case 'maxmin'
cfg.ylim = [minval maxval];
otherwise
error('unsupported value for cfg.ylim');
end % switch ylim
end
% determine coloring of channels
if hasdata
labels_all = data.label;
else
labels_all= hdr.label;
end
if size(cfg.channelcolormap,2) ~= 3
error('cfg.channelcolormap is not valid, size should be Nx3')
end
if isnumeric(cfg.colorgroups)
% groups defined by user
if length(labels_all) ~= length(cfg.colorgroups)
error('length(cfg.colorgroups) should be length(data/hdr.label)')
end
R = cfg.channelcolormap(:,1);
G = cfg.channelcolormap(:,2);
B = cfg.channelcolormap(:,3);
chancolors = [R(cfg.colorgroups(:)) G(cfg.colorgroups(:)) B(cfg.colorgroups(:))];
elseif strcmp(cfg.colorgroups, 'chantype')
type = ft_chantype(labels_all);
[tmp1 tmp2 cfg.colorgroups] = unique(type);
fprintf('%3d colorgroups were identified\n',length(tmp1))
R = cfg.channelcolormap(:,1);
G = cfg.channelcolormap(:,2);
B = cfg.channelcolormap(:,3);
chancolors = [R(cfg.colorgroups(:)) G(cfg.colorgroups(:)) B(cfg.colorgroups(:))];
elseif strcmp(cfg.colorgroups(1:9), 'labelchar')
% groups determined by xth letter of label
labelchar_num = str2double(cfg.colorgroups(10));
vec_letters = num2str(zeros(length(labels_all),1));
for iChan = 1:length(labels_all)
vec_letters(iChan) = labels_all{iChan}(labelchar_num);
end
[tmp1 tmp2 cfg.colorgroups] = unique(vec_letters);
fprintf('%3d colorgroups were identified\n',length(tmp1))
R = cfg.channelcolormap(:,1);
G = cfg.channelcolormap(:,2);
B = cfg.channelcolormap(:,3);
chancolors = [R(cfg.colorgroups(:)) G(cfg.colorgroups(:)) B(cfg.colorgroups(:))];
elseif strcmp(cfg.colorgroups, 'sequential')
% no grouping
chancolors = lines(length(labels_all));
else
error('do not understand cfg.colorgroups')
end
% collect the artifacts that have been detected from cfg.artfctdef.xxx.artifact
artlabel = fieldnames(cfg.artfctdef);
sel = zeros(size(artlabel));
artifact = cell(size(artlabel));
for i=1:length(artlabel)
sel(i) = isfield(cfg.artfctdef.(artlabel{i}), 'artifact');
if sel(i)
artifact{i} = cfg.artfctdef.(artlabel{i}).artifact;
fprintf('detected %3d %s artifacts\n', size(artifact{i}, 1), artlabel{i});
end
end
% get the subset of the artfctdef fields that seem to contain artifacts
artifact = artifact(sel==1);
artlabel = artlabel(sel==1);
if length(artlabel) > 9
error('only up to 9 artifacts groups supported')
end
% make artdata representing all artifacts in a "raw data" format
datendsample = max(trlorg(:,2));
artdata = [];
artdata.trial{1} = convert_event(artifact, 'boolvec', 'endsample', datendsample); % every artifact is a "channel"
artdata.time{1} = offset2time(0, hdr.Fs, datendsample);
artdata.label = artlabel;
artdata.fsample = hdr.Fs;
artdata.cfg.trl = [1 datendsample 0];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% set up the data structures used in the GUI
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% opt represents the global data/settings, it should contain
% - the original data, epoched or continuous
% - the artifacts represented as continuous data
% - the redraw_cb settings
% - the preproc settings
% - the select_range_cb settings (also used in keyboard_cb)
% these elements are stored inside the figure so that the callback routines can modify them
opt = [];
if hasdata
opt.orgdata = data;
else
opt.orgdata = []; % this means that it will look in cfg.dataset
end
if strcmp(cfg.continuous, 'yes')
opt.trialname = 'segment'; % this will be shown in the figure title
else
opt.trialname = 'trial'; % this will be shown in the figure title
end
opt.artdata = artdata;
opt.hdr = hdr;
opt.event = event;
opt.trlop = 1; % the active trial being displayed
opt.ftsel = find(strcmp(artlabel,cfg.selectfeature)); % current artifact/feature being selected
opt.trlorg = trlorg;
opt.fsample = hdr.Fs;
opt.artcolors = [0.9686 0.7608 0.7686; 0.7529 0.7098 0.9647; 0.7373 0.9725 0.6824;0.8118 0.8118 0.8118; 0.9725 0.6745 0.4784; 0.9765 0.9176 0.5686; 0.6863 1 1; 1 0.6863 1; 0 1 0.6000];
opt.chancolors = chancolors;
opt.cleanup = false; % this is needed for a corrent handling if the figure is closed (either in the corner or by "q")
opt.chanindx = []; % this is used to check whether the component topographies need to be redrawn
h = figure;
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% set up the figure and callbacks
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
set(h, 'KeyPressFcn', @keyboard_cb);
set(h, 'WindowButtonDownFcn', {@ft_select_range, 'multiple', false, 'xrange', true, 'yrange', false, 'clear', true, 'callback', {@select_range_cb, h}, 'event', 'WindowButtonDownFcn'});
set(h, 'WindowButtonUpFcn', {@ft_select_range, 'multiple', false, 'xrange', true, 'yrange', false, 'clear', true, 'callback', {@select_range_cb, h}, 'event', 'WindowButtonUpFcn'});
set(h, 'WindowButtonMotionFcn', {@ft_select_range, 'multiple', false, 'xrange', true, 'yrange', false, 'clear', true, 'callback', {@select_range_cb, h}, 'event', 'WindowButtonMotionFcn'});
% make the user interface elements for the data view
uicontrol('tag', 'group1', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', opt.trialname, 'userdata', 't')
uicontrol('tag', 'group2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '<', 'userdata', 'leftarrow')
uicontrol('tag', 'group2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '>', 'userdata', 'rightarrow')
uicontrol('tag', 'group1', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'channel','userdata', 'c')
uicontrol('tag', 'group2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '<', 'userdata', 'uparrow')
uicontrol('tag', 'group2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '>', 'userdata', 'downarrow')
uicontrol('tag', 'group1a', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'horizontal', 'userdata', 'h')
uicontrol('tag', 'group2a', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '-', 'userdata', 'shift+leftarrow')
uicontrol('tag', 'group2a', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '+', 'userdata', 'shift+rightarrow')
if strcmp(cfg.continuous, 'no')
ft_uilayout(h, 'tag', 'group1a', 'visible', 'off', 'retag', 'group1');
ft_uilayout(h, 'tag', 'group2a', 'visible', 'off', 'retag', 'group2');
else
ft_uilayout(h, 'tag', 'group1a', 'visible', 'on', 'retag', 'group1');
ft_uilayout(h, 'tag', 'group2a', 'visible', 'on', 'retag', 'group2');
end
uicontrol('tag', 'group1', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'vertical', 'userdata', 'v')
uicontrol('tag', 'group2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '-', 'userdata', 'shift+downarrow')
uicontrol('tag', 'group2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '+', 'userdata', 'shift+uparrow')
% legend artifacts/features
for iArt = 1:length(artlabel)
uicontrol('tag', 'group3', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', artlabel{iArt}, 'userdata', num2str(iArt), 'position', [0.91, 0.9 - ((iArt-1)*0.09), 0.08, 0.04], 'backgroundcolor', opt.artcolors(iArt,:))
uicontrol('tag', 'group3', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '<', 'userdata', ['shift+' num2str(iArt)], 'position', [0.91, 0.855 - ((iArt-1)*0.09), 0.03, 0.04], 'backgroundcolor', opt.artcolors(iArt,:))
uicontrol('tag', 'group3', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '>', 'userdata', ['control+' num2str(iArt)], 'position', [0.96, 0.855 - ((iArt-1)*0.09), 0.03, 0.04], 'backgroundcolor', opt.artcolors(iArt,:))
end
if strcmp(cfg.viewmode, 'butterfly')
% button to find label of nearest channel to datapoint
uicontrol('tag', 'group3', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'identify', 'userdata', 'i', 'position', [0.91, 0.1, 0.08, 0.05], 'backgroundcolor', [1 1 1])
end
ft_uilayout(h, 'tag', 'group1', 'width', 0.10, 'height', 0.05);
ft_uilayout(h, 'tag', 'group2', 'width', 0.05, 'height', 0.05);
ft_uilayout(h, 'tag', 'group1', 'style', 'pushbutton', 'callback', @keyboard_cb);
ft_uilayout(h, 'tag', 'group2', 'style', 'pushbutton', 'callback', @keyboard_cb);
ft_uilayout(h, 'tag', 'group3', 'style', 'pushbutton', 'callback', @keyboard_cb);
ft_uilayout(h, 'tag', 'group1', 'retag', 'viewui');
ft_uilayout(h, 'tag', 'group2', 'retag', 'viewui');
ft_uilayout(h, 'tag', 'viewui', 'BackgroundColor', [0.8 0.8 0.8], 'hpos', 'auto', 'vpos', 0);
definetrial_cb(h);
redraw_cb(h);
% %% Scrollbar
%
% % set initial scrollbar value
% dx = maxtime;
%
% % set scrollbar position
% fig_pos=get(gca,'position');
% scroll_pos=[fig_pos(1) fig_pos(2) fig_pos(3) 0.02];
%
% % define callback
% S=['set(gca,''xlim'',get(gcbo,''value'')+[ ' num2str(mintime) ',' num2str(maxtime) '])'];
%
% % Creating Uicontrol
% s=uicontrol('style','slider',...
% 'units','normalized','position',scroll_pos,...
% 'callback',S,'min',0,'max',0, ...
% 'visible', 'off'); %'value', xmin
% set initial scrollbar value
% dx = maxtime;
%
% % set scrollbar position
% fig_pos=get(gca,'position');
% scroll_pos=[fig_pos(1) fig_pos(2) fig_pos(3) 0.02];
%
% % define callback
% S=['set(gca,''xlim'',get(gcbo,''value'')+[ ' num2str(mintime) ',' num2str(maxtime) '])'];
%
% % Creating Uicontrol
% s=uicontrol('style','slider',...
% 'units','normalized','position',scroll_pos,...
% 'callback',S,'min',0,'max',0, ...
% 'visible', 'off'); %'value', xmin
%initialize postion of plot
% set(gca,'xlim',[xmin xmin+dx]);
if nargout
% wait until the user interface is closed, get the user data with the updated artifact details
set(h, 'CloseRequestFcn', @cleanup_cb);
while ishandle(h)
uiwait(h);
opt = getappdata(h, 'opt');
if opt.cleanup
delete(h);
end
end
% add the updated artifact definitions to the output cfg
for i=1:length(opt.artdata.label)
cfg.artfctdef.(opt.artdata.label{i}).artifact = convert_event(opt.artdata.trial{1}(i,:), 'artifact');
end
end % if nargout
% add version information to the configuration
cfg.version.name = mfilename('fullpath');
cfg.version.id = '$Id: ft_databrowser.m 3862 2011-07-14 13:41:01Z jorhor $';
% add information about the Matlab version used to the configuration
cfg.callinfo.matlab = version();
% add information about the function call to the configuration
cfg.callinfo.proctime = toc(ftFuncTimer);
cfg.callinfo.calltime = ftFuncClock;
cfg.callinfo.user = getusername();
% remember the configuration details of the input data
if hasdata && isfield(data, 'cfg')
cfg.previous = data.cfg;
end
end % main function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cleanup_cb(h, eventdata)
opt = getappdata(h, 'opt');
opt.cleanup = true;
setappdata(h, 'opt', opt);
uiresume
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function definetrial_cb(h, eventdata)
opt = getappdata(h, 'opt');
cfg = getappdata(h, 'cfg');
if strcmp(cfg.continuous, 'no')
% keep the original trial definition for visualisation
opt.trlvis = opt.trlorg;
else
% construct a trial definition for visualisation
if isfield(opt, 'trlvis')
thistrlbeg = opt.trlvis(opt.trlop,1);
thistrlend = opt.trlvis(opt.trlop,2);
% remember a representative sample of the current trial
% thissample = round((thistrlbeg+thistrlend)/2);
thissample = thistrlbeg;
end
% look at cfg.blocksize and make opt.trl accordingly
% if original data contains more than one trial, it will fail in ft_fetch_data
datbegsample = min(opt.trlorg(:,1));
datendsample = max(opt.trlorg(:,2));
smppertrl = round(opt.fsample * cfg.blocksize);
begsamples = datbegsample:smppertrl:datendsample;
endsamples = datbegsample+smppertrl-1:smppertrl:datendsample;
if numel(endsamples)<numel(begsamples)
endsamples(end+1) = datendsample;
end
trlvis = [];
trlvis(:,1) = begsamples';
trlvis(:,2) = endsamples';
if size(opt.trlorg,1) > 1 || isempty(opt.orgdata)
% offset is now (re)defined that 1st sample is time 0
trlvis(:,3) = begsamples-1;
else
% offset according to original time axis
trlvis(:,3) = opt.trlorg(3) + begsamples - opt.trlorg(1);
end
if isfield(opt, 'trlvis')
% update the current trial counter and try to keep the current sample the same
% opt.trlop = nearest(round((begsamples+endsamples)/2), thissample);
opt.trlop = nearest(begsamples, thissample);
end
opt.trlvis = trlvis;
end % if continuous
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function help_cb(h, eventdata)
fprintf('------------------------------------------------------------------------------------\n')
fprintf('You can use the following buttons in the data viewer\n')
fprintf('1-9 : select artifact type 1-9\n');
fprintf('shift 1-9 : select previous artifact of type 1-9\n');
fprintf('control 1-9 : select next artifact of type 1-9\n');
fprintf('alt 1-9 : select next artifact of type 1-9\n');
fprintf('arrow-left : previous trial\n');
fprintf('arrow-right : next trial\n');
fprintf('shift arrow-up : increase vertical scaling\n');
fprintf('shift arrow-down : decrease vertical scaling\n');
fprintf('shift arrow-left : increase horizontal scaling\n');
fprintf('shift arrow-down : decrease horizontal scaling\n');
fprintf('q : quit\n');
fprintf('------------------------------------------------------------------------------------\n')
fprintf('\n')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function select_range_cb(range, h) %range 1X4 in sec relative to current trial
opt = getappdata(h, 'opt');
cfg = getappdata(h, 'cfg');
% FIXME this is broken at the moment
switch cfg.viewmode
case 'butterfly'
begsample = opt.trlvis(opt.trlop,1);
endsample = opt.trlvis(opt.trlop,2);
offset = opt.trlvis(opt.trlop,3);
% determine the selection
if strcmp(opt.trialname, 'trial')
% this is appropriate when the offset is defined according to a
% different trigger in each trial, which is usually the case in trial data
begsel = round(range(1)*opt.fsample+begsample-offset-1);
endsel = round(range(2)*opt.fsample+begsample-offset);
elseif strcmp(opt.trialname, 'segment')
% this is appropriate when the offset is defined according to a
% one trigger, which is always the case in segment data [I think ingnie]
begsel = round(range(1)*opt.fsample+1);
endsel = round(range(2)*opt.fsample+1);
end
% the selection should always be confined to the current trial
begsel = max(begsample, begsel);
endsel = min(endsample, endsel);
case {'vertical', 'component'}
% the range should be in the displayed box
range(1) = max(opt.hpos-opt.width/2, range(1));
range(2) = max(opt.hpos-opt.width/2, range(2));
range(1) = min(opt.hpos+opt.width/2, range(1));
range(2) = min(opt.hpos+opt.width/2, range(2));
range = (range-(opt.hpos-opt.width/2)) / opt.width; % left side of the box becomes 0, right side becomes 1
range = range * (opt.hlim(2) - opt.hlim(1)) + opt.hlim(1); % 0 becomes hlim(1), 1 becomes hlim(2)
begsample = opt.trlvis(opt.trlop,1);
endsample = opt.trlvis(opt.trlop,2);
offset = opt.trlvis(opt.trlop,3);
% determine the selection
if strcmp(opt.trialname, 'trial')
% this is appropriate when the offset is defined according to a
% different trigger in each trial, which is usually the case in trial data
begsel = round(range(1)*opt.fsample+begsample-offset-1);
endsel = round(range(2)*opt.fsample+begsample-offset);
elseif strcmp(opt.trialname, 'segment')
% this is appropriate when the offset is defined according to
% one trigger, which is always the case in segment data [I think ingnie]
begsel = round(range(1)*opt.fsample+1);
endsel = round(range(2)*opt.fsample+1);
end
% the selection should always be confined to the current trial
begsel = max(begsample, begsel);
endsel = min(endsample, endsel);
otherwise
error('unknown cfg.viewmode "%s"', cfg.viewmode);
end % switch
if strcmp(cfg.selectmode, 'disp')
% FIXME this is only for debugging
disp([begsel endsel])
elseif strcmp(cfg.selectmode, 'mark')
% mark or unmark artifacts
artval = opt.artdata.trial{1}(opt.ftsel, begsel:endsel);
artval = any(artval,1);
if any(artval)
fprintf('there is overlap with the active artifact (%s), disable this artifact\n',opt.artdata.label{opt.ftsel});
opt.artdata.trial{1}(opt.ftsel, begsel:endsel) = 0;
else
fprintf('there is no overlap with the active artifact (%s), mark this as a new artifact\n',opt.artdata.label{opt.ftsel});
opt.artdata.trial{1}(opt.ftsel, begsel:endsel) = 1;
end
elseif strcmp(cfg.selectmode, 'eval')
% cut out the requested data segment
seldata.label = opt.curdat.label;
seldata.time{1} = offset2time(offset+begsel-begsample, opt.fsample, endsel-begsel+1);
seldata.trial{1} = ft_fetch_data(opt.curdat, 'begsample', begsel, 'endsample', endsel);
seldata.fsample = opt.fsample;
seldata.cfg.trl = [begsel endsel offset];
feval(cfg.selfun, cfg.selcfg, seldata);
else
error('unknown value for cfg.selectmode');
end
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
redraw_cb(h);
end % function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function keyboard_cb(h, eventdata)
if isempty(eventdata)
% determine the key that corresponds to the uicontrol element that was activated
key = get(h, 'userdata');
else
% determine the key that was pressed on the keyboard
key = eventdata.Key;
if ~isempty(eventdata.Modifier)
key = [eventdata.Modifier{1} '+' key];
end
end
% get focus back to figure
if ~strcmp(get(h, 'type'), 'figure')
set(h, 'enable', 'off');
drawnow;
set(h, 'enable', 'on');
end
h = getparent(h);
opt = getappdata(h, 'opt');
cfg = getappdata(h, 'cfg');
switch key
case {'1' '2' '3' '4' '5' '6' '7' '8' '9'}
% switch to another artifact type
opt.ftsel = str2double(key);
numart = size(opt.artdata.trial{1}, 1);
if opt.ftsel > numart
fprintf('data has no artifact type %i \n', opt.ftsel)
else
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
fprintf('switching to the "%s" artifact\n', opt.artdata.label{opt.ftsel});
redraw_cb(h, eventdata);
end
case {'shift+1' 'shift+2' 'shift+3' 'shift+4' 'shift+5' 'shift+6' 'shift+7' 'shift+8' 'shift+9'}
% go to previous artifact
opt.ftsel = str2double(key(end));
numart = size(opt.artdata.trial{1}, 1);
if opt.ftsel > numart
fprintf('data has no artifact type %i \n', opt.ftsel)
else
cursam = opt.trlvis(opt.trlop,1);
artsam = find(opt.artdata.trial{1}(opt.ftsel,1:cursam-1), 1, 'last');
if isempty(artsam)
fprintf('no earlier "%s" artifact found\n', opt.artdata.label{opt.ftsel});
else
fprintf('going to previous "%s" artifact\n', opt.artdata.label{opt.ftsel});
if opt.trlvis(nearest(opt.trlvis(:,1),artsam),1) < artsam
arttrl = nearest(opt.trlvis(:,1),artsam);
else
arttrl = nearest(opt.trlvis(:,1),artsam)-1;
end
opt.trlop = arttrl;
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
redraw_cb(h, eventdata);
end
end
case {'control+1' 'control+2' 'control+3' 'control+4' 'control+5' 'control+6' 'control+7' 'control+8' 'control+9' 'alt+1' 'alt+2' 'alt+3' 'alt+4' 'alt+5' 'alt+6' 'alt+7' 'alt+8' 'alt+9'}
% go to next artifact
opt.ftsel = str2double(key(end));
numart = size(opt.artdata.trial{1}, 1);
if opt.ftsel > numart
fprintf('data has no artifact type %i \n', opt.ftsel)
else
cursam = opt.trlvis(opt.trlop,2);
artsam = find(opt.artdata.trial{1}(opt.ftsel,cursam+1:end), 1, 'first') + cursam;
if isempty(artsam)
fprintf('no later "%s" artifact found\n', opt.artdata.label{opt.ftsel});
else
fprintf('going to next "%s" artifact\n', opt.artdata.label{opt.ftsel});
if opt.trlvis(nearest(opt.trlvis(:,1),artsam),1) < artsam
arttrl = nearest(opt.trlvis(:,1),artsam);
else
arttrl = nearest(opt.trlvis(:,1),artsam)-1;
end
opt.trlop = arttrl;
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
redraw_cb(h, eventdata);
end
end
case 'leftarrow'
opt.trlop = max(opt.trlop - 1, 1); % should not be smaller than 1
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
redraw_cb(h, eventdata);
case 'rightarrow'
opt.trlop = min(opt.trlop + 1, size(opt.trlvis,1)); % should not be larger than the number of trials
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
redraw_cb(h, eventdata);
case 'uparrow'
chansel = match_str(opt.hdr.label, cfg.channel);
minchan = min(chansel);
numchan = length(chansel);
chansel = minchan - numchan : minchan - 1;
if min(chansel)<1
chansel = chansel - min(chansel) + 1;
end
% convert numeric array into cell-array with channel labels
cfg.channel = opt.hdr.label(chansel);
disp(cfg.channel);
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
redraw_cb(h, eventdata);
case 'downarrow'
chansel = match_str(opt.hdr.label, cfg.channel);
maxchan = max(chansel);
numchan = length(chansel);
chansel = maxchan + 1 : maxchan + numchan;
if max(chansel)>length(opt.hdr.label)
chansel = chansel - (max(chansel) - length(opt.hdr.label));
end
% convert numeric array into cell-array with channel labels
cfg.channel = opt.hdr.label(chansel);
disp(cfg.channel);
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
redraw_cb(h, eventdata);
case 'shift+leftarrow'
cfg.blocksize = cfg.blocksize*sqrt(2);
disp(cfg.blocksize);
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
definetrial_cb(h, eventdata);
redraw_cb(h, eventdata);
case 'shift+rightarrow'
cfg.blocksize = cfg.blocksize/sqrt(2);
disp(cfg.blocksize);
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
definetrial_cb(h, eventdata);
redraw_cb(h, eventdata);
case 'shift+uparrow'
cfg.ylim = cfg.ylim/sqrt(2);
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
redraw_cb(h, eventdata);
case 'shift+downarrow'
cfg.ylim = cfg.ylim*sqrt(2);
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
redraw_cb(h, eventdata);
case 'q'
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
cleanup_cb(h);
case 't'
% select the trial to display
response = inputdlg(sprintf('%s to display', opt.trialname), 'specify', 1, {num2str(opt.trlop)});
if ~isempty(response)
opt.trlop = str2double(response);
opt.trlop = min(opt.trlop, size(opt.trlvis,1)); % should not be larger than the number of trials
opt.trlop = max(opt.trlop, 1); % should not be smaller than 1
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
redraw_cb(h, eventdata);
end
case 'h'
% select the horizontal scaling
response = inputdlg('horizontal scale', 'specify', 1, {num2str(cfg.blocksize)});
if ~isempty(response)
cfg.blocksize = str2double(response);
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
definetrial_cb(h, eventdata);
redraw_cb(h, eventdata);
end
case 'v'
% select the vertical scaling
response = inputdlg('vertical scale, [ymin ymax], ''maxabs'' or ''maxmin''', 'specify', 1, {['[ ' num2str(cfg.ylim) ' ]']});
if ~isempty(response)
response = ['[' response{1} ']']; % convert to string and add brackets, just to ensure that str2num will work
if strcmp(response, '[maxmin]')
minval = min(opt.curdat.trial{1}(:));
maxval = max(opt.curdat.trial{1}(:));
cfg.ylim = [minval maxval];
elseif strcmp(response, '[maxabs]')
minval = min(opt.curdat.trial{1}(:));
maxval = max(opt.curdat.trial{1}(:));
cfg.ylim = [-max(abs([minval maxval])) max(abs([minval maxval]))];
else
tmp = str2num(response);
if numel(tmp)==2
cfg.ylim = tmp;
else
warning('incorrect specification of cfg.ylim, not changing the limits for the vertical axes')
end
end
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
redraw_cb(h, eventdata);
end
case 'c'
% select channels
select = match_str(opt.hdr.label, cfg.channel);
select = select_channel_list(opt.hdr.label, select);
cfg.channel = opt.hdr.label(select);
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
redraw_cb(h, eventdata);
case 'i'
if strcmp(cfg.viewmode, 'butterfly')
% click in data and get name of nearest channel
fprintf('click in the figure to identify the name of the closest channel\n');
val = ginput(1);
channame = val2nearestchan(opt.curdat,val);
channb = match_str(opt.curdat.label,channame);
fprintf('channel name: %s\n',channame);
redraw_cb(h, eventdata);
ft_plot_text(val(1), 0.9*cfg.ylim(2), channame, 'FontSize', 16);
if ~ishold
hold on
plot(opt.curdat.time{1}, opt.curdat.trial{1}(channb,:),'k','LineWidth',2)
hold off
else
plot(opt.curdat.time{1}, opt.curdat.trial{1}(channb,:),'k','LineWidth',2)
end
else
warning('only supported with cfg.viewmode=''butterfly''');
end
case 'control+control'
% do nothing
case 'shift+shift'
% do nothing
case 'alt+alt'
% do nothing
otherwise
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
help_cb(h);
end
uiresume(h);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function toggle_viewmode_cb(h, eventdata, varargin)
% FIXME should be used
opt = guidata(getparent(h));
if ~isempty(varargin) && ischar(varargin{1})
cfg.viewmode = varargin{1};
end
guidata(getparent(h), opt);
redraw_cb(h);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function h = getparent(h)
p = h;
while p~=0
h = p;
p = get(h, 'parent');
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function redraw_cb(h, eventdata)
h = getparent(h);
opt = getappdata(h, 'opt');
cfg = getappdata(h, 'cfg');
figure(h); % ensure that the calling figure is in the front
fprintf('redrawing with viewmode %s\n', cfg.viewmode);
begsample = opt.trlvis(opt.trlop, 1);
endsample = opt.trlvis(opt.trlop, 2);
offset = opt.trlvis(opt.trlop, 3);
chanindx = match_str(opt.hdr.label, cfg.channel);
if ~isempty(opt.event)
% select only the events in the current time window
event = opt.event;
evtsample = [event(:).sample];
event = event(evtsample>=begsample & evtsample<=endsample);
else
event = [];
end
if isempty(opt.orgdata)
fprintf('reading data... ');
dat = ft_read_data(cfg.datafile, 'header', opt.hdr, 'begsample', begsample, 'endsample', endsample, 'chanindx', chanindx, 'checkboundary', strcmp(cfg.continuous, 'no'), 'dataformat', cfg.dataformat, 'headerformat', cfg.headerformat);
else
fprintf('fetching data... ');
dat = ft_fetch_data(opt.orgdata, 'header', opt.hdr, 'begsample', begsample, 'endsample', endsample, 'chanindx', chanindx);
end
fprintf('done\n');
fprintf('fetching artifacts... ');
art = ft_fetch_data(opt.artdata, 'begsample', begsample, 'endsample', endsample);
fprintf('done\n');
% apply preprocessing and determine the time axis
fprintf('preprocessing data... ');
[dat, lab, tim] = preproc(dat, opt.hdr.label(chanindx), opt.fsample, cfg.preproc, offset);
fprintf('done\n');
opt.curdat.label = lab;
opt.curdat.time{1} = tim;
opt.curdat.trial{1} = dat;
opt.curdat.fsample = opt.fsample;
opt.curdat.sampleinfo = [begsample endsample offset];
% apply scaling to selected channels
% using wildcard to support subselection of channels
if ~isempty(cfg.eegscale)
chansel = match_str(lab, ft_channelselection('EEG', lab));
dat(chansel,:) = dat(chansel,:) .* cfg.eegscale;
end
if ~isempty(cfg.eogscale)
chansel = match_str(lab, ft_channelselection('EOG', lab));
dat(chansel,:) = dat(chansel,:) .* cfg.eogscale;
end
if ~isempty(cfg.ecgscale)
chansel = match_str(lab, ft_channelselection('ECG', lab));
dat(chansel,:) = dat(chansel,:) .* cfg.ecgscale;
end
if ~isempty(cfg.emgscale)
chansel = match_str(lab, ft_channelselection('EMG', lab));
dat(chansel,:) = dat(chansel,:) .* cfg.emgscale;
end
if ~isempty(cfg.megscale)
chansel = match_str(lab, ft_channelselection('MEG', lab));
dat(chansel,:) = dat(chansel,:) .* cfg.megscale;
end
if ~isempty(cfg.magscale)
chansel = match_str(lab, ft_channelselection('MEGMAG', lab));
dat(chansel,:) = dat(chansel,:) .* cfg.magscale;
end
if ~isempty(cfg.gradscale)
chansel = match_str(lab, ft_channelselection('MEGGRAD', lab));
dat(chansel,:) = dat(chansel,:) .* cfg.gradscale;
end
% to assure current feature is plotted on top
ordervec = 1:length(opt.artdata.label);
ordervec(opt.ftsel) = [];
ordervec(end+1) = opt.ftsel;
% FIXME speedup ft_prepare_layout
if strcmp(cfg.viewmode, 'butterfly')
laytime = [];
laytime.label = {'dummy'};
laytime.pos = [0.5 0.5];
laytime.width = 1;
laytime.height = 1;
else
% this needs to be reconstructed if the channel selection changes
tmpcfg = [];
tmpcfg.layout = 'vertical';
tmpcfg.channel = cfg.channel;
tmpcfg.skipcomnt = 'yes';
tmpcfg.skipscale = 'yes';
laytime = ft_prepare_layout(tmpcfg, opt.orgdata);
end
% determine the position of the channel/component labels relative to the real axes
% FIXME needs a shift to the left for components
labelx = laytime.pos(:,1) - laytime.width/2 - 0.01;
labely = laytime.pos(:,2);
% determine the total extent of all virtual axes relative to the real axes
ax(1) = min(laytime.pos(:,1) - laytime.width/2);
ax(2) = max(laytime.pos(:,1) + laytime.width/2);
ax(3) = min(laytime.pos(:,2) - laytime.height/2);
ax(4) = max(laytime.pos(:,2) + laytime.height/2);
axis(ax)
% determine a single local axis that encompasses all channels
% this is in relative figure units
opt.hpos = (ax(1)+ax(2))/2;
opt.vpos = (ax(3)+ax(4))/2;
opt.width = ax(2)-ax(1);
opt.height = ax(4)-ax(3);
% these determine the scaling inside the virtual axes
% the hlim will be in seconds, the vlim will be in Tesla or Volt
opt.hlim = [tim(1) tim(end)];
opt.vlim = cfg.ylim;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fprintf('plotting artifacts...\n');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
delete(findobj(h,'tag', 'artifact'));
for j = ordervec
tmp = diff([0 art(j,:) 0]);
artbeg = find(tmp==+1);
artend = find(tmp==-1) - 1;
for k=1:numel(artbeg)
h_artifact = ft_plot_box([tim(artbeg(k)) tim(artend(k)) -1 1], 'facecolor', opt.artcolors(j,:), 'edgecolor', 'none', 'tag', 'artifact', ...
'hpos', opt.hpos, 'vpos', opt.vpos, 'width', opt.width, 'height', opt.height, 'hlim', opt.hlim, 'vlim', [-1 1]);
end
end % for each of the artifact channels
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fprintf('plotting events...\n');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
delete(findobj(h,'tag', 'event'));
for k=1:length(event)
try
eventstr = sprintf('%s=%s', event(k).type, num2str(event(k).value)); % value can be both number and string
catch
eventstr = 'unknown';
end
eventtim = (event(k).sample-begsample)/opt.fsample + opt.hlim(1);
ft_plot_line([eventtim eventtim], [-1 1], 'tag', 'event', ...
'hpos', opt.hpos, 'vpos', opt.vpos, 'width', opt.width, 'height', opt.height, 'hlim', opt.hlim, 'vlim', [-1 1]);
ft_plot_text(eventtim, 0.9, eventstr, 'tag', 'event', ...
'hpos', opt.hpos, 'vpos', opt.vpos, 'width', opt.width, 'height', opt.height, 'hlim', opt.hlim, 'vlim', [-1 1]);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fprintf('plotting data...\n');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
delete(findobj(h,'tag', 'timecourse'));
if strcmp(cfg.viewmode, 'butterfly')
set(gca,'ColorOrder',opt.chancolors(chanindx,:)) % plot vector does not clear axis, therefore this is possible
ft_plot_vector(tim, dat, 'box', false, 'tag', 'timecourse', ...
'hpos', laytime.pos(1,1), 'vpos', laytime.pos(1,2), 'width', laytime.width(1), 'height', laytime.height(1), 'hlim', opt.hlim, 'vlim', opt.vlim);
elseif any(strcmp(cfg.viewmode, {'vertical' 'component'}))
for i = 1:length(chanindx)
if strcmp(cfg.viewmode, 'component')
color = 'k';
else
color = opt.chancolors(chanindx(i),:);
end
datsel = i;
laysel = match_str(laytime.label, opt.hdr.label(chanindx(i)));
if ~isempty(datsel) && ~isempty(laysel)
ft_plot_text(labelx(laysel), labely(laysel), opt.hdr.label(chanindx(i)), 'tag', 'timecourse', 'HorizontalAlignment', 'right');
ft_plot_vector(tim, dat(datsel, :), 'box', false, 'color', color, 'tag', 'timecourse', ...
'hpos', laytime.pos(laysel,1), 'vpos', laytime.pos(laysel,2), 'width', laytime.width(laysel), 'height', laytime.height(laysel), 'hlim', opt.hlim, 'vlim', opt.vlim);
end
end
if length(chanindx)>19
% no space for xticks
yTickLabel = [];
elseif length(chanindx)> 6
% one tick per channel
set(gca, 'yTick', sort([laytime.pos(:,2)+(laytime.height(laysel)/4); laytime.pos(:,2)-(laytime.height(laysel)/4)]))
yTickLabel = {num2str(-opt.vlim(2)/2), num2str(opt.vlim(2)/2)};
else
% two ticks per channel
set(gca, 'yTick', sort([laytime.pos(:,2)+(laytime.height(laysel)/2); laytime.pos(:,2)+(laytime.height(laysel)/4); laytime.pos(:,2)-(laytime.height(laysel)/4); laytime.pos(:,2)-(laytime.height(laysel)/2)]))
yTickLabel = {num2str(-opt.vlim(2)), num2str(-opt.vlim(2)/2), num2str(opt.vlim(2)/2), num2str(opt.vlim(2))};
end
yTickLabel = repmat(yTickLabel, 1, length(chanindx));
set(gca, 'yTick', []);
set(gca, 'yTickLabel', yTickLabel)
else
error('unknown viewmode "%s"', cfg.viewmode);
end % if strcmp viewmode
nticks = 11;
xTickLabel = cellstr(num2str( linspace(tim(1), tim(end), nticks)' , '%1.2f'))';
set(gca, 'xTick', linspace(ax(1), ax(2), nticks))
set(gca, 'xTickLabel', xTickLabel)
if strcmp(cfg.viewmode, 'component')
% determine the position of each of the original channels for the topgraphy
tmpcfg = [];
tmpcfg.layout = cfg.layout;
laychan = ft_prepare_layout(tmpcfg, opt.orgdata);
% determine the position of each of the topographies
laytopo.pos(:,1) = laytime.pos(:,1) - laytime.width/2 - laytime.height*2;
laytopo.pos(:,2) = laytime.pos(:,2);
laytopo.width = laytime.height;
laytopo.height = laytime.height;
laytopo.label = laytime.label;
if ~isequal(opt.chanindx, chanindx)
opt.chanindx = chanindx;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fprintf('plotting component topographies...\n');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
delete(findobj(h,'tag', 'topography'));
[sel1, sel2] = match_str(opt.orgdata.topolabel, laychan.label);
chanx = laychan.pos(sel2,1);
chany = laychan.pos(sel2,2);
for i=1:length(chanindx)
% plot the topography of this component
laysel = match_str(laytime.label, opt.hdr.label(chanindx(i)));
chanz = opt.orgdata.topo(sel1,chanindx(i));
chanz = chanz./max(abs(chanz));
ft_plot_topo(chanx, chany, chanz, 'mask', laychan.mask, 'interplim', 'mask', 'outline', laychan.outline, 'tag', 'topography', ...
'hpos', laytopo.pos(laysel,1), 'vpos', laytopo.pos(laysel,2), 'width', laytopo.width(laysel), 'height', laytopo.height(laysel));
axis equal
drawnow
end
end % if redraw_topo
set(gca, 'yTick', [])
ax(1) = min(laytopo.pos(:,1) - laytopo.width/2);
ax(2) = max(laytime.pos(:,1) + laytime.width/2);
ax(3) = min(laytime.pos(:,2) - laytime.height/2);
ax(4) = max(laytime.pos(:,2) + laytime.height/2);
axis(ax)
end % plotting topographies
title(sprintf('%s %d, time from %g to %g s', opt.trialname, opt.trlop, tim(1), tim(end)));
xlabel('time');
fprintf('done\n');
setappdata(h, 'opt', opt);
setappdata(h, 'cfg', cfg);
end
|
github
|
philippboehmsturm/antx-master
|
ft_singleplotER.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_singleplotER.m
| 24,509 |
utf_8
|
b68b1345c22cb3b2deb537b1c49bc458
|
function [cfg] = ft_singleplotER(cfg, varargin)
% ft_singleplotER plots the event-related fields or potentials of a single channel
% or the average over multiple channels. multiple datasets can be overlayed.
%
% use as:
% ft_singleplotER(cfg, data)
% ft_singleplotER(cfg, data1, data2, ..., datan)
%
% the data can be an erp/erf produced by ft_timelockanalysis, a powerspectrum
% produced by ft_freqanalysis or a coherencespectrum produced by ft_freqdescriptives.
% if you specify multiple datasets they must contain the same channels, etc.
%
% the configuration can have the following parameters:
% cfg.xparam = field to be plotted on x-axis (default depends on data.dimord)
% 'time' or 'freq'
% cfg.zparam = field to be plotted on y-axis (default depends on data.dimord)
% 'avg', 'powspctrm' or 'cohspctrm'
% cfg.maskparameter = field in the first dataset to be used for masking of data
% (not possible for mean over multiple channels, or when input contains multiple subjects
% or trials)
% cfg.maskstyle = style used for masking of data, 'box', 'thickness' or 'saturation' (default = 'box')
% cfg.xlim = 'maxmin' or [xmin xmax] (default = 'maxmin')
% cfg.ylim = 'maxmin' or [ymin ymax] (default = 'maxmin')
% cfg.channel = nx1 cell-array with selection of channels (default = 'all'),
% see ft_channelselection for details
% cfg.refchannel = name of reference channel for visualising connectivity, can be 'gui'
% cfg.baseline = 'yes','no' or [time1 time2] (default = 'no'), see ft_timelockbaseline
% cfg.baselinetype = 'absolute' or 'relative' (default = 'absolute')
% cfg.trials = 'all' or a selection given as a 1xn vector (default = 'all')
% cfg.fontsize = font size of title (default = 8)
% cfg.hotkeys = enables hotkeys (up/down/left/right arrows) for dynamic x/y axis translation (Ctrl+) and zoom adjustment
% cfg.interactive = interactive plot 'yes' or 'no' (default = 'no')
% in a interactive plot you can select areas and produce a new
% interactive plot when a selected area is clicked. multiple areas
% can be selected by holding down the shift key.
% cfg.renderer = 'painters', 'zbuffer',' opengl' or 'none' (default = [])
% cfg.linestyle = linestyle/marker type, see options of the matlab plot function (default = '-')
% can be a single style for all datasets, or a cell-array containing one style for each dataset
% cfg.linewidth = linewidth in points (default = 0.5)
% cfg.graphcolor = color(s) used for plotting the dataset(s) (default = 'brgkywrgbkywrgbkywrgbkyw')
% alternatively, colors can be specified as nx3 matrix of rgb values
%
% to facilitate data-handling and distributed computing with the peer-to-peer
% module, this function has the following option:
% cfg.inputfile = ...
% if you specify this option the input data will be read from a *.mat
% file on disk. this mat files should contain only a single variable named 'data',
% corresponding to the input structure.
%
% see also:
% ft_singleplotTFR, ft_multiplotER, ft_multiplotTFR, ft_topoplotER, ft_topoplotTFR
% this function depends on ft_timelockbaseline which has the following options:
% cfg.baseline, documented
% cfg.channel
% cfg.baselinewindow
% cfg.previous
% cfg.version
% copyright (c) 2003-2006, ole jensen
%
% this file is part of fieldtrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% fieldtrip 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.
%
% fieldtrip 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 fieldtrip. if not, see <http://www.gnu.org/licenses/>.
%
% $id: ft_singleplotER.m 3147 2011-03-17 12:38:09z jansch $
ft_defaults
cfg = ft_checkconfig(cfg, 'trackconfig', 'on');
cfg = ft_checkconfig(cfg, 'unused', {'cohtargetchannel'});
cfg = ft_checkconfig(cfg, 'renamedval', {'zlim', 'absmax', 'maxabs'});
cfg = ft_checkconfig(cfg, 'renamedval', {'matrixside', 'feedforward', 'outflow'});
cfg = ft_checkconfig(cfg, 'renamedval', {'matrixside', 'feedback', 'inflow'});
cfg = ft_checkconfig(cfg, 'renamed', {'channelindex', 'channel'});
cfg = ft_checkconfig(cfg, 'renamed', {'channelname', 'channel'});
cfg = ft_checkconfig(cfg, 'renamed', {'cohrefchannel', 'refchannel'});
% set default for inputfile
cfg.inputfile = ft_getopt(cfg, 'inputfile', []);
hasdata = nargin>1;
hasinputfile = ~isempty(cfg.inputfile);
if hasdata && hasinputfile
error('cfg.inputfile should not be used in conjunction with giving input data to this function');
end
if hasdata
% do nothing
elseif hasinputfile
if ~ischar(cfg.inputfile)
cfg.inputfile = {cfg.inputfile};
end
for i = 1:numel(cfg.inputfile)
varargin{i} = loadvar(cfg.inputfile{i}, 'data'); % read datasets
end
if isfield(cfg, 'interactive') && strcmp(cfg.interactive, 'yes'),
warning('switching off interactive mode, this is not supported when loading an inputfile from disk');
end
end
% set the defaults:
cfg.baseline = ft_getopt(cfg, 'baseline', 'no');
cfg.trials = ft_getopt(cfg, 'trials', 'all');
cfg.xlim = ft_getopt(cfg, 'xlim', 'maxmin');
cfg.ylim = ft_getopt(cfg, 'ylim', 'maxmin');
cfg.comment = ft_getopt(cfg, 'comment', strcat([date '\n']));
cfg.axes = ft_getopt(cfg,' axes', 'yes');
cfg.fontsize = ft_getopt(cfg, 'fontsize', 8);
cfg.graphcolor = ft_getopt(cfg, 'graphcolor', 'brgkywrgbkywrgbkywrgbkyw');
cfg.hotkeys = ft_getopt(cfg, 'hotkeys', 'no');
cfg.interactive = ft_getopt(cfg, 'interactive', 'no');
cfg.renderer = ft_getopt(cfg, 'renderer', []);
cfg.maskparameter = ft_getopt(cfg, 'maskparameter',[]);
cfg.linestyle = ft_getopt(cfg, 'linestyle', '-');
cfg.linewidth = ft_getopt(cfg, 'linewidth', 0.5);
cfg.maskstyle = ft_getopt(cfg, 'maskstyle', 'box');
cfg.channel = ft_getopt(cfg, 'channel', 'all');
cfg.matrixside = ft_getopt(cfg, 'matrixside', 'outflow');
ndata = numel(varargin);
% interactive plotting is not allowed with more than 1 input
% if ndata >1 && strcmp(cfg.interactive, 'yes')
% error('interactive plotting is not supported with more than 1 input data set');
% end
%fixme rename matrixside and cohrefchannel in more meaningful options
if ischar(cfg.graphcolor)
graphcolor = ['k' cfg.graphcolor];
elseif isnumeric(cfg.graphcolor)
graphcolor = [0 0 0; cfg.graphcolor];
end
% check for linestyle being a cell-array, check it's length, and lengthen it if does not have enough styles in it
if ischar(cfg.linestyle)
cfg.linestyle = {cfg.linestyle};
end
if ndata > 1
if (length(cfg.linestyle) < ndata ) && (length(cfg.linestyle) > 1)
error('either specify cfg.linestyle as a cell-array with one cell for each dataset, or only specify one linestyle')
elseif (length(cfg.linestyle) < ndata ) && (length(cfg.linestyle) == 1)
tmpstyle = cfg.linestyle{1};
cfg.linestyle = cell(ndata , 1);
for idataset = 1:ndata
cfg.linestyle{idataset} = tmpstyle;
end
end
end
% ensure that the input is correct, also backward compatibility with old data structures:
dtype = cell(ndata , 1);
for i=1:ndata
varargin{i} = ft_checkdata(varargin{i}, 'datatype', {'timelock', 'freq'});
dtype{i} = ft_datatype(varargin{i});
% this is needed for correct treatment of graphcolor later on
if nargin>1,
if ~isempty(inputname(i+1))
iname{i+1} = inputname(i+1);
else
iname{i+1} = ['input',num2str(i,'%02d')];
end
else
iname{i+1} = cfg.inputfile{i};
end
end
if ndata >1,
if ~all(strcmp(dtype{1}, dtype))
error('input data are of different type; this is not supported');
end
end
dtype = dtype{1};
dimord = varargin{1}.dimord;
dimtok = tokenize(dimord, '_');
% set x/y/zparam defaults according to datatype and dimord
switch dtype
case 'timelock'
cfg.xparam = ft_getopt(cfg, 'xparam', 'time');
cfg.yparam = ft_getopt(cfg, 'yparam', '');
cfg.zparam = ft_getopt(cfg, 'zparam', 'avg');
case 'freq'
if sum(ismember(dimtok, 'time'))
cfg.xparam = ft_getopt(cfg, 'xparam', 'time');
cfg.yparam = ft_getopt(cfg, 'yparam', 'freq');%fixme
cfg.zparam = ft_getopt(cfg, 'zparam', 'powspctrm');
else
cfg.xparam = ft_getopt(cfg, 'xparam', 'freq');
cfg.yparam = ft_getopt(cfg, 'yparam', '');
cfg.zparam = ft_getopt(cfg, 'zparam', 'powspctrm');
end
case 'comp'
% not supported
otherwise
% not supported
end
% user specified own fields, but no yparam (which is not asked in help)
if isfield(cfg, 'xparam') && isfield(cfg, 'zparam') && ~isfield(cfg, 'yparam')
cfg.yparam = '';
end
if isfield(cfg, 'channel') && isfield(varargin{1}, 'label')
cfg.channel = ft_channelselection(cfg.channel, varargin{1}.label);
elseif isfield(cfg, 'channel') && isfield(varargin{1}, 'labelcmb')
cfg.channel = ft_channelselection(cfg.channel, unique(varargin{1}.labelcmb(:)));
end
% check whether rpt/subj is present and remove if necessary and whether
hasrpt = sum(ismember(dimtok, {'rpt' 'subj'}));
if strcmp(dtype, 'timelock') && hasrpt,
tmpcfg = [];
tmpcfg.trials = cfg.trials;
for i=1:ndata
varargin{i} = ft_timelockanalysis(tmpcfg, varargin{i});
end
dimord = varargin{1}.dimord;
dimtok = tokenize(dimord, '_');
elseif strcmp(dtype, 'freq') && hasrpt,
% this also deals with fourier-spectra in the input
% or with multiple subjects in a frequency domain stat-structure
% on the fly computation of coherence spectrum is not supported
for i=1:ndata
if isfield(varargin{i}, 'crsspctrm'),
varargin{i} = rmfield(varargin{i}, 'crsspctrm');
end
end
tmpcfg = [];
tmpcfg.trials = cfg.trials;
tmpcfg.jackknife = 'no';
for i=1:ndata
if isfield(cfg, 'zparam') && ~strcmp(cfg.zparam,'powspctrm')
% freqdesctiptives will only work on the powspctrm field
% hence a temporary copy of the data is needed
tempdata.dimord = varargin{i}.dimord;
tempdata.freq = varargin{i}.freq;
tempdata.label = varargin{i}.label;
tempdata.powspctrm = varargin{i}.(cfg.zparam);
tempdata.cfg = varargin{i}.cfg;
tempdata = ft_freqdescriptives(tmpcfg, tempdata);
varargin{i}.(cfg.zparam) = tempdata.powspctrm;
clear tempdata
else
varargin{i} = ft_freqdescriptives(tmpcfg, varargin{i});
end
end
dimord = varargin{1}.dimord;
dimtok = tokenize(dimord, '_');
end
% apply baseline correction
if ~strcmp(cfg.baseline, 'no')
for i=1:ndata
if strcmp(dtype, 'timelock') && strcmp(cfg.xparam, 'time')
varargin{i} = ft_timelockbaseline(cfg, varargin{i});
elseif strcmp(dtype, 'freq') && strcmp(cfg.xparam, 'time')
varargin{i} = ft_freqbaseline(cfg, varargin{i});
elseif strcmp(dtype, 'freq') && strcmp(cfg.xparam, 'freq')
error('baseline correction is not supported for spectra without a time dimension');
else
warning('baseline correction not applied, please set cfg.xparam');
end
end
end
% handle the bivariate case
% check for bivariate metric with 'chan_chan' in the dimord
selchan = strmatch('chan', dimtok);
isfull = length(selchan)>1;
% check for bivariate metric with a labelcmb
haslabelcmb = isfield(varargin{1}, 'labelcmb');
if (isfull || haslabelcmb) && isfield(varargin{1}, cfg.zparam)
% a reference channel is required:
if ~isfield(cfg, 'refchannel')
error('no reference channel is specified');
end
% check for refchannel being part of selection
if ~strcmp(cfg.refchannel,'gui')
if (isfull && ~any(ismember(varargin{1}.label, cfg.refchannel))) || ...
(haslabelcmb && ~any(ismember(varargin{1}.labelcmb(:), cfg.refchannel)))
error('cfg.refchannel is a not present in the (selected) channels)')
end
end
% interactively select the reference channel
if strcmp(cfg.refchannel, 'gui')
error('cfg.refchannel = ''gui'' is not supported in ft_singleplotER');
end
for i=1:ndata
if ~isfull,
% convert 2-dimensional channel matrix to a single dimension:
if isempty(cfg.matrixside)
sel1 = strmatch(cfg.refchannel, varargin{i}.labelcmb(:,2), 'exact');
sel2 = strmatch(cfg.refchannel, varargin{i}.labelcmb(:,1), 'exact');
elseif strcmp(cfg.matrixside, 'outflow')
sel1 = [];
sel2 = strmatch(cfg.refchannel, varargin{i}.labelcmb(:,1), 'exact');
elseif strcmp(cfg.matrixside, 'inflow')
sel1 = strmatch(cfg.refchannel, varargin{i}.labelcmb(:,2), 'exact');
sel2 = [];
end
fprintf('selected %d channels for %s\n', length(sel1)+length(sel2), cfg.zparam);
varargin{i}.(cfg.zparam) = varargin{i}.(cfg.zparam)([sel1;sel2],:,:);
varargin{i}.label = [varargin{i}.labelcmb(sel1,1);varargin{i}.labelcmb(sel2,2)];
varargin{i}.labelcmb = varargin{i}.labelcmb([sel1;sel2],:);
varargin{i} = rmfield(varargin{i}, 'labelcmb');
else
% general case
sel = match_str(varargin{i}.label, cfg.refchannel);
siz = [size(varargin{i}.(cfg.zparam)) 1];
if strcmp(cfg.matrixside, 'inflow') || isempty(cfg.matrixside)
%the interpretation of 'inflow' and 'outflow' depend on
%the definition in the bivariate representation of the data
%data.(cfg.zparam) = reshape(mean(data.(cfg.zparam)(:,sel,:),2),[siz(1) 1 siz(3:end)]);
sel1 = 1:siz(1);
sel2 = sel;
meandir = 2;
elseif strcmp(cfg.matrixside, 'outflow')
%data.(cfg.zparam) = reshape(mean(data.(cfg.zparam)(sel,:,:),1),[siz(1) 1 siz(3:end)]);
sel1 = sel;
sel2 = 1:siz(1);
meandir = 1;
elseif strcmp(cfg.matrixside, 'ff-fd')
error('cfg.matrixside = ''ff-fd'' is not supported anymore, you have to manually subtract the two before the call to ft_topoplotER');
elseif strcmp(cfg.matrixside, 'fd-ff')
error('cfg.matrixside = ''fd-ff'' is not supported anymore, you have to manually subtract the two before the call to ft_topoplotER');
end %if matrixside
end %if ~isfull
end %for i
end %handle the bivariate data
% get physical min/max range of x
if strcmp(cfg.xlim,'maxmin')
% find maxmin throughout all varargins:
xmin = [];
xmax = [];
for i=1:ndata
xmin = min([xmin varargin{i}.(cfg.xparam)]);
xmax = max([xmax varargin{i}.(cfg.xparam)]);
end
else
xmin = cfg.xlim(1);
xmax = cfg.xlim(2);
end
% get the index of the nearest bin
for i=1:ndata
xidmin(i,1) = nearest(varargin{i}.(cfg.xparam), xmin);
xidmax(i,1) = nearest(varargin{i}.(cfg.xparam), xmax);
end
%fixme do something with yparam here
%technically should not be defined for multiplotER, but can be defined (and
%use ft_selectdata to average across frequencies
cla
hold on;
colorlabels = [];
% plot each data set:
for i=1:ndata
if isfield(varargin{1}, 'label')
selchannel = ft_channelselection(cfg.channel, varargin{i}.label);
elseif isfield(varargin{1}, 'labelcmb')
selchannel = ft_channelselection(cfg.channel, unique(varargin{i}.labelcmb(:)));
else
error('the input data does not contain a label or labelcmb-field');
end
% make vector dat with one value for each channel
dat = varargin{i}.(cfg.zparam);
xparam = varargin{i}.(cfg.xparam);
% take subselection of channels
% this works for bivariate data with labelcmb because at this point the
% data has a label-field
sellab = match_str(varargin{i}.label, selchannel);
if ~isempty(cfg.yparam)
if isfull
dat = dat(sel1, sel2, ymin:ymax, xidmin(i):xidmax(i));
dat = nanmean(nanmean(dat, meandir), 3);
siz = size(dat);
%fixmedat = reshape(dat, [siz(1:2) siz(4)]);
dat = reshape(dat, [siz(1) siz(3)]);
dat = dat(sellab, :);
elseif haslabelcmb
dat = dat(sellab, ymin:ymax, xidmin(i):xidmax(i));
dat = nanmean(dat, 2);
siz = size(dat);
dat = reshape(dat, [siz(1) siz(3)]);
else
dat = dat(sellab, ymin:ymax, xidmin(i):xidmax(i));
dat = nanmean(nanmean(dat, 3), 2);
siz = size(dat);
dat = reshape(dat, [siz(1) siz(3)]);
end
else
if isfull
dat = dat(sel1, sel2, xidmin(i):xidmax(i));
dat = nanmean(dat, meandir);
siz = size(dat);
siz(find(siz(1:2)==1)) = [];
dat = reshape(dat, siz);
dat = dat(sellab, :);
elseif haslabelcmb
dat = dat(sellab, xidmin(i):xidmax(i));
else
dat = dat(sellab, xidmin(i):xidmax(i));
end
end
xvector = xparam(xidmin(i):xidmax(i));
datavector = reshape(mean(dat, 1), [1 numel(xvector)]); % average over channels
% make mask
if ~isempty(cfg.maskparameter)
datmask = varargin{1}.(cfg.maskparameter)(sellab,:);
datmask = datmask(xidmin(i):xidmax(i));
maskdatavector = reshape(mean(datmask,1), [1 numel(xvector)]);
else
maskdatavector = [];
end
if ndata > 1
if ischar(graphcolor); colorlabels = [colorlabels iname{i+1} '=' graphcolor(i+1) '\n'];
elseif isnumeric(graphcolor); colorlabels = [colorlabels iname{i+1} '=' num2str(graphcolor(i+1,:)) '\n'];
end
end
if ischar(graphcolor); color = graphcolor(i+1);
elseif isnumeric(graphcolor); color = graphcolor(i+1,:);
end
% update ymin and ymax for the current data set:
if strcmp(cfg.ylim,'maxmin')
if i==1
ymin = [];
ymax = [];
end
% select the channels in the data that match with the layout:
ymin = min([ymin min(datavector)]);
ymax = max([ymax max(datavector)]);
else
ymin = cfg.ylim(1);
ymax = cfg.ylim(2);
end
% only plot the mask once, for the first line (it's the same anyway for
% all lines, and if plotted multiple times, it will overlay the others
if i>1 && strcmp(cfg.maskstyle, 'box')
ft_plot_vector(xvector, datavector, 'style', cfg.linestyle{i}, 'color', color, ...
'linewidth', cfg.linewidth, 'hlim', cfg.xlim, 'vlim', cfg.ylim);
else
ft_plot_vector(xvector, datavector, 'style', cfg.linestyle{i}, 'color', color, ...
'highlight', maskdatavector, 'highlightstyle', cfg.maskstyle, 'linewidth', cfg.linewidth, ...
'hlim', cfg.xlim, 'vlim', cfg.ylim);
end
end
% set xlim and ylim:
xlim([xmin xmax]);
ylim([ymin ymax]);
% adjust mask box extents to ymin/ymax
ptchs = findobj(gcf,'type','patch');
for i = 1:length(ptchs)
YData = get(ptchs(i),'YData');
YData(YData == min(YData)) = ymin;
YData(YData == max(YData)) = ymax;
set(ptchs(i),'YData',YData);
end
if strcmp('yes',cfg.hotkeys)
% attach data and cfg to figure and attach a key listener to the figure
set(gcf, 'keypressfcn', {@key_sub, xmin, xmax, ymin, ymax})
end
% make the figure interactive
if strcmp(cfg.interactive, 'yes')
set(gcf, 'windowbuttonupfcn', {@ft_select_range, 'multiple', false, 'yrange', false, 'callback', {@select_topoplotER, cfg, varargin{:}}, 'event', 'windowbuttonupfcn'});
set(gcf, 'windowbuttondownfcn', {@ft_select_range, 'multiple', false, 'yrange', false, 'callback', {@select_topoplotER, cfg, varargin{:}}, 'event', 'windowbuttondownfcn'});
set(gcf, 'windowbuttonmotionfcn', {@ft_select_range, 'multiple', false, 'yrange', false, 'callback', {@select_topoplotER, cfg, varargin{:}}, 'event', 'windowbuttonmotionfcn'});
end
% create title text containing channel name(s) and channel number(s):
if length(sellab) == 1
t = [char(cfg.channel) ' / ' num2str(sellab) ];
else
t = sprintf('mean(%0s)', join(',', cfg.channel));
end
h = title(t,'fontsize', cfg.fontsize);
% set renderer if specified
if ~isempty(cfg.renderer)
set(gcf, 'renderer', cfg.renderer)
end
% get the output cfg
cfg = ft_checkconfig(cfg, 'trackconfig', 'off', 'checksize', 'yes');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% subfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function t = join(separator,cells)
if isempty(cells)
t = '';
return;
end
t = char(cells{1});
for i=2:length(cells)
t = [t separator char(cells{i})];
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% subfunction which is called by ft_select_channel in case cfg.refchannel='gui'
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function select_singleplotER(label, cfg, varargin)
cfg.refchannel = label;
fprintf('selected cfg.refchannel = ''%s''\n', cfg.refchannel);
p = get(gcf, 'position');
f = figure;
set(f, 'position', p);
ft_singleplotER(cfg, varargin{:});
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% subfunction which is called after selecting a time range
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function select_topoplotER(range, cfg, varargin)
cfg.comment = 'auto';
cfg.yparam = [];
cfg.xlim = range(1:2);
if isfield(cfg, 'showlabels')
% this is not allowed in topoplotER
cfg = rmfield(cfg, 'showlabels');
end
fprintf('selected cfg.xlim = [%f %f]\n', cfg.xlim(1), cfg.xlim(2));
p = get(gcf, 'position');
f = figure;
set(f, 'position', p);
ft_topoplotER(cfg, varargin{:});
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% subfunction which handles hot keys in the current plot
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function key_sub(handle, eventdata, varargin)
xlimits = xlim;
ylimits = ylim;
incr_x = abs(xlimits(2) - xlimits(1)) /10;
incr_y = abs(ylimits(2) - ylimits(1)) /10;
% TRANSLATE by 10%
if length(eventdata.Modifier) == 1 && strcmp(eventdata.Modifier{:},'control') && strcmp(eventdata.Key,'leftarrow')
xlim([xlimits(1)+incr_x xlimits(2)+incr_x])
elseif length(eventdata.Modifier) == 1 && strcmp(eventdata.Modifier{:},'control') && strcmp(eventdata.Key,'rightarrow')
xlim([xlimits(1)-incr_x xlimits(2)-incr_x])
elseif length(eventdata.Modifier) == 1 && strcmp(eventdata.Modifier{:},'control') && strcmp(eventdata.Key,'uparrow')
ylim([ylimits(1)-incr_y ylimits(2)-incr_y])
elseif length(eventdata.Modifier) == 1 && strcmp(eventdata.Modifier{:},'control') && strcmp(eventdata.Key,'downarrow')
ylim([ylimits(1)+incr_y ylimits(2)+incr_y])
% ZOOM by 10%
elseif strcmp(eventdata.Key,'leftarrow')
xlim([xlimits(1)-incr_x xlimits(2)+incr_x])
elseif strcmp(eventdata.Key,'rightarrow')
xlim([xlimits(1)+incr_x xlimits(2)-incr_x])
elseif strcmp(eventdata.Key,'uparrow')
ylim([ylimits(1)-incr_y ylimits(2)+incr_y])
elseif strcmp(eventdata.Key,'downarrow')
ylim([ylimits(1)+incr_y ylimits(2)-incr_y])
% resort to minmax of data for x-axis and y-axis
elseif strcmp(eventdata.Key,'m')
xlim([varargin{1} varargin{2}])
ylim([varargin{3} varargin{4}])
end
|
github
|
philippboehmsturm/antx-master
|
ft_spikesimulation.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_spikesimulation.m
| 4,954 |
utf_8
|
f336f0a180f84b0a80ef24d6bd862640
|
function data = ft_spikesimulation(cfg)
% FT_SPIKESIMULATION
%
% Use as
% data = ft_spikesimulation(cfg)
% and please look in the code for the cfg details.
%
% See also FT_DIPOLESIMULATION, FT_FREQSIMULATION
% Copyright (C) 2007, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_spikesimulation.m 3710 2011-06-16 14:04:19Z eelspa $
ft_defaults
% record start time and total processing time
ftFuncTimer = tic();
ftFuncClock = clock();
% set the defaults
if ~isfield(cfg, 'trlduration'), cfg.trlduration = 1; end % in seconds
if ~isfield(cfg, 'nlfpchan'), cfg.nlfpchan = 10; end
if ~isfield(cfg, 'nspikechan'), cfg.nspikechan = 10; end
if ~isfield(cfg, 'spikerate'), cfg.spikerate = ones(cfg.nspikechan,1)*10; end
if ~isfield(cfg, 'ntrial'), cfg.ntrial = 10; end
if ~isfield(cfg, 'bpfreq'), cfg.bpfreq = [40 80]; end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% define the parameters
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% cfg.spikerate = [ 10 50 100 200];
% cfg.nspikechan = 4;
% nlfpchan = 2;
% cfg.ntrial = 10;
% cfg.bpfreq = [40 80];
% cfg.trlduration = 1;
spikemix = eye(cfg.nspikechan, cfg.nlfpchan);
spikemix(5,1:2) = [0.5 0.5]; % mix with lfp chan 1 and 2
spikemix(6,1:2) = [0.5 0.5]; % mix with lfp chan 1 and 2
% cfg.spikerate = 100*ones(1,cfg.nspikechan); % for each channel, per second
% cfg.spikerate = [100 100 300 300 100 300];
fsample = 1000;
nsample = cfg.trlduration*fsample;
nchan = cfg.nlfpchan + cfg.nspikechan;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% create the data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% start with empty data
data = [];
data.fsample = fsample;
% create channel labels
k = 1;
for i=1:cfg.nlfpchan, data.label{k} = sprintf('lfp%02d', i); k=k+1; end
for i=1:cfg.nspikechan, data.label{k} = sprintf('spike%02d', i); k=k+1; end
data.label = data.label(:);
for t=1:cfg.ntrial
fprintf('creating trial %d\n', t);
data.time{t} = (1:nsample)./fsample;
lfp = zeros(cfg.nlfpchan, nsample);
spike = zeros(cfg.nspikechan, nsample);
for i=1:cfg.nlfpchan,
lfp(i,:) = ft_preproc_bandpassfilter(randn(1,nsample), fsample, cfg.bpfreq);
end
for i=1:cfg.nspikechan
% the spikes are generated from a probabilistic mix of the LFP channels
x = spikemix(i,:) * lfp;
% apply a non-linear mapping to the spike probablility, output should be defined between 0 and 1
x = mapping(x);
% normalize the total probability to one
x = x./sum(x);
% randomly assign the spikes over the time series
spike(i,:) = ((cfg.spikerate(i)*nsample/fsample)*x)>=rand(size(x));
end
data.time{t} = (1:nsample)./fsample;
data.trial{t} = [lfp; spike];
clear lfp spike
end
% add the version details of this function call to the configuration
cfg.version.name = mfilename('fullpath');
cfg.version.id = '$Id: ft_spikesimulation.m 3710 2011-06-16 14:04:19Z eelspa $';
% add information about the Matlab version used to the configuration
cfg.callinfo.matlab = version();
% add information about the function call to the configuration
cfg.callinfo.proctime = toc(ftFuncTimer);
cfg.callinfo.calltime = ftFuncClock;
cfg.callinfo.user = getusername();
% remember the configuration details
data.cfg = cfg;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION to strengthen the temporal strucure in the spike train
% by a non-linear modulation of the spike probability
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function y = mapping(x)
x = 6*(x-mean(x))/std(x);
y = 1./(1+exp(-x));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% IIRFILTER simple brick wall filter in the frequency domain
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function s = myiirfilter(s, fs, fb, a)
f = fft(s);
ax = linspace(0, fs, length(s));
fl = nearest(ax, fb(1))-1;
fh = nearest(ax, fb(2))+1;
f(1:fl) = a.*f(1:fl);
f(fh:end) = a.*f(fh:end);
s = real(ifft(f));
|
github
|
philippboehmsturm/antx-master
|
ft_analysisprotocol.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_analysisprotocol.m
| 11,770 |
utf_8
|
3969ed9e334c7c7690a1581f8466046d
|
function [script, details] = ft_analysisprotocol(cfg, datacfg)
% FT_ANALYSISPROTOCOL tries to reconstruct the complete analysis protocol that
% was used to create an arbitrary FieldTrip data structure. It will create
% a Matlab script (as text file) and a flowchart with a graphical
% representation.
%
% Use as
% ft_analysisprotocol(cfg, data)
%
% where the first cfg input contains the settings that apply to the
% behaviour of this particular function and the second data input argument
% can be the output of any FieldTrip function, e.g. FT_PREPROCESSING,
% FT_TIMELOCKANALYSIS, FT_SOURCEANALYSIS, FT_FREQSTATISTICS or whatever you like.
%
% Alternatively, for the second input argument you can also only give the
% configuration of the processed data (i.e. "data.cfg") instead of the full
% data.
%
% The configuration options that apply to the behaviour of this function are
% cfg.feedback = 'no', 'text', 'gui' or 'yes', whether text and/or
% graphical feedback should be presented (default = 'yes')
% cfg.filename = string, filename of m-file to which the script will be
% written (default = [])
% cfg.remove = cell-array with strings, determines which objects will
% be removed from the configuration prior to writing it to
% file. For readibility of the script, you may want to
% remove the large objectssuch as event structure, trial
% definition, source positions
% cfg.keepremoved = 'yes' or 'no', determines whether removed fields are
% completely removed, or only replaced by a short textual
% description (default = 'no')
%
% This function uses the nested cfg and cfg.previous that are present in
% the data structure. It will use the configuration and the nested previous
% configurations to climb all the way back into the tree. This funtction
% will print a complete Matlab script to screen (and optionally to file).
% Furthermore, it will show an interactive graphical flowchart
% representation of the steps taken during the analysis. In the flowchart
% you can click on one of the steps to see the configuration details of
% that step.
%
% Note that the nested cfg and cfg.previous in your data might not contain
% all details that are required to reconstruct a complete and valid
% analysis script.
% TODO the output of this function can perhaps be used as input for the wizard function
% Copyright (C) 2006-2009, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_analysisprotocol.m 2439 2010-12-15 16:33:34Z johzum $
persistent depth % this corresponds to the vertical direction in the figure
persistent branch % this corresponds to the horizontal direction in the figure
persistent parent
persistent info
ft_defaults
% set the defaults
if ~isfield(cfg, 'filename'), cfg.filename = []; end
if ~isfield(cfg, 'keepremoved'), cfg.keepremoved = 'no'; end
if ~isfield(cfg, 'feedback'), cfg.feedback = 'yes'; end
if ~isfield(cfg, 'remove')
% this is the default list of configuration elements to be removed. These
% elements would be very large to print and make the script difficult to
% read. To get a correctly behaving script, you may have to change this.
cfg.remove = {
'sgncmb'
'channelcmb'
'event'
'trl'
'trlold'
'artfctdef.eog.trl'
'artfctdef.jump.trl'
'artfctdef.muscle.trl'
'pos'
'inside'
'outside'
'grid.pos'
'grid.inside'
'grid.outside'
'version.name'
'version.id'
'vol.bnd.pnt'
'vol.bnd.tri'
};
end
feedbackgui = strcmp(cfg.feedback, 'gui') || strcmp(cfg.feedback, 'yes');
feedbacktext = strcmp(cfg.feedback, 'text') || strcmp(cfg.feedback, 'yes');
% we are only interested in the cfg-part of the data
if isfield(datacfg, 'cfg')
datacfg = datacfg.cfg;
end
% set up the persistent variables
if isempty(depth), depth = 1; end
if isempty(branch), branch = 1; end
% start with an empty script
script = '';
% get the function call details before they are removed
try
thisname = getsubfield(datacfg, 'version.name');
if isstruct(thisname)
% I think that this was needed for Matlab 6.5
thisname = thisname.name;
end
[p, f] = fileparts(thisname);
thisname = f;
catch
thisname = 'unknown';
end
try
thisid = getsubfield(datacfg, 'version.id');
catch
thisid = 'unknown';
end
if feedbacktext
% give some feedback on screen
fprintf('\n');
fprintf('recursion depth = %d, branch = %d\n', depth, branch);
disp(thisname)
disp(thisid)
end
% remove the fields that are too large or not interesting
for i=1:length(cfg.remove)
if issubfield(datacfg, cfg.remove{i})
if feedbacktext
fprintf('removing %s\n', cfg.remove{i});
end
siz = size(getsubfield(datacfg, cfg.remove{i}));
if strcmp(cfg.keepremoved, 'yes')
% keep the field, but replace the value with a descriptive string
datacfg = setsubfield(datacfg, cfg.remove{i}, sprintf('empty - this was cleared by analysisprotocol, original size = [%s]', num2str(siz)));
else
datacfg = rmsubfield(datacfg, cfg.remove{i});
end
end
end
% convert this part of the configuration to a matlab script
if isfield(datacfg, 'previous')
thiscfg = rmfield(datacfg, 'previous');
else
thiscfg = datacfg;
end
code = printstruct('cfg', thiscfg);
nl = sprintf('\n');
emptycfg = sprintf('cfg = [];\n');
sep = sprintf('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
head1 = sprintf('%% version name = %s\n', thisname);
head2 = sprintf('%% version id = %s\n', thisid);
thisscript = [nl sep head1 head2 sep emptycfg code nl];
% remember this part of the configuration info
info(branch,depth).name = thisname;
info(branch,depth).id = thisid;
info(branch,depth).cfg = thiscfg;
info(branch,depth).script = thisscript;
info(branch,depth).this = [branch depth];
info(branch,depth).parent = parent;
info(branch,depth).children = {}; % this will be determined later
if isfield(datacfg, 'previous')
prev = parent;
parent = [branch depth]; % this will be used in the recursive call
if isstruct(datacfg.previous)
% increment the depth counter
depth = depth + 1;
% use recursion to parse the previous section of the tree
ft_analysisprotocol(cfg, datacfg.previous);
elseif iscell(datacfg.previous)
for i=1:length(datacfg.previous(:))
% increment the branch counter
branch = branch + (i>1);
% increment the depth counter
depth = depth + 1;
% use recursion to parse each previous section of the tree
ft_analysisprotocol(cfg, datacfg.previous{i});
end
end
% revert to the orignal parent
parent = prev;
end
if depth==1
% the recursion has finished, we are again at the top level
% the parents were determined while climbing up the tree
% now it is time to descend and determine the children
for branch=1:size(info,1)
for depth=1:size(info,2)
if ~isempty(info(branch, depth).parent)
parentbranch = info(branch, depth).parent(1);
parentdepth = info(branch, depth).parent(2);
info(parentbranch, parentdepth).children{end+1} = [branch depth];
end
end
end
% complement the individual scripts with the input and output variables
% and the actual function call
for branch=1:size(info,1)
for depth=1:size(info,2)
outputvar = sprintf('var_%d_%d', info(branch, depth).this);
inputvar = '';
commandline = sprintf('%s = %s(cfg%s);', outputvar, info(branch, depth).name, inputvar);
disp(commandline);
end
end
if nargout>0
% return the complete script as output argument
script = '';
for branch=1:size(info,1)
for depth=1:size(info,2)
script = [info(branch,depth).script script];
end
end
end
if nargout>1
% return the information details as output argument
details = info;
end
if feedbackgui
fig = figure;
hold on
% the axis should not change during the contruction of the arrows,
% otherwise the arrowheads will be distorted
axis manual;
for branch=1:size(info,1)
for depth=1:size(info,2)
plotinfo(info(branch,depth));
end
end
axis auto
axis off
guidata(fig,info);
set(fig, 'WindowButtonUpFcn', @button);
set(fig, 'KeyPressFcn', @key);
end % feedbackgui
if ~isempty(cfg.filename)
% write the complete script to file
fprintf('writing result to file ''%s''\n', cfg.filename);
fid = fopen(cfg.filename, 'wb');
fprintf(fid, '%s', script);
fclose(fid);
end
% clear all persistent variables
depth = [];
branch = [];
info = [];
parent = [];
fig = [];
else
% this level of recursion has finished, decrease the depth
depth = depth - 1;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function plotinfo(element)
if isempty(element.name)
return
end
w = 0.6;
h = 0.3;
% create the 4 courners that can be used as patch
x = [-w/2 w/2 w/2 -w/2];
y = [-h/2 -h/2 h/2 h/2];
% close the patch
x = [x x(end)];
y = [y y(end)];
% move the patch to the desired location
x = element.this(1) + x;
y = element.this(2) + y;
p = patch(x', y', 0);
set(p, 'Facecolor', [1 1 0.6])
label{1} = element.name;
% label{2} = num2str(element.this);
l = text(element.this(1), element.this(2), label);
set(l, 'HorizontalAlignment', 'center')
set(l, 'interpreter', 'none')
set(l, 'fontUnits', 'normalized')
set(l, 'fontSize', 0.03)
% set(l, 'fontName', 'courier')
% draw an arrow to connect this box to its parent
if ~isempty(element.parent)
base = element.this - [0 h/2];
tip = element.parent + [0 h/2];
% ARROW(Start,Stop,Length,BaseAngle,TipAngle,Width,Page,CrossDir)
arrow(base, tip, [], [], [], [], [], []);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function varargout = key(h, eventdata, handles, varargin)
% this is just a placeholder for future functionality
% at the moment it does not do anything
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function varargout = button(h, eventdata, handles, varargin)
pos = get(get(gcbo, 'CurrentAxes'), 'CurrentPoint');
x = pos(1,1);
y = pos(1,2);
info = guidata(h);
dist = zeros(size(info)) + inf;
for i=1:numel(info)
if ~isempty(info(i).this)
dist(i) = norm(info(i).this - [x y]);
end
end
% determine the box that is nearest by the mouse click
[m, indx] = min(dist(:));
% show the information contained in that box
uidisplaytext(info(indx).script, info(indx).name);
|
github
|
philippboehmsturm/antx-master
|
ft_mvaranalysis.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_mvaranalysis.m
| 19,679 |
utf_8
|
f71777fe8c5f884fd1d2671943107b3c
|
function [mvardata] = ft_mvaranalysis(cfg, data)
% FT_MVARANALYSIS performs multivariate autoregressive modeling on
% time series data over multiple trials.
%
% Use as
% [mvardata] = ft_mvaranalysis(cfg, data)
%
% The input data should be organised in a structure as obtained from
% the FT_PREPROCESSING function. The configuration depends on the type
% of computation that you want to perform.
% The output is a data structure of datatype 'mvar' which contains the
% multivariate autoregressive coefficients in the field coeffs, and the
% covariance of the residuals in the field noisecov.
%
% The configuration should contain:
% cfg.toolbox = the name of the toolbox containing the function for the
% actual computation of the ar-coefficients
% this can be 'biosig' (default) or 'bsmart'
% you should have a copy of the specified toolbox in order
% to use mvaranalysis (both can be downloaded directly).
% cfg.mvarmethod = scalar (only required when cfg.toolbox = 'biosig').
% default is 2, relates to the algorithm used for the
% computation of the AR-coefficients by mvar.m
% cfg.order = scalar, order of the autoregressive model (default=10)
% cfg.channel = 'all' (default) or list of channels for which an mvar model
% is fitted. (Do NOT specify if cfg.channelcmb is
% defined)
% cfg.channelcmb = specify channel combinations as a
% two-column cell array with channels in each column between
% which a bivariate model will be fit (overrides
% cfg.channel)
% cfg.keeptrials = 'no' (default) or 'yes' specifies whether the coefficients
% are estimated for each trial seperately, or on the
% concatenated data
% cfg.jackknife = 'no' (default) or 'yes' specifies whether the coefficients
% are estimated for all leave-one-out sets of trials
% cfg.zscore = 'no' (default) or 'yes' specifies whether the channel data
% are z-transformed prior to the model fit. This may be
% necessary if the magnitude of the signals is very different
% e.g. when fitting a model to combined MEG/EMG data
% cfg.demean = 'yes' (default) or 'no' explicit removal of DC-offset
% cfg.ems = 'no' (default) or 'yes' explicit removal ensemble mean
%
% ft_mvaranalysis can be used to obtain one set of coefficients for
% the whole common time axis defined in the data. It will throw an error
% if the trials are of variable length, or if the time axes of the trials
% are not equal to one another.
%
% ft_mvaranalysis can be also used to obtain time-dependent sets of
% coefficients based on a sliding window. In this case the input cfg
% should contain:
%
% cfg.t_ftimwin = the width of the sliding window on which the coefficients
% are estimated
% cfg.toi = [t1 t2 ... tx] the time points at which the windows are
% centered
%
% To facilitate data-handling and distributed computing with the peer-to-peer
% module, this function has the following options:
% cfg.inputfile = ...
% cfg.outputfile = ...
% If you specify one of these (or both) the input data will be read from a *.mat
% file on disk and/or the output data will be written to a *.mat file. These mat
% files should contain only a single variable, corresponding with the
% input/output structure.
% Undocumented local options:
% cfg.keeptapers
% cfg.taper
% Copyright (C) 2009, Jan-Mathijs Schoffelen
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_mvaranalysis.m 3766 2011-07-04 10:44:39Z eelspa $
% record start time and total processing time
ftFuncTimer = tic();
ftFuncClock = clock();
cfg = ft_checkconfig(cfg, 'trackconfig', 'on');
cfg = ft_checkconfig(cfg, 'renamed', {'blc', 'demean'});
cfg = ft_checkconfig(cfg, 'renamed', {'blcwindow', 'baselinewindow'});
% set default configurations
if ~isfield(cfg, 'toolbox'), cfg.toolbox = 'biosig'; end
if ~isfield(cfg, 'mvarmethod'), cfg.mvarmethod = 2; end
if ~isfield(cfg, 'order'), cfg.order = 10; end
if ~isfield(cfg, 'channel'), cfg.channel = 'all'; end
if ~isfield(cfg, 'keeptrials'), cfg.keeptrials = 'no'; end
if ~isfield(cfg, 'jackknife'), cfg.jackknife = 'no'; end
if ~isfield(cfg, 'zscore'), cfg.zscore = 'no'; end
if ~isfield(cfg, 'feedback'), cfg.feedback = 'textbar'; end
if ~isfield(cfg, 'demean'), cfg.demean = 'yes'; end
if ~isfield(cfg, 'ems'), cfg.ems = 'no'; end
if ~isfield(cfg, 'toi'), cfg.toi = []; end
if ~isfield(cfg, 't_ftimwin'), cfg.t_ftimwin = []; end
if ~isfield(cfg, 'keeptapers'), cfg.keeptapers = 'yes'; end
if ~isfield(cfg, 'taper'), cfg.taper = 'rectwin'; end
if ~isfield(cfg, 'inputfile'), cfg.inputfile = []; end
if ~isfield(cfg, 'outputfile'), cfg.outputfile = []; end
%check whether the requested toolbox is present
switch cfg.toolbox
case 'biosig'
ft_hastoolbox('biosig', 1);
nnans = cfg.order;
case 'bsmart'
ft_hastoolbox('bsmart', 1);
nnans = 0;
otherwise
error('toolbox %s is not yet supported', cfg.toolbox);
end
%check that cfg.channel and cfg.channelcmb are not both specified
if ~any(strcmp(cfg.channel, 'all')) && isfield(cfg, 'channelcmb')
warning('cfg.channelcmb defined, overriding cfg.channel setting and computing over bivariate pairs');
end
% load optional given inputfile as data
hasdata = (nargin>1);
if ~isempty(cfg.inputfile)
% the input data should be read from file
if hasdata
error('cfg.inputfile should not be used in conjunction with giving input data to this function');
else
data = loadvar(cfg.inputfile, 'data');
end
end
%check the input-data
data = ft_checkdata(data, 'datatype', 'raw', 'hassampleinfo', 'yes');
%check configurations
switch cfg.toolbox
case 'biosig'
cfg = ft_checkconfig(cfg, 'required', 'mvarmethod');
case 'bsmart'
%nothing extra required
end
if isempty(cfg.toi) && isempty(cfg.t_ftimwin)
%fit model to entire data segment
ok = 1;
for k = 1:numel(data.trial)
%if any(data.time{k}~=data.time{1}),
if size(data.trial{k},2) ~= size(data.trial{1},2)
ok = 0;
break
end
end
if ~ok
error('time axes of all trials should be identical');
else
cfg.toi = mean(data.time{1}([1 end])) + 0.5/data.fsample;
cfg.t_ftimwin = data.time{1}(end)-data.time{1}(1) + 1/data.fsample;
end
elseif ~isempty(cfg.toi) && ~isempty(cfg.t_ftimwin)
%do sliding window approach
else
error('cfg should contain both cfg.toi and cfg.t_ftimwin');
end
cfg.channel = ft_channelselection(cfg.channel, data.label);
keeprpt = strcmp(cfg.keeptrials, 'yes');
keeptap = strcmp(cfg.keeptapers, 'yes');
dojack = strcmp(cfg.jackknife, 'yes');
dozscore = strcmp(cfg.zscore, 'yes');
dobvar = isfield(cfg, 'channelcmb');
if ~keeptap, error('not keeping tapers is not possible yet'); end
if dojack && keeprpt, error('you cannot simultaneously keep trials and do jackknifing'); end
tfwin = round(data.fsample.*cfg.t_ftimwin);
ntrl = length(data.trial);
ntoi = length(cfg.toi);
if ~dobvar
chanindx = match_str(data.label, cfg.channel);
nchan = length(chanindx);
label = data.label(chanindx);
ncmb = nchan*nchan;
cmbindx1 = repmat(chanindx(:), [1 nchan]);
cmbindx2 = repmat(chanindx(:)', [nchan 1]);
labelcmb = [data.label(cmbindx1(:)) data.label(cmbindx2(:))];
else
cfg.channelcmb = ft_channelcombination(cfg.channelcmb, data.label);
cmbindx = zeros(size(cfg.channelcmb));
for k = 1:size(cmbindx,1)
[tmp, cmbindx(k,:)] = match_str(cfg.channelcmb(k,:)', data.label);
end
nchan = 2;
label = data.label(cmbindx);
ncmb = nchan*nchan;
labelcmb = cell(0,2);
cmb = cfg.channelcmb;
for k = 1:size(cmbindx,1)
labelcmb{end+1,1} = [cmb{k,1},'[',cmb{k,1},cmb{k,2},']'];
labelcmb{end ,2} = [cmb{k,1},'[',cmb{k,1},cmb{k,2},']'];
labelcmb{end+1,1} = [cmb{k,2},'[',cmb{k,1},cmb{k,2},']'];
labelcmb{end ,2} = [cmb{k,1},'[',cmb{k,1},cmb{k,2},']'];
labelcmb{end+1,1} = [cmb{k,1},'[',cmb{k,1},cmb{k,2},']'];
labelcmb{end ,2} = [cmb{k,2},'[',cmb{k,1},cmb{k,2},']'];
labelcmb{end+1,1} = [cmb{k,2},'[',cmb{k,1},cmb{k,2},']'];
labelcmb{end ,2} = [cmb{k,2},'[',cmb{k,1},cmb{k,2},']'];
end
end
%---think whether this makes sense at all
if strcmp(cfg.taper, 'dpss')
% create a sequence of DPSS (Slepian) tapers
% ensure that the input arguments are double precision
tap = double_dpss(tfwin,tfwin*(cfg.tapsmofrq./data.fsample))';
tap = tap(1,:); %only use first 'zero-order' taper
elseif strcmp(cfg.taper, 'sine')
tap = sine_taper(tfwin, tfwin*(cfg.tapsmofrq./data.fsample))';
tap = tap(1,:);
else
tap = window(cfg.taper, tfwin)';
tap = tap./norm(tap);
end
ntap = size(tap,1);
%---preprocess data if necessary
%---cut off the uninteresting data segments
tmpcfg = [];
tmpcfg.toilim = cfg.toi([1 end]) + cfg.t_ftimwin.*[-0.5 0.5];
data = ft_redefinetrial(tmpcfg, data);
%---demean
if strcmp(cfg.demean, 'yes'),
tmpcfg = [];
tmpcfg.demean = 'yes';
tmpcfg.baselinewindow = cfg.toi([1 end]) + cfg.t_ftimwin.*[-0.5 0.5];
data = ft_preprocessing(tmpcfg, data);
else
%do nothing
end
%---ensemble mean subtraction
if strcmp(cfg.ems, 'yes')
% to be implemented
end
%---zscore
if dozscore,
zwindow = cfg.toi([1 end]) + cfg.t_ftimwin.*[-0.5 0.5];
sumval = 0;
sumsqr = 0;
numsmp = 0;
trlindx = [];
for k = 1:ntrl
begsmp = nearest(data.time{k}, zwindow(1));
endsmp = nearest(data.time{k}, zwindow(2));
if endsmp>=begsmp,
sumval = sumval + sum(data.trial{k}(:, begsmp:endsmp), 2);
sumsqr = sumsqr + sum(data.trial{k}(:, begsmp:endsmp).^2, 2);
numsmp = numsmp + endsmp - begsmp + 1;
trlindx = [trlindx; k];
end
end
datavg = sumval./numsmp;
datstd = sqrt(sumsqr./numsmp - (sumval./numsmp).^2);
data.trial = data.trial(trlindx);
data.time = data.time(trlindx);
ntrl = length(trlindx);
for k = 1:ntrl
rvec = ones(1,size(data.trial{k},2));
data.trial{k} = (data.trial{k} - datavg*rvec)./(datstd*rvec);
end
else
%do nothing
end
%---generate time axis
maxtim = -inf;
mintim = inf;
for k = 1:ntrl
maxtim = max(maxtim, data.time{k}(end));
mintim = min(mintim, data.time{k}(1));
end
timeaxis = mintim:1/data.fsample:maxtim;
%---allocate memory
if ~dobvar && (keeprpt || dojack)
coeffs = zeros(length(data.trial), nchan, nchan, cfg.order, ntoi, ntap);
noisecov = zeros(length(data.trial), nchan, nchan, ntoi, ntap);
elseif ~dobvar
coeffs = zeros(1, nchan, nchan, cfg.order, ntoi, ntap);
noisecov = zeros(1, nchan, nchan, ntoi, ntap);
elseif dobvar && (keeprpt || dojack)
% not yet implemented
error('doing bivariate model fits in combination with multiple replicates is not yet possible');
elseif dobvar
coeffs = zeros(1, size(cmbindx,1), 2*nchan, cfg.order, ntoi, ntap);
noisecov = zeros(1, size(cmbindx,1), 2*nchan, ntoi, ntap);
end
%---loop over the tois
ft_progress('init', cfg.feedback, 'computing AR-model');
for j = 1:ntoi
ft_progress(j/ntoi, 'processing timewindow %d from %d\n', j, ntoi);
sample = nearest(timeaxis, cfg.toi(j));
cfg.toi(j) = timeaxis(sample);
tmpcfg = [];
tmpcfg.toilim = [timeaxis(sample-floor(tfwin/2)) timeaxis(sample+ceil(tfwin/2)-1)];
tmpcfg.feedback = 'no';
tmpcfg.minlength= 'maxperlen';
tmpdata = ft_redefinetrial(tmpcfg, data);
cfg.toi(j) = mean(tmpdata.time{1}([1 end]))+0.5./data.fsample; %FIXME think about this
%---create cell-array indexing which original trials should go into each replicate
rpt = {};
nrpt = numel(tmpdata.trial);
if dojack
rpt = cell(nrpt,1);
for k = 1:nrpt
rpt{k,1} = setdiff(1:nrpt,k);
end
elseif keeprpt
for k = 1:nrpt
rpt{k,1} = k;
end
else
rpt{1} = 1:numel(tmpdata.trial);
nrpt = 1;
end
for rlop = 1:nrpt
if dobvar % bvar
for m = 1:ntap
%---construct data-matrix
for k = 1:size(cmbindx,1)
dat = catnan(tmpdata.trial, cmbindx(k,:), rpt{rlop}, tap(m,:), nnans, dobvar);
%---estimate autoregressive model
switch cfg.toolbox
case 'biosig'
[ar, rc, pe] = mvar(dat', cfg.order, cfg.mvarmethod);
%---compute noise covariance
tmpnoisecov = pe(:,nchan*cfg.order+1:nchan*(cfg.order+1));
case 'bsmart'
[ar, tmpnoisecov] = armorf(dat, numel(rpt{rlop}), size(tmpdata.trial{1},2), cfg.order);
ar = -ar; %convention is swapped sign with respect to biosig
%FIXME check which is which: X(t) = A1*X(t-1) + ... + An*X(t-n) + E
%the other is then X(t) + A1*X(t-1) + ... + An*X(t-n) = E
end
coeffs(rlop,k,:,:,j,m) = reshape(ar, [nchan*2 cfg.order]);
%---rescale noisecov if necessary
if dozscore, % FIX ME for bvar
noisecov(rlop,k,:,:,j,m) = diag(datstd)*tmpnoisecov*diag(datstd);
else
noisecov(rlop,k,:,j,m) = reshape(tmpnoisecov,[1 4]);
end
dof(rlop,:,j) = numel(rpt{rlop});
end
end
else % mvar
for m = 1:ntap
%---construct data-matrix
dat = catnan(tmpdata.trial, chanindx, rpt{rlop}, tap(m,:), nnans, dobvar);
%---estimate autoregressive model
switch cfg.toolbox
case 'biosig'
[ar, rc, pe] = mvar(dat', cfg.order, cfg.mvarmethod);
%---compute noise covariance
tmpnoisecov = pe(:,nchan*cfg.order+1:nchan*(cfg.order+1));
case 'bsmart'
[ar, tmpnoisecov] = armorf(dat, numel(rpt{rlop}), size(tmpdata.trial{1},2), cfg.order);
ar = -ar; %convention is swapped sign with respect to biosig
%FIXME check which is which: X(t) = A1*X(t-1) + ... + An*X(t-n) + E
%the other is then X(t) + A1*X(t-1) + ... + An*X(t-n) = E
end
coeffs(rlop,:,:,:,j,m) = reshape(ar, [nchan nchan cfg.order]);
%---rescale noisecov if necessary
if dozscore,
noisecov(rlop,:,:,j,m) = diag(datstd)*tmpnoisecov*diag(datstd);
else
noisecov(rlop,:,:,j,m) = tmpnoisecov;
end
dof(rlop,:,j) = numel(rpt{rlop});
end %---tapers
end
end %---replicates
end %---tois
ft_progress('close');
%---create output-structure
mvardata = [];
if ~dobvar && dojack,
mvardata.dimord = 'rptjck_chan_chan_lag';
elseif ~dobvar && keeprpt,
mvardata.dimord = 'rpt_chan_chan_lag';
elseif ~dobvar
mvardata.dimord = 'chan_chan_lag';
mvardata.label = label;
siz = size(coeffs);
coeffs = reshape(coeffs, siz(2:end));
siz = size(noisecov);
noisecov = reshape(noisecov, siz(2:end));
elseif dobvar
mvardata.dimord = 'chancmb_lag';
siz = [size(coeffs) 1];
coeffs = reshape(coeffs, [siz(2) * siz(3) siz(4) siz(5)]);
siz = [size(noisecov) 1];
noisecov = reshape(noisecov, [siz(2) * siz(3) siz(4)]);
mvardata.labelcmb = labelcmb;
end
mvardata.coeffs = coeffs;
mvardata.noisecov = noisecov;
mvardata.dof = dof;
if numel(cfg.toi)>1
mvardata.time = cfg.toi;
mvardata.dimord = [mvardata.dimord,'_time'];
end
mvardata.fsampleorig = data.fsample;
% accessing this field here is needed for the configuration tracking
% by accessing it once, it will not be removed from the output cfg
cfg.outputfile;
% get the output cfg
cfg = ft_checkconfig(cfg, 'trackconfig', 'off', 'checksize', 'yes');
% add version information to the configuration
cfg.version.name = mfilename('fullpath');
cfg.version.id = '$Id: ft_mvaranalysis.m 3766 2011-07-04 10:44:39Z eelspa $';
% add information about the Matlab version used to the configuration
cfg.callinfo.matlab = version();
% add information about the function call to the configuration
cfg.callinfo.proctime = toc(ftFuncTimer);
cfg.callinfo.calltime = ftFuncClock;
cfg.callinfo.user = getusername();
% remember the configuration details of the input data
try
cfg.previous = data.cfg;
end
mvardata.cfg = cfg;
% the output data should be saved to a MATLAB file
if ~isempty(cfg.outputfile)
savevar(cfg.outputfile, 'data', mvardata); % use the variable name "data" in the output file
end
%----------------------------------------------------
%subfunction to concatenate data with nans in between
function [datamatrix] = catnan(datacells, chanindx, trials, taper, nnans, dobvar)
nchan = length(chanindx);
nsmp = size(datacells{1}, 2);
nrpt = numel(trials);
%---initialize
datamatrix = zeros(nchan, nsmp*nrpt + nnans*(nrpt-1)) + nan;
%---fill the matrix
for k = 1:nrpt
if k==1,
begsmp = (k-1)*nsmp + 1;
endsmp = k *nsmp ;
else
begsmp = (k-1)*(nsmp+nnans) + 1;
endsmp = k *(nsmp+nnans) - nnans;
end
if ~dobvar
datamatrix(:,begsmp:endsmp) = datacells{trials(k)}(chanindx,:).*taper(ones(nchan,1),:);
else
datamatrix(:,begsmp:endsmp) = datacells{trials(k)}(chanindx',:).*taper(ones(nchan,1),:);
end
end
%------------------------------------------------------
%---subfunction to ensure that the first two input arguments are of double
% precision this prevents an instability (bug) in the computation of the
% tapers for Matlab 6.5 and 7.0
function [tap] = double_dpss(a, b, varargin)
tap = dpss(double(a), double(b), varargin{:});
|
github
|
philippboehmsturm/antx-master
|
ft_databrowser_old.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_databrowser_old.m
| 56,720 |
utf_8
|
3bc8d11301b8bf813ef8c432cf0c49e3
|
function [cfg] = ft_databrowser_old(cfg, data)
% FT_DATABROWSER can be used for visual inspection of data. Artifacts that were detected
% by artifact functions (see FT_ARTIFACT_xxx functions where xxx is the type of artifact)
% are marked. Additionally data pieces can be marked and unmarked as artifact by
% manual selection. The output cfg contains the updated artifactdef field.
%
% Use as
% cfg = ft_databrowser(cfg)
% required configuration options:
% cfg.dataset or both cfg.headerfile and cfg.datafile
% or as
% cfg = ft_databrowser(cfg, data)
% with the data as obtained from FT_PREPROCESSING
%
% The following configuration options are supported:
% cfg.trl = structure that defines the data segments of interest. See FT_DEFINETRIAL
% cfg.continuous = 'yes' or 'no' wh ether the file contains continuous data
% cfg.channel = cell-array with channel labels, see FT_CHANNELSELECTION
% cfg.comps = a vector with the components to plot (ex. 1:10) (optional)
% cfg.zscale = [zmin zmax] or 'auto' (default = 'auto')
% cfg.blocksize = number (in seconds), only aplicable if data contains only 1 (long) trial
% cfg.viewmode = string, 'butterfly', 'vertical', 'component' (default = 'butterfly')
% cfg.artfctdef.xxx.artifact = Nx2 matrix with artifact segments see FT_ARTIFACT_xxx functions
% cfg.selectfeature = string, name of feature to be selected/added (default = 'visual')
% cfg.selectmode = string, what to do with a selection, can be 'mark', or 'eval' (default = 'mark')
% 'mark': artfctdef field is updated, 'eval': the function defined in
% cfg.selfun is evaluated f.i. browse_movieplotER calls movieplotER which makes
% a movie of the selected data
% cfg.colorgroups = 'sequential' 'labelcharx' (x = xth character in label), 'chantype' or
% vector with length(data/hdr.label) defining groups (default = 'sequential')
% cfg.channelcolormap = COLORMAP (default = customized lines map with 15 colors)
% cfg.selfun = string, name of function which is evaluated if selectmode is set to 'eval'.
% The selected data and the selcfg are passed on to this function.
% cfg.selcfg = configuration options for selfun
% cfg.eegscale = number, scaling to apply to the EEG channels prior to display
% cfg.eogscale = number, scaling to apply to the EOG channels prior to display
% cfg.ecgscale = number, scaling to apply to the ECG channels prior to display
% cfg.emgscale = number, scaling to apply to the EMG channels prior to display
% cfg.megscale = number, scaling to apply to the MEG channels prior to display
%
% The "artifact" field in the output cfg is a Nx2 matrix comparable to the
% "trl" matrix of FT_DEFINETRIAL. The first column of which specifying the
% beginsamples of an artifact period, the second column contains the
% endsamples of the artifactperiods.
%
% To facilitate data-handling and distributed computing with the peer-to-peer
% module, this function has the following options:
% cfg.inputfile = ...
% cfg.outputfile = ...
% If you specify one of these (or both) the input data will be read from a *.mat
% file on disk and/or the output data will be written to a *.mat file.
% These mat
% files should contain only a single variable, corresponding with the
% input/output structure.
%
% NOTE for debugging: in case the databrowser crashes, use delete(gcf) to kill the figure.
%
% See also FT_PREPROCESSING, FT_REJECTARTIFACT, FT_ARTIFACT_EOG, FT_ARTIFACT_MUSCLE,
% FT_ARTIFACT_JUMP, FT_ARTIFACT_MANUAL, FT_ARTIFACT_THRESHOLD, FT_ARTIFACT_CLIP, FT_ARTIFACT_ECG
% Copyright (C) 2009, Robert Oostenveld, Ingrid Niewenhuis
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_databrowser_old.m 3862 2011-07-14 13:41:01Z jorhor $
ft_defaults
% record start time and total processing time
ftFuncTimer = tic();
ftFuncClock = clock();
% set defaults for optional cfg.input and or cfg.outputfile
if ~isfield(cfg, 'inputfile'), cfg.inputfile = []; end
if ~isfield(cfg, 'outputfile'), cfg.outputfile = []; end
% set the defaults
if ~isfield(cfg, 'channel'), cfg.channel = 'all'; end
if ~isfield(cfg, 'zscale'), cfg.zscale = 'auto'; end
if ~isfield(cfg, 'artfctdef'), cfg.artfctdef = struct; end
if ~isfield(cfg, 'selectfeature'), cfg.selectfeature = 'visual'; end % string or cell-array
if ~isfield(cfg, 'selectmode'), cfg.selectmode = 'mark'; end
if ~isfield(cfg, 'viewmode'), cfg.viewmode = 'butterfly'; end % butterfly, vertical, component, settings
if ~isfield(cfg, 'blocksize'), cfg.blocksize = 1; end % only for segmenting continuous data, i.e. one long trial
if ~isfield(cfg, 'preproc'), cfg.preproc = []; end % see preproc for options
if ~isfield(cfg, 'event'), cfg.event = []; end
if ~isfield(cfg, 'selfun'), cfg.selfun = 'browse_multiplotER'; end
if ~isfield(cfg, 'selcfg'), cfg.selcfg = []; end
if ~isfield(cfg, 'colorgroups'), cfg.colorgroups = 'sequential'; end
if ~isfield(cfg, 'channelcolormap'), cfg.channelcolormap = [0.75 0 0;0 0 1;0 1 0;0.44 0.19 0.63;0 0.13 0.38;0.5 0.5 0.5;1 0.75 0;1 0 0;0.89 0.42 0.04;0.85 0.59 0.58;0.57 0.82 0.31;0 0.69 0.94;1 0 0.4;0 0.69 0.31;0 0.44 0.75]; end
if ~isfield(cfg, 'eegscale'), cfg.eegscale = []; end
if ~isfield(cfg, 'eogscale'), cfg.eogscale = []; end
if ~isfield(cfg, 'ecgscale'), cfg.ecgscale = []; end
if ~isfield(cfg, 'emgscale'), cfg.emgscale = []; end
if ~isfield(cfg, 'megscale'), cfg.megscale = []; end
hasdata = (nargin>1);
if ~isempty(cfg.inputfile)
% the input data should be read from file
if hasdata
error('cfg.inputfile should not be used in conjunction with giving input data to this function');
else
data = loadvar(cfg.inputfile, 'data');
hasdata = true;
end
end
if hasdata
data = ft_checkdata(data, 'datatype', {'raw', 'comp'}, 'feedback', 'yes', 'hassampleinfo', 'yes');
% fetch the header from memory
hdr = ft_fetch_header(data);
if ~isfield(cfg, 'continuous') && length(data.trial) == 1
cfg.continuous = 'yes';
elseif ~isfield(cfg, 'continuous') && length(data.trial) > 1
cfg.continuous = 'no';
end
else
% check if the input cfg is valid for this function
cfg = ft_checkconfig(cfg, 'dataset2files', {'yes'});
cfg = ft_checkconfig(cfg, 'required', {'headerfile', 'datafile'});
cfg = ft_checkconfig(cfg, 'renamed', {'datatype', 'continuous'});
cfg = ft_checkconfig(cfg, 'renamedval', {'continuous', 'continuous', 'yes'});
% read the header from file
hdr = ft_read_header(cfg.headerfile, 'headerformat', cfg.headerformat);
if ~isfield(cfg, 'continuous')
if hdr.nTrials==1
cfg.continuous = 'yes';
else
cfg.continuous = 'no';
end
end
end
if hasdata && isfield(data, 'topo') && strcmp(cfg.viewmode, 'component')
if ~isfield(cfg, 'comp')
cfg.comp = 1:10; % to avoid plotting 274 components topographically
end
cfg.channel = data.label(cfg.comp);
end
if ischar(cfg.selectfeature)
% ensure that it is a cell array
cfg.selectfeature = {cfg.selectfeature};
end
% get some initial parameters from the data
if hasdata
% check whether data has been resampled
if isfield(data, 'cfg') && isempty(ft_findcfg(data.cfg, 'origfs'))
resampled = false;
else
resampled = true;
end
% fetch the events
event = ft_fetch_event(data);
cfg.channel = ft_channelselection(cfg.channel, data.label);
chansel = match_str(data.label, cfg.channel);
fsample = 1/(data.time{1}(2)-data.time{1}(1));
Nchans = length(chansel);
% this is how the input data is segmented
trlorg = zeros(numel(data.trial), 3);
trlorg(:,[1 2]) = data.sampleinfo;
% recreate offset vector (databrowser depends on this for visualisation)
for ntrl = 1:numel(data.trial)
trlorg(ntrl,3) = time2offset(data.time{ntrl}, data.fsample);
end
Ntrials = size(trlorg, 1);
if strcmp(cfg.viewmode, 'component')
if ~isfield(cfg, 'layout')
error('You need to specify a layout-file when browsing through components');
end
% read or create the layout that will be used for the topoplots
cfg.layout = ft_prepare_layout(cfg, data);
if ~isfield(cfg, 'comp')
cfg.comp = 1:10; % to avoid plotting 274 components topographically
end
cfg.channel = data.label(cfg.comp);
end
else
% data has not been resampled
resampled = false;
% read the events
if isempty(cfg.event)
event = ft_read_event(cfg.dataset);
else
event = cfg.event;
end
cfg.channel = ft_channelselection(cfg.channel, hdr.label);
chansel = match_str(hdr.label, cfg.channel);
fsample = hdr.Fs;
Nchans = length(chansel);
Ntrials = hdr.nTrials;
% construct trl-matrix for data from file on disk
trlorg = zeros(Ntrials,3);
for k = 1:Ntrials
trlorg(k,[1 2]) = [1 hdr.nSamples] + [hdr.nSamples hdr.nSamples] .* (k-1);
end
end % if hasdata
if Nchans == 0
error('no channels to display');
end
if Ntrials == 0
error('no trials to display');
end
% determine coloring of channels
if hasdata
labels_all = data.label;
else
labels_all= hdr.label;
end
if size(cfg.channelcolormap,2) ~= 3
error('cfg.channelcolormap is not valid, size should be Nx3')
end
if isnumeric(cfg.colorgroups)
% groups defined by user
if length(labels_all) ~= length(cfg.colorgroups)
error('length(cfg.colorgroups) should be length(data/hdr.label)')
end
R = cfg.channelcolormap(:,1);
G = cfg.channelcolormap(:,2);
B = cfg.channelcolormap(:,3);
chan_colors = [R(cfg.colorgroups(:)) G(cfg.colorgroups(:)) B(cfg.colorgroups(:))];
elseif strcmp(cfg.colorgroups, 'chantype')
type = ft_chantype(labels_all);
[tmp1 tmp2 cfg.colorgroups] = unique(type);
fprintf('%3d colorgroups were identified\n',length(tmp1))
R = cfg.channelcolormap(:,1);
G = cfg.channelcolormap(:,2);
B = cfg.channelcolormap(:,3);
chan_colors = [R(cfg.colorgroups(:)) G(cfg.colorgroups(:)) B(cfg.colorgroups(:))];
elseif strcmp(cfg.colorgroups(1:9), 'labelchar')
% groups determined by xth letter of label
labelchar_num = str2double(cfg.colorgroups(10));
vec_letters = num2str(zeros(length(labels_all),1));
for iChan = 1:length(labels_all)
vec_letters(iChan) = labels_all{iChan}(labelchar_num);
end
[tmp1 tmp2 cfg.colorgroups] = unique(vec_letters);
fprintf('%3d colorgroups were identified\n',length(tmp1))
R = cfg.channelcolormap(:,1);
G = cfg.channelcolormap(:,2);
B = cfg.channelcolormap(:,3);
chan_colors = [R(cfg.colorgroups(:)) G(cfg.colorgroups(:)) B(cfg.colorgroups(:))];
elseif strcmp(cfg.colorgroups, 'sequential')
% no grouping
chan_colors = lines(length(labels_all));
else
error('do not understand cfg.colorgroups')
end
% collect the artifacts that have been detected from cfg.artfctdef.xxx.artifact
artlabel = fieldnames(cfg.artfctdef);
sel = zeros(size(artlabel));
artifact = cell(size(artlabel));
for i=1:length(artlabel)
sel(i) = issubfield(cfg.artfctdef, [artlabel{i} '.artifact']);
if sel(i)
artifact{i} = getsubfield(cfg.artfctdef, [artlabel{i} '.artifact']);
num = size(artifact{i}, 1);
if isempty(num)
num = 0;
end
fprintf('detected %3d %s artifacts\n', num, artlabel{i});
end
end
artifact = artifact(sel==1);
artlabel = artlabel(sel==1);
for i=1:length(cfg.selectfeature)
if ~any(strcmp(cfg.selectfeature{i}, artlabel))
artifact = {[], artifact{:}};
artlabel = {cfg.selectfeature{i}, artlabel{:}};
end
end
if length(artlabel) > 9
error('only upto 9 artifacts groups supported')
end
% make artdata representing all artifacts in a "raw data" format
datendsample = max(trlorg(:,2));
artdat = convert_event(artifact, 'boolvec', 'endsample', datendsample);
artdata = [];
artdata.trial{1} = artdat; % every artifact is a "channel"
artdata.time{1} = offset2time(0, fsample, datendsample);
artdata.label = artlabel;
artdata.fsample = fsample;
artdata.cfg.trl = [1 datendsample 0];
if ischar(cfg.zscale) && strcmp(cfg.zscale, 'auto')
if nargin>1
dat = data.trial{1}(chansel,:);
time = data.time{1};
else
% one second of data is read from file to determine the vertical scaling
dat = ft_read_data(cfg.datafile, 'header', hdr, 'begsample', 1, 'endsample', round(hdr.Fs), 'chanindx', chansel, 'checkboundary', strcmp(cfg.continuous, 'no'), 'dataformat', cfg.dataformat, 'headerformat', cfg.headerformat);
time = (1:hdr.nSamples) / fsample;
end
minval = min(dat(:));
maxval = max(dat(:));
mintime = min(time(:));
maxtime = max(time(:));
cfg.zscale = max(abs(minval), abs(maxval));
cfg.yscale = max(abs(mintime), abs(maxtime));
end
h = figure;
set(h, 'KeyPressFcn', @keyboard_cb);
set(h, 'WindowButtonDownFcn', {@ft_select_range, 'multiple', false, 'xrange', true, 'yrange', false, 'clear', true, 'callback', {@select_range_cb, h}, 'event', 'WindowButtonDownFcn'});
set(h, 'WindowButtonUpFcn', {@ft_select_range, 'multiple', false, 'xrange', true, 'yrange', false, 'clear', true, 'callback', {@select_range_cb, h}, 'event', 'WindowButtonUpFcn'});
set(h, 'WindowButtonMotionFcn', {@ft_select_range, 'multiple', false, 'xrange', true, 'yrange', false, 'clear', true, 'callback', {@select_range_cb, h}, 'event', 'WindowButtonMotionFcn'});
% opt represents the global data/settings, it should contain
% - the original data, epoched or continuous
% - the artifacts represented as continuous data
% - the redraw_cb settings
% - the preproc settings
% - the select_range_cb settings (also used in keyboard_cb)
% these elements are stored inside the figure so that the callback routines can modify them
opt = [];
if hasdata
opt.orgdata = data;
else
opt.orgdata = []; % this means that it will look in opt.cfg.dataset
end
opt.artdata = artdata;
opt.cfg = cfg; % the configuration of this function, not of the preprocessing
opt.hdr = hdr;
opt.event = event;
opt.trlop = 1; % active trial being displayed
opt.ftsel = find(strcmp(artlabel,cfg.selectfeature)); % current artifact/feature being selected
opt.trlorg = trlorg;
opt.fsample = fsample;
opt.artcol = [0.9686 0.7608 0.7686; 0.7529 0.7098 0.9647; 0.7373 0.9725 0.6824;0.8118 0.8118 0.8118; 0.9725 0.6745 0.4784; 0.9765 0.9176 0.5686; 0.6863 1 1; 1 0.6863 1; 0 1 0.6000];
opt.chan_colors = chan_colors;
opt.cleanup = false; % this is needed for a corrent handling if the figure is closed (either in the corner or by "q")
opt.compindx = []; % index of components to be drawn (if viewmode = "component")
opt.resampled = resampled;
if strcmp(cfg.continuous, 'yes')
opt.trialname = 'segment';
else
opt.trialname = 'trial';
end
guidata(h, opt);
% make the user interface elements for the data view
uicontrol('tag', 'group1', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', opt.trialname, 'userdata', 't')
uicontrol('tag', 'group2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '<', 'userdata', 'leftarrow')
uicontrol('tag', 'group2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '>', 'userdata', 'rightarrow')
uicontrol('tag', 'group1', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'channel','userdata', 'c')
uicontrol('tag', 'group2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '<', 'userdata', 'uparrow')
uicontrol('tag', 'group2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '>', 'userdata', 'downarrow')
uicontrol('tag', 'group1a', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'horizontal', 'userdata', 'h')
uicontrol('tag', 'group2a', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '-', 'userdata', 'shift+leftarrow')
uicontrol('tag', 'group2a', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '+', 'userdata', 'shift+rightarrow')
if strcmp(cfg.continuous, 'no')
ft_uilayout(h, 'tag', 'group1a', 'visible', 'on', 'retag', 'group1');
ft_uilayout(h, 'tag', 'group2a', 'visible', 'on', 'retag', 'group2');
else
ft_uilayout(h, 'tag', 'group1a', 'visible', 'on', 'retag', 'group1');
ft_uilayout(h, 'tag', 'group2a', 'visible', 'on', 'retag', 'group2');
end
uicontrol('tag', 'group1', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'vertical', 'userdata', 'v')
uicontrol('tag', 'group2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '-', 'userdata', 'shift+downarrow')
uicontrol('tag', 'group2', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '+', 'userdata', 'shift+uparrow')
% legend artifacts/features
for iArt = 1:length(artlabel)
uicontrol('tag', 'group3', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', artlabel{iArt}, 'userdata', num2str(iArt), 'position', [0.91, 0.9 - ((iArt-1)*0.09), 0.08, 0.04], 'backgroundcolor', opt.artcol(iArt,:))
uicontrol('tag', 'group3', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '<', 'userdata', ['shift+' num2str(iArt)], 'position', [0.91, 0.85 - ((iArt-1)*0.09), 0.03, 0.04], 'backgroundcolor', opt.artcol(iArt,:))
uicontrol('tag', 'group3', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', '>', 'userdata', ['control+' num2str(iArt)], 'position', [0.96, 0.85 - ((iArt-1)*0.09), 0.03, 0.04], 'backgroundcolor', opt.artcol(iArt,:))
end
if strcmp(cfg.viewmode, 'butterfly')
% button to find label of nearest channel to datapoint
uicontrol('tag', 'group3', 'parent', h, 'units', 'normalized', 'style', 'pushbutton', 'string', 'identify', 'userdata', 'i', 'position', [0.91, 0.1, 0.08, 0.05], 'backgroundcolor', [1 1 1])
end
ft_uilayout(h, 'tag', 'group1', 'width', 0.10, 'height', 0.05);
ft_uilayout(h, 'tag', 'group2', 'width', 0.05, 'height', 0.05);
ft_uilayout(h, 'tag', 'group1', 'style', 'pushbutton', 'callback', @keyboard_cb);
ft_uilayout(h, 'tag', 'group2', 'style', 'pushbutton', 'callback', @keyboard_cb);
ft_uilayout(h, 'tag', 'group3', 'style', 'pushbutton', 'callback', @keyboard_cb);
ft_uilayout(h, 'tag', 'group1', 'retag', 'viewui');
ft_uilayout(h, 'tag', 'group2', 'retag', 'viewui');
ft_uilayout(h, 'tag', 'viewui', 'BackgroundColor', [0.8 0.8 0.8], 'hpos', 'auto', 'vpos', 0);
definetrial_cb(h);
redraw_cb(h);
% %% Scrollbar
%
% % set initial scrollbar value
% dx = maxtime;
%
% % set scrollbar position
% fig_pos=get(gca,'position');
% scroll_pos=[fig_pos(1) fig_pos(2) fig_pos(3) 0.02];
%
% % define callback
% S=['set(gca,''xlim'',get(gcbo,''value'')+[ ' num2str(mintime) ',' num2str(maxtime) '])'];
%
% % Creating Uicontrol
% s=uicontrol('style','slider',...
% 'units','normalized','position',scroll_pos,...
% 'callback',S,'min',0,'max',0, ...
% 'visible', 'off'); %'value', xmin
% set initial scrollbar value
% dx = maxtime;
%
% % set scrollbar position
% fig_pos=get(gca,'position');
% scroll_pos=[fig_pos(1) fig_pos(2) fig_pos(3) 0.02];
%
% % define callback
% S=['set(gca,''xlim'',get(gcbo,''value'')+[ ' num2str(mintime) ',' num2str(maxtime) '])'];
%
% % Creating Uicontrol
% s=uicontrol('style','slider',...
% 'units','normalized','position',scroll_pos,...
% 'callback',S,'min',0,'max',0, ...
% 'visible', 'off'); %'value', xmin
%initialize postion of plot
% set(gca,'xlim',[xmin xmin+dx]);
if nargout
% wait until the user interface is closed, get the user data with the updated artifact details
set(h, 'CloseRequestFcn', @cleanup_cb);
while ishandle(h)
uiwait(h);
opt = guidata(h);
if opt.cleanup
delete(h);
end
end
% add the updated artifact definitions to the output cfg
for i=1:length(opt.artdata.label)
cfg.artfctdef.(opt.artdata.label{i}).artifact = convert_event(opt.artdata.trial{1}(i,:), 'artifact');
end
end % if nargout
% add version information to the configuration
cfg.version.name = mfilename('fullpath');
cfg.version.id = '$Id: ft_databrowser_old.m 3862 2011-07-14 13:41:01Z jorhor $';
% add information about the Matlab version used to the configuration
cfg.callinfo.matlab = version();
% add information about the function call to the configuration
cfg.callinfo.proctime = toc(ftFuncTimer);
cfg.callinfo.calltime = ftFuncClock;
cfg.callinfo.user = getusername();
% remember the configuration details of the input data
if hasdata && isfield(data, 'cfg')
cfg.previous = data.cfg;
end
% remember the exact configuration details in the output
dataout.cfg = cfg;
% the output data should be saved to a MATLAB file
if ~isempty(cfg.outputfile)
savevar(cfg.outputfile, 'data', dataout); % use the variable name "data" in the output file
end
end % main function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cleanup_cb(h, eventdata)
opt = guidata(h);
opt.cleanup = true;
guidata(h, opt);
uiresume
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function definetrial_cb(h, eventdata)
opt = guidata(h);
if strcmp(opt.cfg.continuous, 'no')
% keep the original trial definition for visualisation
opt.trlvis = opt.trlorg;
else
% construct a trial definition for visualisation
if isfield(opt, 'trlvis')
thistrlbeg = opt.trlvis(opt.trlop,1);
thistrlend = opt.trlvis(opt.trlop,2);
% remember a representative sample of the current trial
% thissample = round((thistrlbeg+thistrlend)/2);
thissample = thistrlbeg;
end
% look at opt.cfg.blocksize and make opt.trl accordingly
% if original data contains more than one trial, it will fail in ft_fetch_data
datbegsample = min(opt.trlorg(:,1));
datendsample = max(opt.trlorg(:,2));
smppertrl = round(opt.fsample * opt.cfg.blocksize);
begsamples = datbegsample:smppertrl:datendsample;
endsamples = datbegsample+smppertrl-1:smppertrl:datendsample;
if numel(endsamples)<numel(begsamples)
endsamples(end+1) = datendsample;
end
trlvis = [];
trlvis(:,1) = begsamples';
trlvis(:,2) = endsamples';
if size(opt.trlorg,1) > 1 || isempty(opt.orgdata)
% offset is now (re)defined that 1st sample is time 0
trlvis(:,3) = begsamples-1;
else
% offset according to original time axis
trlvis(:,3) = opt.trlorg(3) + begsamples - opt.trlorg(1);
end
if isfield(opt, 'trlvis')
% update the current trial counter and try to keep the current sample the same
% opt.trlop = nearest(round((begsamples+endsamples)/2), thissample);
opt.trlop = nearest(begsamples, thissample);
end
opt.trlvis = trlvis;
end % if continuous
guidata(h, opt);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function help_cb(h, eventdata)
fprintf('------------------------------------------------------------------------------------\n')
fprintf('You can use the following buttons in the data viewer\n')
fprintf('1-9 : select artifact type 1-9\n');
fprintf('shift 1-9 : select previous artifact of type 1-9\n');
fprintf('control 1-9 : select next artifact of type 1-9\n');
fprintf('alt 1-9 : select next artifact of type 1-9\n');
fprintf('arrow-left : previous trial\n');
fprintf('arrow-right : next trial\n');
fprintf('shift arrow-up : increase vertical scaling\n');
fprintf('shift arrow-down : decrease vertical scaling\n');
fprintf('shift arrow-left : increase horizontal scaling\n');
fprintf('shift arrow-down : decrease horizontal scaling\n');
fprintf('q : quit\n');
fprintf('------------------------------------------------------------------------------------\n')
fprintf('\n')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function select_range_cb(range, h) %range 1X4 in sec relative to current trial
opt = guidata(h);
switch opt.cfg.viewmode
case 'butterfly'
begsample = opt.trlvis(opt.trlop,1);
endsample = opt.trlvis(opt.trlop,2);
offset = opt.trlvis(opt.trlop,3);
% determine the selection
if strcmp(opt.trialname, 'trial')
% this is appropriate when the offset is defined according to a
% different trigger in each trial, which is usually the case in trial data
begsel = round(range(1)*opt.fsample+begsample-offset-1);
endsel = round(range(2)*opt.fsample+begsample-offset);
elseif strcmp(opt.trialname, 'segment')
% this is appropriate when the offset is defined according to a
% one trigger, which is always the case in segment data [I think ingnie]
begsel = round(range(1)*opt.fsample+1);
endsel = round(range(2)*opt.fsample+1);
end
% the selection should always be confined to the current trial
begsel = max(begsample, begsel);
endsel = min(endsample, endsel);
case {'vertical', 'component'}
% the range should be in the displayed box
range(1) = max(opt.hpos(1), range(1));
range(2) = max(opt.hpos(1), range(2));
range(1) = min(opt.hpos(2), range(1));
range(2) = min(opt.hpos(2), range(2));
range = (range - opt.hpos(1)) / (opt.hpos(2) - opt.hpos(1)); % left side of the box becomes 0, right side becomes 1
range = range * (opt.hlim(2) - opt.hlim(1)) + opt.hlim(1); % 0 becomes hlim(1), 1 becomes hlim(2)
begsample = opt.trlvis(opt.trlop,1);
endsample = opt.trlvis(opt.trlop,2);
offset = opt.trlvis(opt.trlop,3);
% determine the selection
if strcmp(opt.trialname, 'trial')
% this is appropriate when the offset is defined according to a
% different trigger in each trial, which is usually the case in trial data
begsel = round(range(1)*opt.fsample+begsample-offset-1);
endsel = round(range(2)*opt.fsample+begsample-offset);
elseif strcmp(opt.trialname, 'segment')
% this is appropriate when the offset is defined according to
% one trigger, which is always the case in segment data [I think ingnie]
begsel = round(range(1)*opt.fsample+1);
endsel = round(range(2)*opt.fsample+1);
end
% the selection should always be confined to the current trial
begsel = max(begsample, begsel);
endsel = min(endsample, endsel);
otherwise
error('unknown opt.cfg.viewmode "%s"', opt.cfg.viewmode);
end % switch
if strcmp(opt.cfg.selectmode, 'disp')
% FIXME this is only for debugging
disp([begsel endsel])
elseif strcmp(opt.cfg.selectmode, 'mark')
% mark or unmark artifacts
artval = opt.artdata.trial{1}(opt.ftsel, begsel:endsel);
artval = any(artval,1);
if any(artval)
fprintf('there is overlap with the active artifact (%s), disable this artifact\n',opt.artdata.label{opt.ftsel});
opt.artdata.trial{1}(opt.ftsel, begsel:endsel) = 0;
else
fprintf('there is no overlap with the active artifact (%s), mark this as a new artifact\n',opt.artdata.label{opt.ftsel});
opt.artdata.trial{1}(opt.ftsel, begsel:endsel) = 1;
end
elseif strcmp(opt.cfg.selectmode, 'eval')
% cut out the requested data segment
seldata.label = opt.curdat.label;
seldata.time{1} = offset2time(offset+begsel-begsample, opt.fsample, endsel-begsel+1);
seldata.trial{1} = ft_fetch_data(opt.curdat, 'begsample', begsel, 'endsample', endsel);
seldata.fsample = opt.fsample;
seldata.cfg.trl = [begsel endsel offset];
feval(opt.cfg.selfun, opt.cfg.selcfg, seldata);
else
error('unknown value for cfg.selectmode');
end
guidata(h, opt);
redraw_cb(h);
end % function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function keyboard_cb(h, eventdata)
opt = guidata(h);
if isempty(eventdata)
% determine the key that corresponds to the uicontrol element that was activated
key = get(h, 'userdata');
h = getparent(h);
else
% determine the key that was pressed on the keyboard
key = eventdata.Key;
if ~isempty(eventdata.Modifier)
key = [eventdata.Modifier{1} '+' key];
end
end
switch key
case {'1' '2' '3' '4' '5' '6' '7' '8' '9'}
% switch to another artifact type
opt.ftsel = str2double(key);
numart = size(opt.artdata.trial{1}, 1);
if opt.ftsel > numart
fprintf('data has no artifact type %i \n', opt.ftsel)
else
guidata(h, opt);
fprintf('switching to the "%s" artifact\n', opt.artdata.label{opt.ftsel});
redraw_cb(h, eventdata);
end
case {'shift+1' 'shift+2' 'shift+3' 'shift+4' 'shift+5' 'shift+6' 'shift+7' 'shift+8' 'shift+9'}
% go to previous artifact
opt.ftsel = str2double(key(end));
numart = size(opt.artdata.trial{1}, 1);
if opt.ftsel > numart
fprintf('data has no artifact type %i \n', opt.ftsel)
else
cursam = opt.trlvis(opt.trlop,1);
artsam = find(opt.artdata.trial{1}(opt.ftsel,1:cursam-1), 1, 'last');
if isempty(artsam)
fprintf('no earlier "%s" artifact found\n', opt.artdata.label{opt.ftsel});
else
fprintf('going to previous "%s" artifact\n', opt.artdata.label{opt.ftsel});
if opt.trlvis(nearest(opt.trlvis(:,1),artsam),1) < artsam
arttrl = nearest(opt.trlvis(:,1),artsam);
else
arttrl = nearest(opt.trlvis(:,1),artsam)-1;
end
opt.trlop = arttrl;
guidata(h, opt);
redraw_cb(h, eventdata);
end
end
case {'control+1' 'control+2' 'control+3' 'control+4' 'control+5' 'control+6' 'control+7' 'control+8' 'control+9' 'alt+1' 'alt+2' 'alt+3' 'alt+4' 'alt+5' 'alt+6' 'alt+7' 'alt+8' 'alt+9'}
% go to next artifact
opt.ftsel = str2double(key(end));
numart = size(opt.artdata.trial{1}, 1);
if opt.ftsel > numart
fprintf('data has no artifact type %i \n', opt.ftsel)
else
cursam = opt.trlvis(opt.trlop,2);
artsam = find(opt.artdata.trial{1}(opt.ftsel,cursam+1:end), 1, 'first') + cursam;
if isempty(artsam)
fprintf('no later "%s" artifact found\n', opt.artdata.label{opt.ftsel});
else
fprintf('going to next "%s" artifact\n', opt.artdata.label{opt.ftsel});
if opt.trlvis(nearest(opt.trlvis(:,1),artsam),1) < artsam
arttrl = nearest(opt.trlvis(:,1),artsam);
else
arttrl = nearest(opt.trlvis(:,1),artsam)-1;
end
opt.trlop = arttrl;
guidata(h, opt);
redraw_cb(h, eventdata);
end
end
case 'leftarrow'
opt.trlop = max(opt.trlop - 1, 1); % should not be smaller than 1
guidata(h, opt);
redraw_cb(h, eventdata);
case 'rightarrow'
opt.trlop = min(opt.trlop + 1, size(opt.trlvis,1)); % should not be larger than the number of trials
guidata(h, opt);
redraw_cb(h, eventdata);
case 'uparrow'
chansel = match_str(opt.hdr.label, opt.cfg.channel);
minchan = min(chansel);
numchan = length(chansel);
chansel = minchan - numchan : minchan - 1;
if min(chansel)<1
chansel = chansel - min(chansel) + 1;
end
% convert numeric array into cell-array with channel labels
opt.cfg.channel = opt.hdr.label(chansel);
disp(opt.cfg.channel);
guidata(h, opt);
redraw_cb(h, eventdata);
case 'downarrow'
chansel = match_str(opt.hdr.label, opt.cfg.channel);
maxchan = max(chansel);
numchan = length(chansel);
chansel = maxchan + 1 : maxchan + numchan;
if max(chansel)>length(opt.hdr.label)
chansel = chansel - (max(chansel) - length(opt.hdr.label));
end
% convert numeric array into cell-array with channel labels
opt.cfg.channel = opt.hdr.label(chansel);
disp(opt.cfg.channel);
guidata(h, opt);
redraw_cb(h, eventdata);
case 'shift+leftarrow'
opt.cfg.blocksize = opt.cfg.blocksize*sqrt(2);
disp(opt.cfg.blocksize);
guidata(h, opt);
definetrial_cb(h, eventdata);
redraw_cb(h, eventdata);
case 'shift+rightarrow'
opt.cfg.blocksize = opt.cfg.blocksize/sqrt(2);
disp(opt.cfg.blocksize);
guidata(h, opt);
definetrial_cb(h, eventdata);
redraw_cb(h, eventdata);
case 'shift+uparrow'
opt.cfg.zscale = opt.cfg.zscale/sqrt(2);
guidata(h, opt);
redraw_cb(h, eventdata);
case 'shift+downarrow'
opt.cfg.zscale = opt.cfg.zscale*sqrt(2);
guidata(h, opt);
redraw_cb(h, eventdata);
case 'q'
guidata(h, opt);
cleanup_cb(h);
case 't'
% select the trial to display
response = inputdlg(sprintf('%s to display', opt.trialname), 'specify', 1, {num2str(opt.trlop)});
if ~isempty(response)
opt.trlop = str2double(response);
opt.trlop = min(opt.trlop, size(opt.trlvis,1)); % should not be larger than the number of trials
opt.trlop = max(opt.trlop, 1); % should not be smaller than 1
end
guidata(h, opt);
redraw_cb(h, eventdata);
case 'h'
% select the horizontal scaling
response = inputdlg('horizontal scale', 'specify', 1, {num2str(opt.cfg.blocksize)});
if ~isempty(response)
opt.cfg.blocksize = str2double(response);
end
guidata(h, opt);
definetrial_cb(h, eventdata);
redraw_cb(h, eventdata);
case 'v'
% select the vertical scaling
response = inputdlg('vertical scale, number or ''maxabs'')', 'specify', 1, {num2str(opt.cfg.zscale)});
if ~isempty(response)
if isnan(str2double(response)) && strcmp(response, 'maxabs')
minval = min(opt.curdat.trial{1}(:));
maxval = max(opt.curdat.trial{1}(:));
opt.cfg.zscale = max(abs([minval maxval]));
else
opt.cfg.zscale = str2double(response);
end
end
guidata(h, opt);
redraw_cb(h, eventdata);
case 'c'
% select channels
select = match_str(opt.hdr.label, opt.cfg.channel);
select = select_channel_list(opt.hdr.label, select);
opt.cfg.channel = opt.hdr.label(select);
guidata(h, opt);
redraw_cb(h, eventdata);
case 'i'
if strcmp(opt.cfg.viewmode, 'butterfly')
% click in data and get name of nearest channel
fprintf('click in the figure to identify the name of the closest channel\n');
val = ginput(1);
channame = val2nearestchan(opt.curdat,val);
channb = match_str(opt.curdat.label,channame);
fprintf('channel name: %s\n',channame);
redraw_cb(h, eventdata);
hold on
xtext = opt.cfg.zscale - 0.1*opt.cfg.zscale;
ft_plot_text(val(1), xtext, channame, 'FontSize', 16);
plot(opt.curdat.time{1}, opt.curdat.trial{1}(channb,:),'k','LineWidth',2)
end
case 'control+control'
% do nothing
case 'shift+shift'
% do nothing
case 'alt+alt'
% do nothing
otherwise
guidata(h, opt);
help_cb(h);
end
uiresume(h);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function toggle_viewmode_cb(h, eventdata, varargin)
opt = guidata(getparent(h));
if ~isempty(varargin) && ischar(varargin{1})
opt.cfg.viewmode = varargin{1};
end
guidata(getparent(h), opt);
redraw_cb(h);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function h = getparent(h)
p = h;
while p~=0
h = p;
p = get(h, 'parent');
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function redraw_cb(h, eventdata)
h = getparent(h);
opt = guidata(h);
figure(h); % ensure that the calling figure is in the front
fprintf('redrawing with viewmode %s\n', opt.cfg.viewmode);
begsample = opt.trlvis(opt.trlop, 1);
endsample = opt.trlvis(opt.trlop, 2);
offset = opt.trlvis(opt.trlop, 3);
chanindx = match_str(opt.hdr.label, opt.cfg.channel);
if ~isempty(opt.event)
% select only the events in the current time window
event = opt.event;
evtsample = [event(:).sample];
event = event(evtsample>=begsample & evtsample<=endsample);
else
event = [];
end
if isempty(opt.orgdata)
fprintf('reading data... ');
dat = ft_read_data(opt.cfg.datafile, 'header', opt.hdr, 'begsample', begsample, 'endsample', endsample, 'chanindx', chanindx, 'checkboundary', strcmp(opt.cfg.continuous, 'no'), 'dataformat', opt.cfg.dataformat, 'headerformat', opt.cfg.headerformat);
else
fprintf('fetching data... ');
dat = ft_fetch_data(opt.orgdata, 'header', opt.hdr, 'begsample', begsample, 'endsample', endsample, 'chanindx', chanindx);
end
fprintf('done\n');
fprintf('fetching artifacts... ');
art = ft_fetch_data(opt.artdata, 'begsample', begsample, 'endsample', endsample);
fprintf('done\n');
% apply preprocessing and determine the time axis
fprintf('preprocessing data... ');
[dat, lab, tim] = preproc(dat, opt.hdr.label(chanindx), opt.fsample, opt.cfg.preproc, offset);
fprintf('done\n');
opt.curdat.label = lab;
opt.curdat.time{1} = tim;
opt.curdat.trial{1} = dat;
opt.curdat.fsample = opt.fsample;
opt.curdat.cfg.trl = [begsample endsample offset];
% apply scaling to selected channels
% using wildcard to support subselection of channels
if ~isempty(opt.cfg.megscale)
chansel = match_str(lab, ft_channelselection('MEG*', lab));
dat(chansel,:) = dat(chansel,:) .* opt.cfg.megscale;
end
if ~isempty(opt.cfg.eegscale)
chansel = match_str(lab, ft_channelselection('EEG*', lab));
dat(chansel,:) = dat(chansel,:) .* opt.cfg.eegscale;
end
if ~isempty(opt.cfg.eogscale)
chansel = match_str(lab, ft_channelselection('EOG*', lab));
dat(chansel,:) = dat(chansel,:) .* opt.cfg.eogscale;
end
if ~isempty(opt.cfg.ecgscale)
chansel = match_str(lab, ft_channelselection('ECG*', lab));
dat(chansel,:) = dat(chansel,:) .* opt.cfg.ecgscale;
end
if ~isempty(opt.cfg.emgscale)
chansel = match_str(lab, ft_channelselection('EMG*', lab));
dat(chansel,:) = dat(chansel,:) .* opt.cfg.emgscale;
end
fprintf('plotting data... ');
switch opt.cfg.viewmode
case 'butterfly'
cla; % clear the content in the current axis
% to assure current feature is plotted on top
ordervec = 1:length(opt.artdata.label);
ordervec(opt.ftsel) = [];
ordervec(end+1) = opt.ftsel;
for i = ordervec
tmp = diff([0 art(i,:) 0]);
artbeg = find(tmp==+1);
artend = find(tmp==-1) - 1;
for j=1:numel(artbeg)
ft_plot_box([tim(artbeg(j)) tim(artend(j)) -opt.cfg.zscale opt.cfg.zscale], 'facecolor', opt.artcol(i,:), 'edgecolor', 'none');
end
end
h_event = zeros(0, length(event));
h_event_txt = zeros(0, length(event));
if ~opt.resampled
try
% plot a line with text for each event
for k=1:length(event)
try
eventstr = sprintf('%s=%s', event(k).type, num2str(event(k).value)); %value can be both number and string
catch
eventstr = 'unknown';
end
eventtim = (event(k).sample-begsample+offset)/opt.fsample;
eventtim = (eventtim - opt.hlim(1)) / (opt.hlim(2) - opt.hlim(1)); % convert to value relative to box, i.e. from 0 to 1
eventtim = eventtim * (opt.hpos(2) - opt.hpos(1)) + opt.hpos(1); % convert from relative to actual value along the horizontal figure axis
h_event(k) = ft_plot_line([eventtim eventtim], [0 1]);
% h_event(k) = ft_plot_line([eventtim eventtim], [-opt.cfg.zscale opt.cfg.zscale]);
h_event_txt(k) = ft_plot_text(eventtim, ax(4)-0.01, eventstr);
end
end % try
else
if isfield(opt, 'orgdata') && isfield(opt.orgdata, 'sampleinfo') && isfield(opt.orgdata, 'offset')
% find trials within this segment
trlindx = find(((opt.orgdata.sampleinfo(:, 1)-opt.orgdata.offset) >= begsample & (opt.orgdata.sampleinfo(:, 1)-opt.orgdata.offset) <= endsample)==1);
for t = 1:numel(trlindx)
eventtim = (opt.orgdata.sampleinfo(trlindx(t), 1)-opt.orgdata.offset(trlindx(t))-begsample+offset)/opt.fsample;
eventtim = (eventtim - opt.hlim(1)) / (opt.hlim(2) - opt.hlim(1)); % convert to value relative to box, i.e. from 0 to 1
eventtim = eventtim * (opt.hpos(2) - opt.hpos(1)) + opt.hpos(1); % convert from relative to actual value along the horizontal figure axis
h_event(end+1) = ft_plot_line([eventtim eventtim], [-opt.cfg.zscale 1]);
h_event_txt(end+1) = ft_plot_text(eventtim, ax(4)+.01, 'stim');
end
end
end
set(h_event, 'tag', 'events');
set(h_event_txt, 'tag', 'events');
set(gca,'ColorOrder',opt.chan_colors(chanindx,:)) % plot vector does not clear axis, therefore this is possible
% plot the data on top of the box
h_act = ft_plot_vector(tim, dat);
set(h_act, 'tag', 'activations');
ax(1) = tim(1);
ax(2) = tim(end);
ax(3) = -opt.cfg.zscale;
ax(4) = opt.cfg.zscale;
axis(ax);
title(sprintf('%s %d, time from %g to %g s', opt.trialname, opt.trlop, tim(1), tim(end)));
xlabel('time');
% set tags
case 'vertical'
cla; % clear the content in the current axis
tmpcfg = [];
tmpcfg.layout = 'vertical';
tmpcfg.channel = opt.cfg.channel;
tmpcfg.skipcomnt = 'yes';
tmpcfg.skipscale = 'yes';
laytime = ft_prepare_layout(tmpcfg, opt.orgdata);
hlim = [tim(1) tim(end)];
vlim = [-opt.cfg.zscale +opt.cfg.zscale];
% determine the position of each of the labels
labelx = laytime.pos(:,1) - laytime.width/2 - 0.01;
labely = laytime.pos(:,2);
ax(1) = min(laytime.pos(:,1) - laytime.width/2);
ax(2) = max(laytime.pos(:,1) + laytime.width/2);
ax(3) = min(laytime.pos(:,2) - laytime.height/2);
ax(4) = max(laytime.pos(:,2) + laytime.height/2);
axis(ax)
% remember the scaling of the horizontal axis, this is needed for mouse input
hpos(1) = laytime.pos(1,1) - laytime.width(1)/2; % the position of the left side of the timecourse box
hpos(2) = laytime.pos(1,1) + laytime.width(1)/2; % the position of the right side of the timecourse box
opt.hlim = hlim;
opt.hpos = hpos;
% to assure current feature is plotted on top
ordervec = 1:length(opt.artdata.label);
ordervec(opt.ftsel) = [];
ordervec(end+1) = opt.ftsel;
for j = ordervec
tmp = diff([0 art(j,:) 0]);
artbeg = find(tmp==+1);
artend = find(tmp==-1) - 1;
arttim = [tim(artbeg)' tim(artend)']; % convert the artifact sample number to time
arttim = (arttim - opt.hlim(1)) / (opt.hlim(2) - opt.hlim(1)); % convert to value relative to box, i.e. from 0 to 1
arttim = arttim * (opt.hpos(2) - opt.hpos(1)) + opt.hpos(1); % convert from relative to actual value along the horizontal figure axis
for k=1:numel(artbeg)
ft_plot_box([arttim(k,1) arttim(k,2) ax(3) ax(4)], 'facecolor', opt.artcol(j,:), 'edgecolor', 'none');
end
end % for each of the artifact channels
h_event = zeros(0, length(event));
h_event_txt = zeros(0, length(event));
if ~opt.resampled
% plot a line with text for each event
for k=1:length(event)
try
eventstr = sprintf('%s=%s', event(k).type, num2str(event(k).value)); %value can be both number and string
catch
eventstr = 'unknown';
end
eventtim = (event(k).sample-begsample+offset)/opt.fsample;
eventtim = (eventtim - opt.hlim(1)) / (opt.hlim(2) - opt.hlim(1)); % convert to value relative to box, i.e. from 0 to 1
eventtim = eventtim * (opt.hpos(2) - opt.hpos(1)) + opt.hpos(1); % convert from relative to actual value along the horizontal figure axis
h_event(k) = ft_plot_line([eventtim eventtim], [0 1]);
% h_event(k) = ft_plot_line([eventtim eventtim], [-opt.cfg.zscale opt.cfg.zscale]);
h_event_txt(k) = ft_plot_text(eventtim, ax(4)-0.01, eventstr);
end
else
if isfield(opt, 'orgdata') && isfield(opt.orgdata, 'sampleinfo') && isfield(opt.orgdata, 'offset')
% find trials within this segment
trlindx = find(((opt.orgdata.sampleinfo(:, 1)-opt.orgdata.offset) >= begsample & (opt.orgdata.sampleinfo(:, 1)-opt.orgdata.offset) <= endsample)==1);
for t = 1:numel(trlindx)
eventtim = (opt.orgdata.sampleinfo(trlindx(t), 1)-opt.orgdata.offset(trlindx(t))-begsample+offset)/opt.fsample;
eventtim = (eventtim - opt.hlim(1)) / (opt.hlim(2) - opt.hlim(1)); % convert to value relative to box, i.e. from 0 to 1
eventtim = eventtim * (opt.hpos(2) - opt.hpos(1)) + opt.hpos(1); % convert from relative to actual value along the horizontal figure axis
h_event(end+1) = ft_plot_line([eventtim eventtim], [-opt.cfg.zscale 1]);
h_event_txt(end+1) = ft_plot_text(eventtim, ax(4)+.01, 'stim');
end
end
end
% set tags
set(h_event, 'tag', 'events');
set(h_event_txt, 'tag', 'events');
for i = 1:length(chanindx)
datsel = i;
laysel = match_str(laytime.label, opt.hdr.label(chanindx(i)));
if ~isempty(datsel)
h_text = ft_plot_text(labelx(laysel), labely(laysel), opt.hdr.label(chanindx(i)), 'HorizontalAlignment', 'right');
h_act = ft_plot_vector(tim, dat(datsel, :), 'hpos', laytime.pos(laysel,1), 'vpos', laytime.pos(laysel,2), 'width', laytime.width(laysel), 'height', laytime.height(laysel), 'hlim', hlim, 'vlim', vlim, 'box', false, 'color', opt.chan_colors(chanindx(i),:));
end
end
% set tags
set(h_text, 'tag', 'activations');
set(h_act, 'tag', 'activations');
nticks = 11;
set(gca, 'xTick', linspace(ax(1), ax(2), nticks))
xTickLabel = cellstr(num2str( linspace(tim(1), tim(end), nticks)' , '%1.2f'))';
set(gca, 'xTickLabel', xTickLabel)
set(gca, 'yTick', [])
if length(chanindx)<7
% two ticks per channel
set(gca, 'yTick', sort([laytime.pos(:,2)+(laytime.height(laysel)/2); laytime.pos(:,2)+(laytime.height(laysel)/4); laytime.pos(:,2)-(laytime.height(laysel)/4); laytime.pos(:,2)-(laytime.height(laysel)/2)]))
yTickLabel = {num2str(-vlim(2)), num2str(-vlim(2)/2), num2str(vlim(2)/2), num2str(vlim(2))};
elseif length(chanindx)> 6 && length(chanindx)< 20
% one tick per channel
set(gca, 'yTick', sort([laytime.pos(:,2)+(laytime.height(laysel)/4); laytime.pos(:,2)-(laytime.height(laysel)/4)]))
yTickLabel = {num2str(-vlim(2)/2), num2str(vlim(2)/2)};
else
% no space for xticks
yTickLabel = [];
end
tmp = yTickLabel;
for chanloop = 2:length(chanindx)
yTickLabel = [yTickLabel tmp];
end
set(gca, 'yTickLabel', yTickLabel)
title(sprintf('%s %d, time from %g to %g s', opt.trialname, opt.trlop, tim(1), tim(end)));
case 'component'
% delete time courses
delete(findobj(h,'tag', 'activations'));
delete(findobj(h,'tag', 'events'));
delete(findobj(h,'tag', 'artifacts'));
compindx = chanindx;
clear chanindx
tmpcfg = [];
tmpcfg.layout = 'vertical';
tmpcfg.channel = opt.cfg.channel;
tmpcfg.skipcomnt = 'yes';
tmpcfg.skipscale = 'yes';
laytime = ft_prepare_layout(tmpcfg, opt.orgdata);
ax(1) = min(laytime.pos(:,1) - laytime.width/2);
ax(2) = max(laytime.pos(:,1) + laytime.width/2);
ax(3) = min(laytime.pos(:,2) - laytime.height/2);
ax(4) = max(laytime.pos(:,2) + laytime.height/2);
tmpcfg = [];
tmpcfg.layout = opt.cfg.layout;
laychan = ft_prepare_layout(tmpcfg, opt.orgdata);
% determine the position of each of the topographies
laytopo.pos(:,1) = laytime.pos(:,1) - laytime.width/2 - laytime.height*2;
laytopo.pos(:,2) = laytime.pos(:,2);
laytopo.width = laytime.height;
laytopo.height = laytime.height;
laytopo.label = laytime.label;
% determine the position of each of the labels
labelx = laytopo.pos(:,1) + laytopo.width;
labely = laytopo.pos(:,2);
hlim = [tim(1) tim(end)];
vlim = [-opt.cfg.zscale +opt.cfg.zscale];
hpos(1) = laytime.pos(1,1) - laytime.width(1)/2; % the position of the left side of the timecourse box
hpos(2) = laytime.pos(1,1) + laytime.width(1)/2; % the position of the right side of the timecourse box
opt.hlim = hlim;
opt.hpos = hpos;
% check if topographies need to be redrawn
redraw_topo = false;
if ~isequal(opt.compindx, compindx)
redraw_topo = true;
cla; % clear axis
end
% to assure current feature is plotted on top
ordervec = 1:length(opt.artdata.label);
ordervec(opt.ftsel) = [];
ordervec(end+1) = opt.ftsel;
h_art = cell(1, ordervec);
for j = ordervec
tmp = diff([0 art(j,:) 0]);
artbeg = find(tmp==+1);
artend = find(tmp==-1) - 1;
arttim = [tim(artbeg)' tim(artend)']; % convert the artifact sample number to time
arttim = (arttim - opt.hlim(1)) / (opt.hlim(2) - opt.hlim(1)); % convert to value relative to box, i.e. from 0 to 1
arttim = arttim * (opt.hpos(2) - opt.hpos(1)) + opt.hpos(1); % convert from relative to actual value along the horizontal figure axis
h_art{j} = zeros(1, length(artbeg));
for k=1:numel(artbeg)
h_art{j}(k) = ft_plot_box([arttim(k,1) arttim(k,2) ax(3) ax(4)], 'facecolor', opt.artcol(j,:), 'edgecolor', 'none');
end
end % for each of the artifact channels
[sel1, sel2] = match_str(opt.orgdata.topolabel, laychan.label);
chanx = laychan.pos(sel2,1);
chany = laychan.pos(sel2,2);
h_act = zeros(1, length(compindx));
h_text = zeros(1, length(compindx));
for i=1:length(compindx)
datsel = i;
laysel = match_str(laytime.label,opt.hdr.label(compindx(i)));
if ~isempty(datsel)
% plot the timecourse of this component
h_act(i) = ft_plot_vector(tim, dat(datsel, :), 'hpos', laytime.pos(laysel,1), 'vpos', laytime.pos(laysel,2), 'width', laytime.width(laysel), 'height', laytime.height(laysel), 'hlim', hlim, 'vlim', vlim);
if redraw_topo
h_text(i) = ft_plot_text(labelx(laysel), labely(laysel), opt.hdr.label(compindx(i)));
% plot the topography of this component
chanz = opt.orgdata.topo(sel1,compindx(i));
ft_plot_topo(chanx, chany, chanz./max(abs(chanz)), 'hpos', laytopo.pos(laysel,1), ...
'vpos', laytopo.pos(laysel,2), 'mask', laychan.mask, ...
'interplim', 'mask', 'outline', laychan.outline, ...
'width', laytopo.width(laysel), 'height', laytopo.height(laysel));
end
axis equal
drawnow
end
end
% draw events
h_event = zeros(0, length(event));
h_event_txt = zeros(0, length(event));
if ~opt.resampled
% plot a line with text for each event
for k=1:length(event)
try
eventstr = sprintf('%s=%s', event(k).type, num2str(event(k).value)); %value can be both number and string
catch
eventstr = 'unknown';
end
eventtim = (event(k).sample-begsample+offset)/opt.fsample;
eventtim = (eventtim - opt.hlim(1)) / (opt.hlim(2) - opt.hlim(1)); % convert to value relative to box, i.e. from 0 to 1
eventtim = eventtim * (opt.hpos(2) - opt.hpos(1)) + opt.hpos(1); % convert from relative to actual value along the horizontal figure axis
h_event(k) = ft_plot_line([eventtim eventtim], [0 1]);
% h_event(k) = ft_plot_line([eventtim eventtim], [-opt.cfg.zscale opt.cfg.zscale]);
h_event_txt(k) = ft_plot_text(eventtim, ax(4)-0.01, eventstr);
end
else
if isfield(opt, 'orgdata') && isfield(opt.orgdata, 'sampleinfo') && isfield(opt.orgdata, 'offset')
% find trials within this segment
trlindx = find(((opt.orgdata.sampleinfo(:, 1)-opt.orgdata.offset) >= begsample & (opt.orgdata.sampleinfo(:, 1)-opt.orgdata.offset) <= endsample)==1);
for t = 1:numel(trlindx)
eventtim = (opt.orgdata.sampleinfo(trlindx(t), 1)-opt.orgdata.offset(trlindx(t))-begsample+offset)/opt.fsample;
eventtim = (eventtim - opt.hlim(1)) / (opt.hlim(2) - opt.hlim(1)); % convert to value relative to box, i.e. from 0 to 1
eventtim = eventtim * (opt.hpos(2) - opt.hpos(1)) + opt.hpos(1); % convert from relative to actual value along the horizontal figure axis
h_event(end+1) = ft_plot_line([eventtim eventtim], [-opt.cfg.zscale 1]);
h_event_txt(end+1) = ft_plot_text(eventtim, ax(4)+.01, 'stim');
end
end
end
% set tags
set(h_event, 'tag', 'events');
set(h_event_txt, 'tag', 'events');
set(h_act, 'tag', 'activations');
for k = 1:numel(h_art)
set(h_art{k}, 'tag', 'artifacts');
end
h_topo = findobj(h, 'type', 'surface');
set(h_text, 'tag', 'comptopo')
set(h_topo, 'tag', 'comptopo')
opt.compindx = compindx;
set(gca, 'xTick', [])
set(gca, 'yTick', [])
title(sprintf('%s %d, time from %g to %g s', opt.trialname, opt.trlop, tim(1), tim(end)));
ax(1) = min(laytopo.pos(:,1) - laytopo.width/2);
ax(2) = max(laytime.pos(:,1) + laytime.width/2);
ax(3) = min(laytime.pos(:,2) - laytime.height/2);
ax(4) = max(laytime.pos(:,2) + laytime.height/2);
axis(ax)
% remember the scaling of the horizontal axis, this is needed for mouse input
hpos(1) = laytime.pos(1,1) - laytime.width(1)/2; % the position of the left side of the timecourse box
hpos(2) = laytime.pos(1,1) + laytime.width(1)/2; % the position of the right side of the timecourse box
opt.hlim = hlim;
opt.hpos = hpos;
case 'settings'
% FIXME implement further details
otherwise
error('unknown viewmode "%s"', opt.cfg.viewmode);
end % switch viewmode
fprintf('done\n');
guidata(h, opt);
end
|
github
|
philippboehmsturm/antx-master
|
ft_volumesegment.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_volumesegment.m
| 22,470 |
utf_8
|
78a76e125b0adb93d8d39508455d1428
|
function [segment] = ft_volumesegment(cfg, mri)
% FT_VOLUMESEGMENT segments an anatomical MRI. The behaviour depends on the
% output requested. It can return probabilistic tissue maps of
% gray/white/csf compartments, a skull-stripped anatomy, or binary masks
% representing the brain surface, skull, or scalp surface.
%
% This function uses the SPM8 toolbox, see http://www.fil.ion.ucl.ac.uk/spm/
%
% Use as
% [segment] = ft_volumesegment(cfg, mri)
%
% The input arguments are a configuration structure (see below) and an
% anatomical MRI structure. Instead of an MRI structure, you can also
% specify a string with a filename of an MRI file. You can also provide an
% already segmented volume in the input for the purpose of creating a
% binary mask.
%
% The configuration options are
% cfg.output = 'tpm' (default), 'brain', 'skull', 'skullstrip', 'scalp', or any
% combination of these in a cell-array
% cfg.spmversion = 'spm8' (default) or 'spm2'
% cfg.template = filename of the template anatomical MRI (default is the 'T1.nii'
% (spm8) or 'T1.mnc' (spm2) in the (spm-directory)/templates/)
% cfg.name = string for output filename
% cfg.write = 'no' or 'yes' (default = 'no'),
% writes the probabilistic tissue maps to SPM compatible analyze (spm2),
% or nifti (spm8) files,
% with the suffix (spm2)
% _seg1, for the gray matter segmentation
% _seg2, for the white matter segmentation
% _seg3, for the csf segmentation
% or with the prefix (spm8)
% c1, for the gray matter segmentation
% c2, for the white matter segmentation
% c3, for the csf segmentation
%
% cfg.smooth = 'no', or scalar, the FWHM of the gaussian kernel in
% voxels, default depends on the requested output
% cfg.threshold = 'no', or scalar, relative threshold value which is
% used to threshold the data in order to create a
% volumetric mask (see below).
% the default depends on the requested output
% cfg.downsample = integer, amount of downsampling before segmentation
% (default = 1; i.e., no downsampling)
% cfg.coordsys = string, specifying the coordinate system in which the
% anatomical data is defined. This will be used if
% the input mri does not contain a coordsys-field.
% (default = '', which results in the user being
% forced to evaluate the coordinate system)
% cfg.units = the physical units in which the output will be
% expressed. (default = 'mm')
%
% Example use:
%
% segment = ft_volumesegment([], mri) will segment the anatomy and will output
% the segmentation result as 3 probabilistic masks in
% segment.gray/.white/.csf
%
% cfg.output = 'skullstrip';
% segment = ft_volumesegment(cfg, mri) will generate a skullstripped anatomy
% based on a brainmask generated from the probabilistic
% tissue maps. The skull-stripped anatomy is be stored in
% the field segment.anatomy.
%
%
% cfg.output = {'brain' 'scalp' 'skull'};
% segment = ft_volumesegment(cfg, mri) will produce a volume with 3 binary
% masks, representing the brain surface, scalp surface, and skull
%
% For the SPM-based segmentation to work, the coordinate frame of the input
% MRI needs to be approximately coregistered to the templates of the
% probabilistic tissue maps. The templates are defined in SPM/MNI-space.
% FieldTrip attempts to do an automatic alignment based on the
% coordsys-field in the mri, and if this is not present, based on the
% coordsys-field in the cfg. If none of them is specified the
% FT_DETERMINE_COORDSYS function is used to interactively assess the
% coordinate system in which the MRI is expressed.
%
% The template mri is defined in SPM/MNI-coordinates:
% x-axis pointing to the right ear
% y-axis along the acpc-line
% z-axis pointing to the top of the head
% origin in the anterior commissure.
% Note that the segmentation only works if the template MRI is in SPM
% coordinates.
%
% If the input mri is a string pointing to a CTF *.mri file, the
% x-axis is assumed to point to the nose, and the origin is assumed
% to be on the interauricular line. In this specific case, when ft_read_mri
% is used to read in the mri, the coordsys field is automatically attached.
%
% To facilitate data-handling and distributed computing with the peer-to-peer
% module, this function has the following options:
% cfg.inputfile = ...
% cfg.outputfile = ...
% If you specify one of these (or both) the input data will be read from a *.mat
% file on disk and/or the output data will be written to a *.mat file. These mat
% files should contain only a single variable, corresponding with the
% input/output structure.
%
% See also FT_READ_MRI FT_DETERMINE_COORDSYS
% undocumented options
% cfg.keepintermediate = 'yes' or 'no'
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_volumesegment.m 3735 2011-06-29 08:22:09Z jorhor $
ft_defaults
cfg = ft_checkconfig(cfg, 'trackconfig', 'on');
cfg = ft_checkconfig(cfg, 'renamed', {'coordinates', 'coordsys'});
% set the defaults
cfg.output = ft_getopt(cfg, 'output', 'tpm');
cfg.downsample = ft_getopt(cfg, 'downsample', 1);
cfg.spmversion = ft_getopt(cfg, 'spmversion', 'spm8');
cfg.write = ft_getopt(cfg, 'write', 'no');
cfg.keepintermediate = ft_getopt(cfg, 'keepintermediate', 'no');
cfg.coordsys = ft_getopt(cfg, 'coordsys', '');
cfg.units = ft_getopt(cfg, 'units', '');
cfg.inputfile = ft_getopt(cfg, 'inputfile', []);
cfg.outputfile = ft_getopt(cfg, 'outputfile', []);
% check if the required spm is in your path:
if strcmpi(cfg.spmversion, 'spm2'),
ft_hastoolbox('SPM2',1);
elseif strcmpi(cfg.spmversion, 'spm8'),
ft_hastoolbox('SPM8',1);
end
% get the names of the templates for the segmentation
if ~isfield(cfg, 'template'),
spmpath = spm('dir');
if strcmpi(cfg.spmversion, 'spm8'), cfg.template = [spmpath,filesep,'templates',filesep,'T1.nii']; end
if strcmpi(cfg.spmversion, 'spm2'), cfg.template = [spmpath,filesep,'templates',filesep,'T1.mnc']; end
end
if ~isfield(cfg,'name')
if ~strcmp(cfg.write,'yes')
tmp = tempname;
cfg.name = tmp;
else
error('you must specify the output filename in cfg.name');
end
end
if ~iscell(cfg.output)
% ensure it to be cell, to allow for multiple outputs
cfg.output = {cfg.output};
end
for k = 1:numel(cfg.output)
% set defaults for the smoothing and thresholding if needed
switch cfg.output{k}
case 'tpm'
tmp = ft_getopt(cfg, 'smooth', nan);
if ischar(tmp) && strcmp(tmp, 'no')
cfgsmooth(k) = nan;
elseif ischar(tmp)
error('invalid value %s for cfg.smooth', tmp);
else
cfgsmooth(k) = tmp;
end
cfgthreshold(k) = ft_getopt(cfg, 'threshold', nan);
case {'skullstrip' 'brain' 'skull'}
tmp = ft_getopt(cfg, 'smooth', 5);
if ischar(tmp) && strcmp(tmp, 'no')
cfgsmooth(k) = nan;
elseif ischar(tmp)
error('invalid value %s for cfg.smooth', tmp);
else
cfgsmooth(k) = tmp;
end
cfgthreshold(k) = ft_getopt(cfg, 'threshold', 0.5);
case 'scalp'
tmp = ft_getopt(cfg, 'smooth', 5);
if ischar(tmp) && strcmp(tmp, 'no')
cfgsmooth(k) = nan;
elseif ischar(tmp)
error('invalid value %s for cfg.smooth', tmp);
else
cfgsmooth(k) = tmp;
end
cfgthreshold(k) = ft_getopt(cfg, 'threshold', 0.1);
otherwise
error('unknown output %s requested', cfg.output);
end
end
cfg.smooth = cfgsmooth;
cfg.threshold = cfgthreshold;
hasdata = (nargin>1);
hasinputfile = ~isempty(cfg.inputfile);
if hasdata && hasinputfile
error('cfg.inputfile should not be used in conjunction with giving input data to this function');
elseif hasinputfile
% the input data should be read from file
mri = loadvar(cfg.inputfile, 'mri');
elseif hasdata
if ischar(mri),
% read the anatomical MRI data from file
filename = mri;
fprintf('reading MRI from file\n');
mri = ft_read_mri(filename);
if ft_filetype(filename, 'ctf_mri') && isempty(cfg.coordsys)
% based on the filetype assume that the coordinates correspond with CTF convention
cfg.coordsys = 'ctf';
end
end
else
error('neither a data structure, nor a cfg.inputfile is provided');
end
% check if the input data is valid for this function
mri = ft_checkdata(mri, 'datatype', 'volume', 'feedback', 'yes');
% check whether spm is needed to generate tissue probability maps
needtpm = any(ismember(cfg.output, {'tpm' 'brain' 'skullstrip'}));
hastpm = isfield(mri, 'gray') && isfield(mri, 'white') && isfield(mri, 'csf');
if needtpm && ~hastpm
% spm needs to be used for the creation of the tissue probability maps
dotpm = 1;
else
dotpm = 0;
end
needana = any(ismember(cfg.output, {'scalp' 'skullstrip'})) || dotpm;
hasanatomy = isfield(mri, 'anatomy');
if needana && ~hasanatomy
error('the input volume needs an anatomy-field');
end
% perform optional downsampling before segmentation
if cfg.downsample ~= 1
tmpcfg = [];
tmpcfg.downsample = cfg.downsample;
tmpcfg.smooth = 'no'; % smoothing is done in ft_volumesegment itself
mri = ft_volumedownsample(tmpcfg, mri);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% create the tissue probability maps if needed
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if dotpm
% ensure that the data has interpretable units and that the coordinate
% system is in approximate spm space
if ~isfield(mri, 'unit'), mri.unit = cfg.units; end
if ~isfield(mri, 'coordsys'), mri.coordsys = cfg.coordsys; end
% remember the original transformation matrix coordinate system
original.transform = mri.transform;
original.coordsys = mri.coordsys;
mri = ft_convert_units(mri, 'mm');
mri = ft_convert_coordsys(mri, 'spm');
% flip and permute the 3D volume itself, so that the voxel and
% headcoordinates approximately correspond this improves the convergence
% of the segmentation algorithm
[mri,permutevec,flipflags] = align_ijk2xyz(mri);
Va = ft_write_volume([cfg.name,'.img'], mri.anatomy, 'transform', mri.transform, 'spmversion', cfg.spmversion);
% spm is quite noisy, prevent the warnings from displaying on screen
% warning off;
if strcmpi(cfg.spmversion, 'spm2'),
% set the spm segmentation defaults (from /opt/spm2/spm_defaults.m script)
defaults.segment.estimate.priors = str2mat(...
fullfile(spm('Dir'),'apriori','gray.mnc'),...
fullfile(spm('Dir'),'apriori','white.mnc'),...
fullfile(spm('Dir'),'apriori','csf.mnc'));
defaults.segment.estimate.reg = 0.01;
defaults.segment.estimate.cutoff = 30;
defaults.segment.estimate.samp = 3;
defaults.segment.estimate.bb = [[-88 88]' [-122 86]' [-60 95]'];
defaults.segment.estimate.affreg.smosrc = 8;
defaults.segment.estimate.affreg.regtype = 'mni';
%defaults.segment.estimate.affreg.weight = fullfile(spm('Dir'),'apriori','brainmask.mnc');
defaults.segment.estimate.affreg.weight = '';
defaults.segment.write.cleanup = 1;
defaults.segment.write.wrt_cor = 1;
flags = defaults.segment;
% perform the segmentation
fprintf('performing the segmentation on the specified volume\n');
spm_segment(Va,cfg.template,flags);
Vtmp = spm_vol({[cfg.name,'_seg1.img'];...
[cfg.name,'_seg2.img'];...
[cfg.name,'_seg3.img']});
% read the resulting volumes
for j = 1:3
vol = spm_read_vols(Vtmp{j});
Vtmp{j}.dat = vol;
V(j) = struct(Vtmp{j});
end
% keep or remove the files according to the configuration
if strcmp(cfg.keepintermediate,'no'),
delete([cfg.name,'.img']);
delete([cfg.name,'.hdr']);
delete([cfg.name,'.mat']);
end
if strcmp(cfg.write,'no'),
delete([cfg.name,'_seg1.hdr']);
delete([cfg.name,'_seg2.hdr']);
delete([cfg.name,'_seg3.hdr']);
delete([cfg.name,'_seg1.img']);
delete([cfg.name,'_seg2.img']);
delete([cfg.name,'_seg3.img']);
delete([cfg.name,'_seg1.mat']);
delete([cfg.name,'_seg2.mat']);
delete([cfg.name,'_seg3.mat']);
elseif strcmp(cfg.write,'yes'),
for j = 1:3
% put the original transformation-matrix in the headers
V(j).mat = original.transform;
% write the updated header information back to file ???????
V(j) = spm_create_vol(V(j));
end
end
elseif strcmpi(cfg.spmversion, 'spm8'),
fprintf('performing the segmentation on the specified volume\n');
if isfield(cfg, 'tpm')
px.tpm = cfg.tpm;
p = spm_preproc(Va, px);
else
p = spm_preproc(Va);
end
[po,pin] = spm_prep2sn(p);
% I took these settings from a batch
opts = [];
opts.GM = [0 0 1];
opts.WM = [0 0 1];
opts.CSF = [0 0 1];
opts.biascor = 1;
opts.cleanup = 0;
spm_preproc_write(po, opts);
[pathstr,name,ext] = fileparts(cfg.name);
Vtmp = spm_vol({fullfile(pathstr,['c1',name,'.img']);...
fullfile(pathstr,['c2',name,'.img']);...
fullfile(pathstr,['c3',name,'.img'])});
% read the resulting volumes
for j = 1:3
vol = spm_read_vols(Vtmp{j});
Vtmp{j}.dat = vol;
V(j) = struct(Vtmp{j});
end
% keep or remove the files according to the configuration
if strcmp(cfg.keepintermediate,'no'),
delete([cfg.name,'.img']);
delete([cfg.name,'.hdr']);
if exist([cfg.name,'.mat'], 'file'),
delete([cfg.name,'.mat']);
end %does not always exist
end
% keep the files written to disk or remove them
% FIXME check whether this works at all
if strcmp(cfg.write,'no'),
delete(fullfile(pathstr,['c1',name,'.hdr'])); %FIXME this may not be needed in spm8
delete(fullfile(pathstr,['c1',name,'.img']));
delete(fullfile(pathstr,['c2',name,'.hdr']));
delete(fullfile(pathstr,['c2',name,'.img']));
delete(fullfile(pathstr,['c3',name,'.hdr']));
delete(fullfile(pathstr,['c3',name,'.img']));
delete(fullfile(pathstr,['m',name,'.hdr']));
delete(fullfile(pathstr,['m',name,'.img']));
elseif strcmp(cfg.write,'yes'),
for j = 1:3
% put the original transformation-matrix in the headers
V(j).mat = original.transform;
% write the updated header information back to file ???????
V(j) = spm_create_vol(V(j));
end
end
end
% collect the results
segment.dim = size(V(1).dat);
segment.dim = segment.dim(:)'; % enforce a row vector
segment.transform = original.transform; % use the original transform
segment.coordsys = original.coordsys; % use the original coordsys
if isfield(mri, 'unit')
segment.unit = mri.unit;
end
segment.gray = V(1).dat;
if length(V)>1, segment.white = V(2).dat; end
if length(V)>2, segment.csf = V(3).dat; end
segment.anatomy = mri.anatomy;
% flip the volumes back according to the changes introduced by align_ijk2xyz
for k = 1:3
if flipflags(k)
segment.gray = flipdim(segment.gray, k);
segment.anatomy = flipdim(segment.anatomy, k);
if isfield(segment, 'white'), segment.white = flipdim(segment.white, k); end
if isfield(segment, 'csf'), segment.csf = flipdim(segment.csf, k); end
end
end
if ~all(permutevec == [1 2 3])
segment.gray = ipermute(segment.gray, permutevec);
segment.anatomy = ipermute(segment.anatomy, permutevec);
if isfield(segment, 'white'), segment.white = ipermute(segment.white, permutevec); end
if isfield(segment, 'csf'), segment.csf = ipermute(segment.csf, permutevec); end
segment.dim = size(segment.gray);
end
else
% rename the data
segment = mri;
clear mri;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% now the data contains the tissue probability maps
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% create the requested output fields
removefields = {'anatomy' 'csf' 'gray' 'white'};
for k = 1:numel(cfg.output)
dosmooth = isfinite(cfg.smooth(k));
dothresh = isfinite(cfg.threshold(k));
switch cfg.output{k}
case 'tpm'
% do nothing
if dosmooth, warning_once('You requested the tpms to be smoothed, which is not possible because does not make sense'); end
if dothresh, warning_once('You requested the tpms to be thresholded, which is not possible because it does not make sense');end
removefields = intersect(removefields, {'anatomy'});
case 'skullstrip'
% create brain surface from tissue probability maps
fprintf('creating brainmask\n');
brain = segment.gray + segment.white + segment.csf;
if dosmooth, brain = dosmoothing(brain, cfg.smooth(k), 'brainmask'); end
if dothresh, brain = threshold(brain, cfg.threshold(k), 'brainmask'); end
fprintf('creating skullstripped anatomy\n');
brain = cast(brain, class(segment.anatomy));
segment.anatomy = segment.anatomy.*brain;
removefields = intersect(removefields, {'gray' 'white' 'csf'});
clear brain;
case 'brain'
% create brain surface from tissue probability maps
fprintf('creating brainmask\n');
brain = segment.gray + segment.white + segment.csf;
if dosmooth, brain = dosmoothing(brain, cfg.smooth(k), 'brainmask'); end
if dothresh, brain = threshold(brain, cfg.threshold(k), 'brainmask'); end
segment.brain = brain>0;
removefields = intersect(removefields, {'gray' 'white' 'csf' 'anatomy'});
clear brain;
case 'skull'
% create brain surface from tissue probability maps
fprintf('creating brainmask\n');
brain = segment.gray + segment.white + segment.csf;
if dosmooth, brain = dosmoothing(brain, cfg.smooth(k), 'brainmask'); end
if dothresh, brain = threshold(brain, cfg.threshold(k), 'brainmask'); end
% create skull from brain mask FIXME check this (e.g. strel_bol)
fprintf('creating skullmask\n');
braindil = imdilate(brain>0, strel_bol(6));
segment.skull = braindil & ~brain;
removefields = intersect(removefields, {'gray' 'white' 'csf' 'anatomy'});
clear brain braindil;
case 'scalp'
% create scalp surface from anatomy
fprintf('creating scalpmask\n');
anatomy = segment.anatomy;
anatomy(1) = anatomy(1)+1-1; % ensure that spm's smoothing does not affect
% the original segment.anatomy
if dosmooth, anatomy = dosmoothing(anatomy, cfg.smooth(k), 'anatomy'); end
if dothresh, anatomy = threshold(anatomy, cfg.threshold(k), 'anatomy'); end
% fill in the holes
anatomy = fill(anatomy);
segment.scalp = anatomy>0;
removefields = intersect(removefields, {'gray' 'white' 'csf' 'anatomy'});
clear anatomy;
otherwise
error('unknown output %s requested', cfg.output);
end
end
% remove unnecessary fields
for k = 1:numel(removefields)
try, segment = rmfield(segment, removefields{k}); end
end
% accessing this field here is needed for the configuration tracking
% by accessing it once, it will not be removed from the output cfg
cfg.outputfile;
% get the output cfg
cfg = ft_checkconfig(cfg, 'trackconfig', 'off', 'checksize', 'yes');
% add version information to the configuration
cfg.version.name = mfilename('fullpath');
cfg.version.id = '$Id: ft_volumesegment.m 3735 2011-06-29 08:22:09Z jorhor $';
% add information about the Matlab version used to the configuration
cfg.callinfo.matlab = version();
% remember the configuration details of the input data
if isfield(segment, 'cfg'),
cfg.previous = segment.cfg;
end
% remember the exact configuration details in the output
segment.cfg = cfg;
% the output data should be saved to a MATLAB file
if ~isempty(cfg.outputfile)
savevar(cfg.outputfile, 'segment', segment); % use the variable name "segment" in the output file
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [output] = dosmoothing(input, fwhm, str)
fprintf('smoothing %s with a %d-voxel FWHM kernel\n', str, fwhm);
spm_smooth(input, input, fwhm);
output = input;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [output] = threshold(input, thresh, str)
fprintf('thresholding %s at a relative threshold of %0.3f\n', str, thresh);
% mask by taking the negative of the brain, thus ensuring
% that no holes are within the compartment and do a two-pass
% approach to eliminate potential vitamin E capsules etc.
output = double(input>(thresh*max(input(:))));
[tmp, N] = spm_bwlabel(output, 6);
for k = 1:N
n(k,1) = sum(tmp(:)==k);
end
output = double(tmp~=find(n==max(n))); clear tmp;
[tmp, N] = spm_bwlabel(output, 6);
for k = 1:N
m(k,1) = sum(tmp(:)==k);
end
output = double(tmp~=find(m==max(m))); clear tmp;
function [output] = fill(input)
output = input;
dim = size(input);
for i=1:dim(2)
slice=squeeze(input(:,i,:));
im = imfill(slice,8,'holes');
output(:,i,:) = im;
end
|
github
|
philippboehmsturm/antx-master
|
ft_sourceplot.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_sourceplot.m
| 45,118 |
utf_8
|
7add1886d3ca1752014d51f9fdaf2071
|
function [cfg] = ft_sourceplot(cfg, data)
% FT_SOURCEPLOT plots functional source reconstruction data on slices or on a
% surface, optionally as an overlay on anatomical MRI data, where
% statistical data can be used to determine the opacity of the mask.
% Input data comes from FT_SOURCEANALYSIS, FT_SOURCEGRANDAVERAGE or
% statistical values from FT_SOURCESTATISTICS.
%
% Use as:
% ft_sourceplot(cfg, data)
%
% The data can contain functional data, anatomical MRI data and statistical data,
% interpolated onto the same grid.
%
% The configuration should contain:
% cfg.method = 'slice', plots the data on a number of slices in the same plane
% 'ortho', plots the data on three orthogonal slices
% 'surface', plots the data on a 3D brain surface
%
% cfg.anaparameter = string, field in data with the anatomical data (default = 'anatomy' if present in data)
% cfg.funparameter = string, field in data with the functional parameter of interest (default = [])
% cfg.maskparameter = string, field in the data to be used for opacity masking of fun data (default = [])
% If values are between 0 and 1, zero is fully transparant and one is fully opaque.
% If values in the field are not between 0 and 1 they will be scaled depending on the values
% of cfg.opacitymap and cfg.opacitylim (see below)
% You can use masking in several ways, f.i.
% - use outcome of statistics to show only the significant values and mask the insignificant
% NB see also cfg.opacitymap and cfg.opacitylim below
% - use the functional data itself as mask, the highest value (and/or lowest when negative)
% will be opaque and the value closest to zero transparent
% - Make your own field in the data with values between 0 and 1 to control opacity directly
%
% The following parameters can be used in all methods:
% cfg.downsample = downsampling for resolution reduction, integer value (default = 1) (orig: from surface)
% cfg.atlas = string, filename of atlas to use (default = []) SEE FT_PREPARE_ATLAS
% for ROI masking (see "masking" below) or in interactive mode (see "ortho-plotting" below)
% cfg.coordsys = 'mni' or 'tal', coordinate system of the input data, used to lookup the label from the atlas
%
% The following parameters can be used for the functional data:
% cfg.funcolormap = colormap for functional data, see COLORMAP (default = 'auto')
% 'auto', depends structure funparameter, or on funcolorlim
% - funparameter: only positive values, or funcolorlim:'zeromax' -> 'hot'
% - funparameter: only negative values, or funcolorlim:'minzero' -> 'cool'
% - funparameter: both pos and neg values, or funcolorlim:'maxabs' -> 'jet'
% - funcolorlim: [min max] if min & max pos-> 'hot', neg-> 'cool', both-> 'jet'
% cfg.funcolorlim = color range of the functional data (default = 'auto')
% [min max]
% 'maxabs', from -max(abs(funparameter)) to +max(abs(funparameter))
% 'zeromax', from 0 to max(abs(funparameter))
% 'minzero', from min(abs(funparameter)) to 0
% 'auto', if funparameter values are all positive: 'zeromax',
% all negative: 'minzero', both possitive and negative: 'maxabs'
% cfg.colorbar = 'yes' or 'no' (default = 'yes')
%
% The following parameters can be used for the masking data:
% cfg.opacitymap = opacitymap for mask data, see ALPHAMAP (default = 'auto')
% 'auto', depends structure maskparameter, or on opacitylim
% - maskparameter: only positive values, or opacitylim:'zeromax' -> 'rampup'
% - maskparameter: only negative values, or opacitylim:'minzero' -> 'rampdown'
% - maskparameter: both pos and neg values, or opacitylim:'maxabs' -> 'vdown'
% - opacitylim: [min max] if min & max pos-> 'rampup', neg-> 'rampdown', both-> 'vdown'
% - NB. to use p-values use 'rampdown' to get lowest p-values opaque and highest transparent
% cfg.opacitylim = range of mask values to which opacitymap is scaled (default = 'auto')
% [min max]
% 'maxabs', from -max(abs(maskparameter)) to +max(abs(maskparameter))
% 'zeromax', from 0 to max(abs(maskparameter))
% 'minzero', from min(abs(maskparameter)) to 0
% 'auto', if maskparameter values are all positive: 'zeromax',
% all negative: 'minzero', both possitive and negative: 'maxabs'
% cfg.roi = string or cell of strings, region(s) of interest from anatomical atlas (see cfg.atlas above)
% everything is masked except for ROI
%
% The folowing parameters apply for ortho-plotting
% cfg.location = location of cut, (default = 'auto')
% 'auto', 'center' if only anatomy, 'max' if functional data
% 'min' and 'max' position of min/max funparameter
% 'center' of the brain
% [x y z], coordinates in voxels or head, see cfg.locationcoordinates
% cfg.locationcoordinates = coordinate system used in cfg.location, 'head' or 'voxel' (default = 'head')
% 'head', headcoordinates from anatomical MRI
% 'voxel', voxelcoordinates
% cfg.crosshair = 'yes' or 'no' (default = 'yes')
% cfg.axis = 'on' or 'off' (default = 'on')
% cfg.interactive = 'yes' or 'no' (default = 'no')
% in interactive mode cursor click determines location of cut
% cfg.queryrange = number, in atlas voxels (default 3)
%
%
% The folowing parameters apply for slice-plotting
% cfg.nslices = number of slices, (default = 20)
% cfg.slicerange = range of slices in data, (default = 'auto')
% 'auto', full range of data
% [min max], coordinates of first and last slice in voxels
% cfg.slicedim = dimension to slice 1 (x-axis) 2(y-axis) 3(z-axis) (default = 3)
% cfg.title = string, title of the figure window
%
% The folowing parameters apply for surface-plotting
% cfg.surffile = string, file that contains the surface (default = 'single_subj_T1.mat')
% 'single_subj_T1.mat' contains a triangulation that corresponds with the
% SPM anatomical template in MNI coordinates
% cfg.surfinflated = string, file that contains the inflated surface (default = [])
% cfg.surfdownsample = number (default = 1, i.e. no downsampling)
% cfg.projmethod = projection method, how functional volume data is
% projected onto surface
% 'nearest', 'project', 'sphere_avg', 'sphere_weighteddistance'
% cfg.projvec = vector (in mm) to allow different projections that
% are combined with the method specified in cfg.projcomb
% cfg.projcomb = 'mean', 'max', method to combine the different
% projections
% cfg.projweight = vector of weights for the different projections
% (default: 1)
% cfg.projthresh = implements thresholding on the surface level
% (cfg.projthresh = 0.7 means 70% of maximum)
% cfg.sphereradius = maximum distance from each voxel to the surface to be
% included in the sphere projection methods, expressed in mm
% cfg.distmat = precomputed distance matrix (default = [])
% cfg.camlight = 'yes' or 'no' (default = 'yes')
% cfg.renderer = 'painters', 'zbuffer',' opengl' or 'none' (default = 'opengl')
% When using opacity the OpenGL renderer is required.
%
% To facilitate data-handling and distributed computing with the peer-to-peer
% module, this function has the following option:
% cfg.inputfile = ...
% If you specify this option the input data will be read from a *.mat
% file on disk. This mat files should contain only a single variable named 'data',
% corresponding to the input structure.
%
% See also FT_SOURCEANALYSIS, FT_SOURCEGRANDAVERAGE, FT_SOURCESTATISTICS,
% FT_VOLUMELOOKUP, FT_PREPARE_ATLAS
% TODO have to be built in:
% cfg.marker = [Nx3] array defining N marker positions to display (orig: from sliceinterp)
% cfg.markersize = radius of markers (default = 5)
% cfg.markercolor = [1x3] marker color in RGB (default = [1 1 1], i.e. white) (orig: from sliceinterp)
% white background option
% undocumented TODO
% slice in all directions
% surface also optimal when inside present
% come up with a good glass brain projection
% Copyright (C) 2007-2008, Robert Oostenveld, Ingrid Nieuwenhuis
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_sourceplot.m 3744 2011-06-30 06:06:20Z jansch $
ft_defaults
cfg = ft_checkconfig(cfg, 'trackconfig', 'on');
cfg = ft_checkconfig(cfg, 'renamed', {'inputcoordsys', 'coordsys'});
%%% ft_checkdata see below!!! %%%
% set default for inputfile
cfg.inputfile = ft_getopt(cfg, 'inputfile', []);
% load optional given inputfile as data
hasdata = (nargin>1);
hasinputfile = ~isempty(cfg.inputfile);
if hasdata && hasinputfile
error('cfg.inputfile should not be used in conjunction with giving input data to this function');
elseif hasdata
% do nothing
elseif hasinputfile
data = loadvar(cfg.inputfile, 'data');
end
% set the common defaults
cfg.method = ft_getopt(cfg, 'method', 'ortho');
if ~isfield(cfg, 'anaparameter'),
if isfield(data, 'anatomy'),
cfg.anaparameter = 'anatomy';
else
cfg.anaparameter = [];
end
end
% all methods
cfg.funparameter = ft_getopt(cfg, 'funparameter', []);
cfg.maskparameter = ft_getopt(cfg, 'maskparameter', []);
cfg.downsample = ft_getopt(cfg, 'downsample', 1);
cfg.title = ft_getopt(cfg, 'title', '');
cfg.atlas = ft_getopt(cfg, 'atlas', []);
cfg.marker = ft_getopt(cfg, 'marker', []);
cfg.markersize = ft_getopt(cfg, 'markersize', 5);
cfg.markercolor = ft_getopt(cfg, 'markercolor', [1 1 1]);
% set the common defaults for the functional data
cfg.funcolormap = ft_getopt(cfg, 'funcolormap', 'auto');
cfg.funcolorlim = ft_getopt(cfg, 'funcolorlim', 'auto');
% set the common defaults for the statistical data
cfg.opacitymap = ft_getopt(cfg, 'opacitymap', 'auto');
cfg.opacitylim = ft_getopt(cfg, 'opacitylim', 'auto');
cfg.roi = ft_getopt(cfg, 'roi', []);
% set the defaults per method
% ortho
cfg.location = ft_getopt(cfg, 'location', 'auto');
cfg.locationcoordinates = ft_getopt(cfg, 'locationcoordinates', 'head');
cfg.crosshair = ft_getopt(cfg, 'crosshair', 'yes');
cfg.colorbar = ft_getopt(cfg, 'colorbar', 'yes');
cfg.axis = ft_getopt(cfg, 'axis', 'on');
cfg.interactive = ft_getopt(cfg, 'interactive', 'no');
cfg.queryrange = ft_getopt(cfg, 'queryrange', 3);
cfg.coordsys = ft_getopt(cfg, 'coordsys', []);
cfg.units = ft_getopt(cfg, 'units', []);
if isfield(cfg, 'TTlookup'),
error('TTlookup is old; now specify cfg.atlas, see help!');
end
% slice
cfg.nslices = ft_getopt(cfg, 'nslices', 20);
cfg.slicedim = ft_getopt(cfg, 'slicedim', 3);
cfg.slicerange = ft_getopt(cfg, 'slicerange', 'auto');
% surface
cfg.downsample = ft_getopt(cfg, 'downsample', 1);
cfg.surfdownsample = ft_getopt(cfg, 'surfdownsample', 1);
cfg.surffile = ft_getopt(cfg, 'surffile', 'single_subj_T1.mat');% use a triangulation that corresponds with the collin27 anatomical template in MNI coordinates
cfg.surfinflated = ft_getopt(cfg, 'surfinflated', []);
cfg.sphereradius = ft_getopt(cfg, 'sphereradius', []);
cfg.projvec = ft_getopt(cfg, 'projvec', 1);
cfg.projweight = ft_getopt(cfg, 'projweight', ones(size(cfg.projvec)));
cfg.projcomb = ft_getopt(cfg, 'projcomb', 'mean'); %or max
cfg.projthresh = ft_getopt(cfg, 'projthresh', []);
cfg.distmat = ft_getopt(cfg, 'distmat', []);
cfg.camlight = ft_getopt(cfg, 'camlight', 'yes');
cfg.renderer = ft_getopt(cfg, 'renderer', 'opengl');
if isequal(cfg.method,'surface')
if ~isfield(cfg, 'projmethod'), error('specify cfg.projmethod'); end
end
% for backward compatibility
if strcmp(cfg.location, 'interactive')
cfg.location = 'auto';
cfg.interactive = 'yes';
end
%%%%%%%
if ischar(data)
% read the anatomical MRI data from file
filename = data;
fprintf('reading MRI from file\n');
data = ft_read_mri(filename);
end
% check if the input data is valid for this function
data = ft_checkdata(data, 'datatype', 'volume', 'feedback', 'yes');
% ensure that the data has interpretable spatial units
if ~isfield(data, 'unit') && ~isempty(cfg.units)
data.unit = cfg.units;
elseif ~isfield(data, 'unit') && isempty(cfg.units)
data = ft_convert_units(data);
elseif isfield(data, 'unit') && ~isempty(cfg.units)
data = ft_convert_units(data, cfg.units);
elseif isfield(data, 'unit') && isempty(cfg.units)
% nothing to do
end
% ensure that the data has an interpretable coordinate system
if ~isfield(data, 'coordsys') && ~isempty(cfg.coordsys)
data.coordsys = cfg.coordsys;
elseif ~isfield(data, 'coordsys') && isempty(cfg.coordsys) && ~isempty(cfg.atlas)
% only needed if an atlas was specified for volumelookup
data = ft_convert_coordsys(data);
elseif isfield(data, 'coordsys') && ~isempty(cfg.coordsys) && ~isempty(cfg.atlas)
% only needed if an atlas was specified for volumelookup
data = ft_convert_coordsys(data, cfg.units);
elseif isfield(data, 'coordsys') && isempty(cfg.coordsys)
% nothing to do
end
% select the functional and the mask parameter
cfg.funparameter = parameterselection(cfg.funparameter, data);
cfg.maskparameter = parameterselection(cfg.maskparameter, data);
% only a single parameter should be selected
try, cfg.funparameter = cfg.funparameter{1}; end
try, cfg.maskparameter = cfg.maskparameter{1}; end
% downsample all volumes
tmpcfg = [];
tmpcfg.parameter = {cfg.funparameter, cfg.maskparameter, cfg.anaparameter};
tmpcfg.downsample = cfg.downsample;
data = ft_volumedownsample(tmpcfg, data);
%%% make the local variables:
dim = data.dim;
hasatlas = ~isempty(cfg.atlas);
if hasatlas
% initialize the atlas
[p, f, x] = fileparts(cfg.atlas);
fprintf(['reading ', f,' atlas coordinates and labels\n']);
atlas = ft_prepare_atlas(cfg.atlas);
end
hasroi = ~isempty(cfg.roi);
if hasroi
if ~hasatlas
error('specify cfg.atlas which belongs to cfg.roi')
else
% get the mask
tmpcfg = [];
tmpcfg.roi = cfg.roi;
tmpcfg.atlas = cfg.atlas;
tmpcfg.coordsys = cfg.coordsys;
roi = ft_volumelookup(tmpcfg,data);
end
end
%%% anaparameter
if isempty(cfg.anaparameter);
hasana = 0;
fprintf('not plotting anatomy\n');
elseif isfield(data, cfg.anaparameter)
hasana = 1;
ana = getsubfield(data, cfg.anaparameter);
% convert integers to single precision float if neccessary
if isa(ana, 'uint8') || isa(ana, 'uint16') || isa(ana, 'int8') || isa(ana, 'int16')
fprintf('converting anatomy to double\n');
ana = double(ana);
end
else
warning('do not understand cfg.anaparameter, not plotting anatomy\n')
hasana = 0;
end
%%% funparameter
% has fun?
if ~isempty(cfg.funparameter)
if issubfield(data, cfg.funparameter)
hasfun = 1;
fun = getsubfield(data, cfg.funparameter);
else
error('cfg.funparameter not found in data');
end
else
hasfun = 0;
fprintf('no functional parameter\n');
end
% handle fun
if hasfun && issubfield(data, 'dimord') && strcmp(data.dimord(end-2:end),'rgb')
% treat functional data as rgb values
if any(fun(:)>1 | fun(:)<0)
%scale
tmpdim = size(fun);
nvox = prod(tmpdim(1:end-1));
tmpfun = reshape(fun,[nvox tmpdim(end)]);
m1 = max(tmpfun,[],1);
m2 = min(tmpfun,[],1);
tmpfun = (tmpfun-m2(ones(nvox,1),:))./(m1(ones(nvox,1),:)-m2(ones(nvox,1),:));
fun = reshape(tmpfun, tmpdim);
end
qi = 1;
hasfreq = 0;
hastime = 0;
doimage = 1;
fcolmin = 0;
fcolmax = 1;
elseif hasfun
% determine scaling min and max (fcolmin fcolmax) and funcolormap
if ~isa(fun, 'logical')
funmin = min(fun(:));
funmax = max(fun(:));
else
funmin = 0;
funmax = 1;
end
% smart lims: make from auto other string
if isequal(cfg.funcolorlim,'auto')
if sign(funmin)>-1 && sign(funmax)>-1
cfg.funcolorlim = 'zeromax';
elseif sign(funmin)<1 && sign(funmax)<1
cfg.funcolorlim = 'minzero';
else
cfg.funcolorlim = 'maxabs';
end
end
if ischar(cfg.funcolorlim)
% limits are given as string
if isequal(cfg.funcolorlim,'maxabs')
fcolmin = -max(abs([funmin,funmax]));
fcolmax = max(abs([funmin,funmax]));
if isequal(cfg.funcolormap,'auto'); cfg.funcolormap = 'jet'; end;
elseif isequal(cfg.funcolorlim,'zeromax')
fcolmin = 0;
fcolmax = funmax;
if isequal(cfg.funcolormap,'auto'); cfg.funcolormap = 'hot'; end;
elseif isequal(cfg.funcolorlim,'minzero')
fcolmin = funmin;
fcolmax = 0;
if isequal(cfg.funcolormap,'auto'); cfg.funcolormap = 'cool'; end;
else
error('do not understand cfg.funcolorlim');
end
else
% limits are numeric
fcolmin = cfg.funcolorlim(1);
fcolmax = cfg.funcolorlim(2);
% smart colormap
if isequal(cfg.funcolormap,'auto')
if sign(fcolmin) == -1 && sign(fcolmax) == 1
cfg.funcolormap = 'jet';
else
if fcolmin < 0
cfg.funcolormap = 'cool';
else
cfg.funcolormap = 'hot';
end
end
end
end %if ischar
clear funmin funmax;
% ensure that the functional data is real
if ~isreal(fun)
fprintf('taking absolute value of complex data\n');
fun = abs(fun);
end
%what if fun is 4D?
if ndims(fun)>3,
if isfield(data, 'time') && isfield(data, 'freq'),
%data contains timefrequency representation
qi = [1 1];
hasfreq = 1;
hastime = 1;
elseif isfield(data, 'time')
%data contains evoked field
qi = 1;
hasfreq = 0;
hastime = 1;
elseif isfield(data, 'freq')
%data contains frequency spectra
qi = 1;
hasfreq = 1;
hastime = 0;
end
else
%do nothing
qi = 1;
hasfreq = 0;
hastime = 0;
end
doimage = 0;
else
qi = 1;
hasfreq = 0;
hastime = 0;
doimage = 0;
end % handle fun
%%% maskparameter
% has mask?
if ~isempty(cfg.maskparameter)
if issubfield(data, cfg.maskparameter)
if ~hasfun
error('you can not have a mask without functional data')
else
hasmsk = 1;
msk = getsubfield(data, cfg.maskparameter);
if islogical(msk) %otherwise sign() not posible
msk = double(msk);
end
end
else
error('cfg.maskparameter not found in data');
end
else
hasmsk = 0;
fprintf('no masking parameter\n');
end
% handle mask
if hasmsk
% determine scaling and opacitymap
mskmin = min(msk(:));
mskmax = max(msk(:));
% determine the opacity limits and the opacity map
% smart lims: make from auto other string, or equal to funcolorlim if funparameter == maskparameter
if isequal(cfg.opacitylim,'auto')
if isequal(cfg.funparameter,cfg.maskparameter)
cfg.opacitylim = cfg.funcolorlim;
else
if sign(mskmin)>-1 && sign(mskmax)>-1
cfg.opacitylim = 'zeromax';
elseif sign(mskmin)<1 && sign(mskmax)<1
cfg.opacitylim = 'minzero';
else
cfg.opacitylim = 'maxabs';
end
end
end
if ischar(cfg.opacitylim)
% limits are given as string
switch cfg.opacitylim
case 'zeromax'
opacmin = 0;
opacmax = mskmax;
if isequal(cfg.opacitymap,'auto'), cfg.opacitymap = 'rampup'; end;
case 'minzero'
opacmin = mskmin;
opacmax = 0;
if isequal(cfg.opacitymap,'auto'), cfg.opacitymap = 'rampdown'; end;
case 'maxabs'
opacmin = -max(abs([mskmin, mskmax]));
opacmax = max(abs([mskmin, mskmax]));
if isequal(cfg.opacitymap,'auto'), cfg.opacitymap = 'vdown'; end;
otherwise
error('incorrect specification of cfg.opacitylim');
end % switch opacitylim
else
% limits are numeric
opacmin = cfg.opacitylim(1);
opacmax = cfg.opacitylim(2);
if isequal(cfg.opacitymap,'auto')
if sign(opacmin)>-1 && sign(opacmax)>-1
cfg.opacitymap = 'rampup';
elseif sign(opacmin)<1 && sign(opacmax)<1
cfg.opacitymap = 'rampdown';
else
cfg.opacitymap = 'vdown';
end
end
end % handling opacitylim and opacitymap
clear mskmin mskmax;
end
% prevent outside fun from being plotted
if hasfun && isfield(data,'inside') && ~hasmsk
hasmsk = 1;
msk = zeros(dim);
cfg.opacitymap = 'rampup';
opacmin = 0;
opacmax = 1;
% make intelligent mask
if isequal(cfg.method,'surface')
msk(data.inside) = 1;
else
if hasana
msk(data.inside) = 0.5; %so anatomy is visible
else
msk(data.inside) = 1;
end
end
end
% if region of interest is specified, mask everything besides roi
if hasfun && hasroi && ~hasmsk
hasmsk = 1;
msk = roi;
cfg.opacitymap = 'rampup';
opacmin = 0;
opacmax = 1;
elseif hasfun && hasroi && hasmsk
msk = roi .* msk;
elseif hasroi
error('you can not have a roi without functional data')
end
%%% set color and opacity mapping for this figure
if hasfun
cfg.funcolormap = colormap(cfg.funcolormap);
colormap(cfg.funcolormap);
end
if hasmsk
cfg.opacitymap = alphamap(cfg.opacitymap);
alphamap(cfg.opacitymap);
end
%%% determine what has to be plotted, depends on method
if isequal(cfg.method,'ortho')
if ~ischar(cfg.location)
if strcmp(cfg.locationcoordinates, 'head')
% convert the headcoordinates location into voxel coordinates
loc = inv(data.transform) * [cfg.location(:); 1];
loc = round(loc(1:3));
elseif strcmp(cfg.locationcoordinates, 'voxel')
% the location is already in voxel coordinates
loc = round(cfg.location(1:3));
else
error('you should specify cfg.locationcoordinates');
end
else
if isequal(cfg.location,'auto')
if hasfun
if isequal(cfg.funcolorlim,'maxabs');
loc = 'max';
elseif isequal(cfg.funcolorlim, 'zeromax');
loc = 'max';
elseif isequal(cfg.funcolorlim, 'minzero');
loc = 'min';
else %if numerical
loc = 'max';
end
else
loc = 'center';
end;
else
loc = cfg.location;
end
end
% determine the initial intersection of the cursor (xi yi zi)
if ischar(loc) && strcmp(loc, 'min')
if isempty(cfg.funparameter)
error('cfg.location is min, but no functional parameter specified');
end
[minval, minindx] = min(fun(:));
[xi, yi, zi] = ind2sub(dim, minindx);
elseif ischar(loc) && strcmp(loc, 'max')
if isempty(cfg.funparameter)
error('cfg.location is max, but no functional parameter specified');
end
[maxval, maxindx] = max(fun(:));
[xi, yi, zi] = ind2sub(dim, maxindx);
elseif ischar(loc) && strcmp(loc, 'center')
xi = round(dim(1)/2);
yi = round(dim(2)/2);
zi = round(dim(3)/2);
elseif ~ischar(loc)
% using nearest instead of round ensures that the position remains within the volume
xi = nearest(1:dim(1), loc(1));
yi = nearest(1:dim(2), loc(2));
zi = nearest(1:dim(3), loc(3));
end
%% do the actual plotting %%
nas = [];
lpa = [];
rpa = [];
interactive_flag = 1; % it happens at least once
while(interactive_flag)
interactive_flag = strcmp(cfg.interactive, 'yes');
xi = round(xi); xi = max(xi, 1); xi = min(xi, dim(1));
yi = round(yi); yi = max(yi, 1); yi = min(yi, dim(2));
zi = round(zi); zi = max(zi, 1); zi = min(zi, dim(3));
if interactive_flag
fprintf('\n');
fprintf('click with mouse button to reposition the cursor\n');
fprintf('press n/l/r on keyboard to record a fiducial position\n');
fprintf('press q on keyboard to quit interactive mode\n');
end
ijk = [xi yi zi 1]';
xyz = data.transform * ijk;
% construct a string with user feedback
str = sprintf('voxel %d, indices [%d %d %d]', sub2ind(dim(1:3), xi, yi, zi), ijk(1:3));
if isfield(data, 'coordsys') && isfield(data, 'unit')
str = sprintf('%s, %s coordinates [%.1f %.1f %.1f] %s', str, data.coordsys, xyz(1:3), data.unit);
elseif ~isfield(data, 'coordsys') && isfield(data, 'unit')
str = sprintf('%s, location [%.1f %.1f %.1f] %s', str, xyz(1:3), data.unit);
elseif isfield(data, 'coordsys') && ~isfield(data, 'unit')
str = sprintf('%s, %s coordinates [%.1f %.1f %.1f]', str, data.coordsys, xyz(1:3));
elseif ~isfield(data, 'coordsys') && ~isfield(data, 'unis')
str = sprintf('%s, location [%.1f %.1f %.1f]', str, xyz(1:3));
end
if hasfreq && hastime,
str = sprintf('%s, %.1f s, %.1f Hz', str, qi(1), qi(2));
elseif ~hasfreq && hastime,
str = sprintf('%s, %.1f s', str, qi(1));
elseif hasfreq && ~hastime,
str = sprintf('%s, %.1f Hz', str, qi(1));
end
if hasfun
if ~hasfreq && ~hastime
val = fun(xi, yi, zi);
elseif ~hasfreq && hastime
val = fun(xi, yi, zi, qi);
elseif hasfreq && ~hastime
val = fun(xi, yi, zi, qi);
elseif hasfreq && hastime
val = fun(xi, yi, zi, qi(1), qi(2));
end
str = sprintf('%s, value %f', str, val);
end
fprintf('%s\n', str);
if hasatlas
% determine the anatomical label of the current position
lab = atlas_lookup(atlas, (xyz(1:3)), 'inputcoord', data.coordsys, 'queryrange', cfg.queryrange);
if isempty(lab)
fprintf([f,' labels: not found\n']);
else
fprintf([f,' labels: '])
fprintf('%s', lab{1});
for i=2:length(lab)
fprintf(', %s', lab{i});
end
fprintf('\n');
end
end
% make vols and scales, containes volumes to be plotted (fun, ana, msk)
vols = {};
if hasana; vols{1} = ana; scales{1} = []; end; % needed when only plotting ana
if hasfun; vols{2} = fun; scales{2} = [fcolmin fcolmax]; end;
if hasmsk; vols{3} = msk; scales{3} = [opacmin opacmax]; end;
if isempty(vols)
% this seems to be a problem that people often have
error('no anatomy is present and no functional data is selected, please check your cfg.funparameter');
end
h1 = subplot(2,2,1);
[vols2D] = handle_ortho(vols, [xi yi zi qi], 2, dim, doimage);
plot2D(vols2D, scales, doimage);
xlabel('i'); ylabel('k'); axis(cfg.axis);
if strcmp(cfg.crosshair, 'yes'), crosshair([xi zi]); end
h2 = subplot(2,2,2);
[vols2D] = handle_ortho(vols, [xi yi zi qi], 1, dim, doimage);
plot2D(vols2D, scales, doimage);
xlabel('j'); ylabel('k'); axis(cfg.axis);
if strcmp(cfg.crosshair, 'yes'), crosshair([yi zi]); end
h3 = subplot(2,2,3);
[vols2D] = handle_ortho(vols, [xi yi zi qi], 3, dim, doimage);
plot2D(vols2D, scales, doimage);
xlabel('i'); ylabel('j'); axis(cfg.axis);
if strcmp(cfg.crosshair, 'yes'), crosshair([xi yi]); end
if hasfreq && hastime && hasfun,
h=subplot(2,2,4);
%uimagesc(data.time, data.freq, squeeze(vols{2}(xi,yi,zi,:,:))');axis xy;
tmpdat = double(squeeze(vols{2}(xi,yi,zi,:,:)));
pcolor(double(data.time), double(data.freq), double(squeeze(vols{2}(xi,yi,zi,:,:))));
shading('interp');
xlabel('time'); ylabel('freq');
try
caxis([-1 1].*max(abs(caxis)));
end
colorbar;
%caxis([fcolmin fcolmax]);
%set(gca, 'Visible', 'off');
elseif hasfreq && hasfun,
subplot(2,2,4);
plot(data.freq, squeeze(vols{2}(xi,yi,zi,:))); xlabel('freq');
axis([data.freq(1) data.freq(end) scales{2}]);
elseif hastime && hasfun,
subplot(2,2,4);
plot(data.time, squeeze(vols{2}(xi,yi,zi,:))); xlabel('time');
axis([data.time(1) data.time(end) scales{2}]);
elseif strcmp(cfg.colorbar, 'yes'),
if hasfun
% vectorcolorbar = linspace(fcolmin, fcolmax,length(cfg.funcolormap));
% imagesc(vectorcolorbar,1,vectorcolorbar);colormap(cfg.funcolormap);
subplot(2,2,4);
% use a normal Matlab colorbar, attach it to the invisible 4th subplot
try
caxis([fcolmin fcolmax]);
end
hc = colorbar;
try
set(hc, 'YLim', [fcolmin fcolmax]);
end
set(gca, 'Visible', 'off');
else
warning('no colorbar possible without functional data')
end
end
set(gcf, 'renderer', cfg.renderer); % ensure that this is done in interactive mode
drawnow;
if interactive_flag
try
[d1, d2, key] = ginput(1);
catch
% this happens if the figure is closed
key='q';
end
if isempty(key)
% this happens if you press the apple key
key = '';
end
switch key
case ''
% do nothing
case 'q'
break;
case 'l'
lpa = [xi yi zi];
case 'r'
rpa = [xi yi zi];
case 'n'
nas = [xi yi zi];
case {'i' 'j''k' 'm'}
% update the view to a new position
if l1=='i' && l2=='k' && key=='i', zi = zi+1;
elseif l1=='i' && l2=='k' && key=='j', xi = xi-1;
elseif l1=='i' && l2=='k' && key=='k', xi = xi+1;
elseif l1=='i' && l2=='k' && key=='m', zi = zi-1;
elseif l1=='i' && l2=='j' && key=='i', yi = yi+1;
elseif l1=='i' && l2=='j' && key=='j', xi = xi-1;
elseif l1=='i' && l2=='j' && key=='k', xi = xi+1;
elseif l1=='i' && l2=='j' && key=='m', yi = yi-1;
elseif l1=='j' && l2=='k' && key=='i', zi = zi+1;
elseif l1=='j' && l2=='k' && key=='j', yi = yi-1;
elseif l1=='j' && l2=='k' && key=='k', yi = yi+1;
elseif l1=='j' && l2=='k' && key=='m', zi = zi-1;
end;
otherwise
% update the view to a new position
l1 = get(get(gca, 'xlabel'), 'string');
l2 = get(get(gca, 'ylabel'), 'string');
switch l1,
case 'i'
xi = d1;
case 'j'
yi = d1;
case 'k'
zi = d1;
case 'freq'
qi = nearest(data.freq,d1);
case 'time'
qi = nearest(data.time,d1);
end
switch l2,
case 'i'
xi = d2;
case 'j'
yi = d2;
case 'k'
zi = d2;
case 'freq'
qi = [nearest(data.freq,d2) qi(1)];
end
end % switch key
end % if interactive_flag
if ~isempty(nas), fprintf('nas = [%f %f %f]\n', nas); cfg.fiducial.nas = nas; else fprintf('nas = undefined\n'); end
if ~isempty(lpa), fprintf('lpa = [%f %f %f]\n', lpa); cfg.fiducial.lpa = lpa; else fprintf('lpa = undefined\n'); end
if ~isempty(rpa), fprintf('rpa = [%f %f %f]\n', rpa); cfg.fiducial.rpa = rpa; else fprintf('rpa = undefined\n'); end
end % while interactive_flag
elseif isequal(cfg.method,'glassbrain')
tmpcfg = [];
tmpcfg.funparameter = cfg.funparameter;
tmpcfg.method = 'ortho';
tmpcfg.location = [1 1 1];
tmpcfg.funcolorlim = cfg.funcolorlim;
tmpcfg.funcolormap = cfg.funcolormap;
tmpcfg.opacitylim = cfg.opacitylim;
tmpcfg.locationcoordinates = 'voxel';
tmpcfg.maskparameter = 'inside';
tmpcfg.axis = cfg.axis;
tmpcfg.renderer = cfg.renderer;
if hasfun,
fun = getsubfield(data, cfg.funparameter);
fun(1,:,:) = max(fun, [], 1);
fun(:,1,:) = max(fun, [], 2);
fun(:,:,1) = max(fun, [], 3);
data = setsubfield(data, cfg.funparameter, fun);
end
if hasana,
ana = getsubfield(data, cfg.anaparameter);
%ana(1,:,:) = max(ana, [], 1);
%ana(:,1,:) = max(ana, [], 2);
%ana(:,:,1) = max(ana, [], 3);
data = setsubfield(data, cfg.anaparameter, ana);
end
if hasmsk,
msk = getsubfield(data, 'inside');
msk(1,:,:) = squeeze(fun(1,:,:))>0 & imfill(abs(squeeze(ana(1,:,:))-1))>0;
msk(:,1,:) = squeeze(fun(:,1,:))>0 & imfill(abs(squeeze(ana(:,1,:))-1))>0;
msk(:,:,1) = squeeze(fun(:,:,1))>0 & imfill(abs(ana(:,:,1)-1))>0;
data = setsubfield(data, 'inside', msk);
end
ft_sourceplot(tmpcfg, data);
elseif isequal(cfg.method,'surface')
% read the triangulated cortical surface from file
tmp = load(cfg.surffile, 'bnd');
surf = tmp.bnd;
if isfield(surf, 'transform'),
% compute the surface vertices in head coordinates
surf.pnt = warp_apply(surf.transform, surf.pnt);
end
% downsample the cortical surface
if cfg.surfdownsample > 1
if ~isempty(cfg.surfinflated)
error('downsampling the surface is not possible in combination with an inflated surface');
end
fprintf('downsampling surface from %d vertices\n', size(surf.pnt,1));
[surf.tri, surf.pnt] = reducepatch(surf.tri, surf.pnt, 1/cfg.surfdownsample);
end
% these are required
if ~isfield(data, 'inside')
data.inside = true(dim);
end
fprintf('%d voxels in functional data\n', prod(dim));
fprintf('%d vertices in cortical surface\n', size(surf.pnt,1));
if (hasfun && strcmp(cfg.projmethod,'project')),
val=zeros(size(surf.pnt,1),1);
if hasmsk
maskval = val;
end;
%convert projvec in mm to a factor, assume mean distance of 70mm
cfg.projvec=(70-cfg.projvec)/70;
for iproj = 1:length(cfg.projvec),
sub = round(warp_apply(inv(data.transform), surf.pnt*cfg.projvec(iproj), 'homogenous')); % express
sub(sub(:)<1) = 1;
sub(sub(:,1)>dim(1),1) = dim(1);
sub(sub(:,2)>dim(2),2) = dim(2);
sub(sub(:,3)>dim(3),3) = dim(3);
disp('projecting...')
ind = sub2ind(dim, sub(:,1), sub(:,2), sub(:,3));
if strcmp(cfg.projcomb,'mean')
val = val + cfg.projweight(iproj) * fun(ind);
if hasmsk
maskval = maskval + cfg.projweight(iproj) * msk(ind);
end
elseif strcmp(cfg.projcomb,'max')
val = max([val cfg.projweight(iproj) * fun(ind)],[],2);
tmp2 = min([val cfg.projweight(iproj) * fun(ind)],[],2);
fi = find(val < max(tmp2));
val(fi) = tmp2(fi);
if hasmsk
maskval = max(abs([maskval cfg.projweight(iproj) * fun(ind)]),[],2);
end
else
error('undefined method to combine projections; use cfg.projcomb= mean or max')
end
end
if strcmp(cfg.projcomb,'mean'),
val=val/length(cfg.projvec);
if hasmsk
maskval = max(abs([maskval cfg.projweight(iproj) * fun(ind)]),[],2);
end
end;
if ~isempty(cfg.projthresh),
mm=max(abs(val(:)));
maskval(abs(val) < cfg.projthresh*mm) = 0;
end
end
if (hasfun && ~strcmp(cfg.projmethod,'project')),
[interpmat, cfg.distmat] = interp_gridded(data.transform, fun, surf.pnt, 'projmethod', cfg.projmethod, 'distmat', cfg.distmat, 'sphereradius', cfg.sphereradius, 'inside', data.inside);
% interpolate the functional data
val = interpmat * fun(data.inside(:));
end;
if (hasmsk && ~strcmp(cfg.projmethod,'project')),
% also interpolate the opacity mask
maskval = interpmat * msk(data.inside(:));
end
if ~isempty(cfg.surfinflated)
% read the inflated triangulated cortical surface from file
tmp = load(cfg.surfinflated, 'bnd');
surf = tmp.bnd;
if isfield(surf, 'transform'),
% compute the surface vertices in head coordinates
surf.pnt = warp_apply(surf.transform, surf.pnt);
end
end
%------do the plotting
cortex_light = [0.781 0.762 0.664];
cortex_dark = [0.781 0.762 0.664]/2;
if isfield(surf, 'curv')
% the curvature determines the color of gyri and sulci
color = surf.curv(:) * cortex_light + (1-surf.curv(:)) * cortex_dark;
else
color = repmat(cortex_light, size(surf.pnt,1), 1);
end
h1 = patch('Vertices', surf.pnt, 'Faces', surf.tri, 'FaceVertexCData', color , 'FaceColor', 'interp');
set(h1, 'EdgeColor', 'none');
axis off;
axis vis3d;
axis equal;
h2 = patch('Vertices', surf.pnt, 'Faces', surf.tri, 'FaceVertexCData', val , 'FaceColor', 'interp');
set(h2, 'EdgeColor', 'none');
if hasmsk
set(h2, 'FaceVertexAlphaData', maskval);
set(h2, 'FaceAlpha', 'interp');
set(h2, 'AlphaDataMapping', 'scaled');
try
alim(gca, [opacmin opacmax]);
end
end
try
caxis(gca,[fcolmin fcolmax]);
end
lighting gouraud
if hasfun
colormap(cfg.funcolormap);
end
if hasmsk
alphamap(cfg.opacitymap);
end
if strcmp(cfg.camlight,'yes')
camlight
end
if strcmp(cfg.colorbar, 'yes'),
if hasfun
% use a normal Matlab colorbar
hc = colorbar;
set(hc, 'YLim', [fcolmin fcolmax]);
else
warning('no colorbar possible without functional data')
end
end
elseif isequal(cfg.method,'slice')
% white BG => mskana
%% TODO: HERE THE FUNCTION THAT MAKES TO SLICE DIMENSION ALWAYS THE THIRD
%% DIMENSION, AND ALSO KEEP TRANSFORMATION MATRIX UP TO DATE
% zoiets
%if hasana; ana = shiftdim(ana,cfg.slicedim-1); end;
%if hasfun; fun = shiftdim(fun,cfg.slicedim-1); end;
%if hasmsk; msk = shiftdim(msk,cfg.slicedim-1); end;
%%%%% select slices
if ~ischar(cfg.slicerange)
ind_fslice = cfg.slicerange(1);
ind_lslice = cfg.slicerange(2);
elseif isequal(cfg.slicerange, 'auto')
if hasfun %default
if isfield(data,'inside')
ind_fslice = min(find(max(max(data.inside,[],1),[],2)));
ind_lslice = max(find(max(max(data.inside,[],1),[],2)));
else
ind_fslice = min(find(~isnan(max(max(fun,[],1),[],2))));
ind_lslice = max(find(~isnan(max(max(fun,[],1),[],2))));
end
elseif hasana %if only ana, no fun
ind_fslice = min(find(max(max(ana,[],1),[],2)));
ind_lslice = max(find(max(max(ana,[],1),[],2)));
else
error('no functional parameter and no anatomical parameter, can not plot');
end
else
error('do not understand cfg.slicerange');
end
ind_allslice = linspace(ind_fslice,ind_lslice,cfg.nslices);
ind_allslice = round(ind_allslice);
% make new ana, fun, msk, mskana with only the slices that will be plotted (slice dim is always third dimension)
if hasana; new_ana = ana(:,:,ind_allslice); clear ana; ana=new_ana; clear new_ana; end;
if hasfun; new_fun = fun(:,:,ind_allslice); clear fun; fun=new_fun; clear new_fun; end;
if hasmsk; new_msk = msk(:,:,ind_allslice); clear msk; msk=new_msk; clear new_msk; end;
%if hasmskana; new_mskana = mskana(:,:,ind_allslice); clear mskana; mskana=new_mskana; clear new_mskana; end;
% update the dimensions of the volume
if hasana; dim=size(ana); else dim=size(fun); end;
%%%%% make "quilts", that contain all slices on 2D patched sheet
% Number of patches along sides of Quilt (M and N)
% Size (in voxels) of side of patches of Quilt (m and n)
m = dim(1);
n = dim(2);
M = ceil(sqrt(dim(3)));
N = ceil(sqrt(dim(3)));
num_patch = N*M;
if cfg.slicedim~=3
error('only supported for slicedim=3');
end
num_slice = (dim(cfg.slicedim));
num_empt = num_patch-num_slice;
% put empty slides on ana, fun, msk, mskana to fill Quilt up
if hasana; ana(:,:,end+1:num_patch)=0; end;
if hasfun; fun(:,:,end+1:num_patch)=0; end;
if hasmsk; msk(:,:,end+1:num_patch)=0; end;
%if hasmskana; mskana(:,:,end:num_patch)=0; end;
% put the slices in the quilt
for iSlice = 1:num_slice
xbeg = floor((iSlice-1)./M);
ybeg = mod(iSlice-1, M);
if hasana
quilt_ana(ybeg.*m+1:(ybeg+1).*m, xbeg.*n+1:(xbeg+1).*n)=squeeze(ana(:,:,iSlice));
end
if hasfun
quilt_fun(ybeg.*m+1:(ybeg+1).*m, xbeg.*n+1:(xbeg+1).*n)=squeeze(fun(:,:,iSlice));
end
if hasmsk
quilt_msk(ybeg.*m+1:(ybeg+1).*m, xbeg.*n+1:(xbeg+1).*n)=squeeze(msk(:,:,iSlice));
end
% if hasmskana
% quilt_mskana(ybeg.*m+1:(ybeg+1).*m, xbeg.*n+1:(xbeg+1).*n)=squeeze(mskana(:,:,iSlice));
% end
end
% make vols and scales, containes volumes to be plotted (fun, ana, msk) %added ingnie
if hasana; vols2D{1} = quilt_ana; scales{1} = []; end; % needed when only plotting ana
if hasfun; vols2D{2} = quilt_fun; scales{2} = [fcolmin fcolmax]; end;
if hasmsk; vols2D{3} = quilt_msk; scales{3} = [opacmin opacmax]; end;
plot2D(vols2D, scales, doimage);
axis off
if strcmp(cfg.colorbar, 'yes'),
if hasfun
% use a normal Matlab coorbar
hc = colorbar;
set(hc, 'YLim', [fcolmin fcolmax]);
else
warning('no colorbar possible without functional data')
end
end
end
title(cfg.title);
set(gcf, 'renderer', cfg.renderer);
% get the output cfg
cfg = ft_checkconfig(cfg, 'trackconfig', 'off', 'checksize', 'yes');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% handle_ortho makes an overlay of 3D anatomical, functional and probability
% volumes. The three volumes must be scaled between 0 and 1.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [vols2D] = handle_ortho(vols, indx, slicedir, dim, doimage)
% put 2Dvolumes in fun, ana and msk
if length(vols)>=1 && isempty(vols{1}); hasana=0; else ana=vols{1}; hasana=1; end;
if length(vols)>=2
if isempty(vols{2}); hasfun=0; else fun=vols{2}; hasfun=1; end;
else hasfun=0; end
if length(vols)>=3
if isempty(vols{3}); hasmsk=0; else msk=vols{3}; hasmsk=1; end;
else hasmsk=0; end
% select the indices of the intersection
xi = indx(1);
yi = indx(2);
zi = indx(3);
qi = indx(4);
if length(indx)>4,
qi(2) = indx(5);
else
qi(2) = 1;
end
% select the slice to plot
if slicedir==1
yi = 1:dim(2);
zi = 1:dim(3);
elseif slicedir==2
xi = 1:dim(1);
zi = 1:dim(3);
elseif slicedir==3
xi = 1:dim(1);
yi = 1:dim(2);
end
% cut out the slice of interest
if hasana; ana = squeeze(ana(xi,yi,zi)); end;
if hasfun;
if doimage
fun = squeeze(fun(xi,yi,zi,:));
else
fun = squeeze(fun(xi,yi,zi,qi(1),qi(2)));
end
end
if hasmsk && length(size(msk))>3
msk = squeeze(msk(xi,yi,zi,qi(1),qi(2)));
elseif hasmsk
msk = squeeze(msk(xi,yi,zi));
end;
%put fun, ana and msk in vols2D
if hasana; vols2D{1} = ana; end;
if hasfun; vols2D{2} = fun; end;
if hasmsk; vols2D{3} = msk; end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% plot2D plots a two dimensional plot, used in ortho and slice
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function plot2D(vols2D, scales, doimage);
cla;
% put 2D volumes in fun, ana and msk
hasana = length(vols2D)>0 && ~isempty(vols2D{1});
hasfun = length(vols2D)>1 && ~isempty(vols2D{2});
hasmsk = length(vols2D)>2 && ~isempty(vols2D{3});
% the transpose is needed for displaying the matrix using the Matlab image() function
if hasana; ana = vols2D{1}'; end;
if hasfun && ~doimage; fun = vols2D{2}'; end;
if hasfun && doimage; fun = permute(vols2D{2},[2 1 3]); end;
if hasmsk; msk = vols2D{3}'; end;
if hasana
% scale anatomy between 0 and 1
fprintf('scaling anatomy\n');
amin = min(ana(:));
amax = max(ana(:));
ana = (ana-amin)./(amax-amin);
clear amin amax;
% convert anatomy into RGB values
ana = cat(3, ana, ana, ana);
ha = imagesc(ana);
end
hold on
if hasfun
if doimage
hf = image(fun);
else
hf = imagesc(fun);
try
caxis(scales{2});
end
% apply the opacity mask to the functional data
if hasmsk
% set the opacity
set(hf, 'AlphaData', msk)
set(hf, 'AlphaDataMapping', 'scaled')
try
alim(scales{3});
end
elseif hasana
set(hf, 'AlphaData', 0.5)
end
end
end
axis equal
axis tight
axis xy
|
github
|
philippboehmsturm/antx-master
|
ft_spike_rate.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_spike_rate.m
| 9,725 |
utf_8
|
fae9529146eb80f86cd4594d1ba8325a
|
function [rate] = ft_spike_rate(cfg,spike)
% FT_SPIKE_RATE computes the firing rate of spiketrains and their variance
%
% Use as
% [RATE] = FT_SPIKE_RATE(CFG,SPIKE)
%
% The input SPIKE should be organised as:
% The SPIKE datatype, obtained from FT_SPIKE_DATA2SPIKE or
% FT_SPIKE_MAKETRIALS.
%
% Configurations options:
%
% cfg.outputunit = - 'rate' (default) If 'rate', we convert the
% output per trial to firing rates (spikes/sec).
% - 'spike': we count the number spikes per trial.
% cfg.spikechannel = See FT_CHANNELSELECTION for details
% cfg.trials = - vector of indices (e.g., 1:2:10)
% - logical selection of trials (e.g., [1010101010])
% - 'all' (default), selects all trials% cfg.trials
% cfg.vartriallen = 'yes' (default) or 'no'.
% If 'yes' - accept variable trial lengths and use all available trials
% and the samples in every trial.
% If 'no' - only select those trials that fully cover the window as
% specified by cfg.latency and discard those trials that do not.
% cfg.latency = - [begin end] in seconds
% - 'maxperiod' (default)
% - 'minperiod', i.e., the minimal period all trials share
% - 'prestim' (all t<=0)
% - 'poststim' (all t>=0).
% cfg.keeptrials = 'yes' or 'no' (default).
%
% The outputs from spike are the following:
% - rate.trial: nTrials x nUnits matrix containing the firing rate per unit
% and trial
% - rate.avg: nTrials array containing the average firing rate per unit
% - rate.var: nTrials array containing the variance of firing rates per unit
% - rate.dof: nTrials array containing the degree of freedom per unit
% - rate.label: nUnits cell array containing the labels of the neuronal units%
% Copyright (C) 2010, Martin Vinck
% removed covariance / correlation here since one may get it very easily with COV or
% corrcoef
% ADD: selection on condition
% ADD: population script, for correlation - principal components - population vector
if nargin~=2, error('ft:spike_rate:nargin','Two input arguments required'), end
% defaults
defaults.outputunit = {'rate' 'spikecount'};
defaults.spikechannel = {'all'};
defaults.trials = {'all'};
defaults.latency = {'maxperiod'};
defaults.vartriallen = {'yes' 'no'};
defaults.keeptrials = {'yes' 'no'};
cfg = ft_spike_sub_defaultcfg(cfg,defaults);
% detect the format of spike, replace with CHECKDATA eventually, but that needs modification
hasAllFields = all(isfield(spike, {'time', 'trial', 'trialtime', 'label'}));
if ~hasAllFields, error('ft:spike_rate:wrongStructInput',...
'input spike should be struct with .time, .trial, .trialtime, .label fields')
end
% check whether all are of right format
correctInp = iscell(spike.time) && iscell(spike.trial) && iscell(spike.label) && isrealmat(spike.trialtime) ...
&& size(spike.trialtime,2)==2;
if ~correctInp, error('ft:spike_rate:wrongStructInput',...
'.time, .trial and .label should be cell arrays, trialtime should be nTrials-by-2 matrix')
end
% get the spikechannels
cfg.channel = ft_channelselection(cfg.spikechannel, spike.label);
spikesel = match_str(spike.label, cfg.channel);
nUnits = length(spikesel); % number of spike channels
if nUnits==0, error('ft:spike_rate:cfg:spikechannel:noSpikeChanSelected',...
'No spikechannel selected by means of cfg.spikechannel');
end
% get the number of trials
cfg = trialselection(cfg,spike);
nTrials = length(cfg.trials); % actual number of trials we use
% determine the duration of each trial
begTrialLatency = spike.trialtime(cfg.trials,1);
endTrialLatency = spike.trialtime(cfg.trials,2);
% select the latencies
cfg = latencyselection(cfg,begTrialLatency,endTrialLatency);
% check which trials will be used based on the latency
overlaps = endTrialLatency>(cfg.latency(1)) & begTrialLatency<(cfg.latency(2));
hasWindow = ones(nTrials,1);
if strcmp(cfg.vartriallen,'no') % only select trials that fully cover our latency window
startsLater = begTrialLatency>cfg.latency(1);
endsEarlier = endTrialLatency<cfg.latency(2);
hasWindow = ~(startsLater | endsEarlier); % it should not start later or end earlier
trialDur = ones(nTrials,1)*(cfg.latency(2)-cfg.latency(1));
elseif strcmp(cfg.vartriallen,'yes')
winBeg = max([begTrialLatency(:) cfg.latency(1)*ones(nTrials,1)],[],2);
winEnd = min([endTrialLatency(:) cfg.latency(2)*ones(nTrials,1)],[],2);
trialDur = winEnd-winBeg;
end
cfg.trials = cfg.trials(overlaps(:) & hasWindow(:));
trialDur = trialDur(overlaps(:) & hasWindow(:)); % select the durations, we will need this later
nTrials = length(cfg.trials);
% issue an explicit error if nothing was selected, this is in general indicative of bug
if isempty(cfg.trials), warning('ft:spike_rate:cfg:trials:noneSelected',...
'No trials were selected in the end, please give us something to analyse');
end
% preallocate before computing the psth
keepTrials = strcmp(cfg.keeptrials,'yes');
if keepTrials, singleTrials = NaN(nTrials,nUnits); end % preallocate single trials with NaNs
[s,ss] = deal(zeros(nUnits,1));
dof = nTrials*ones(nUnits,1); % compute degrees of freedom
for iUnit = 1:nUnits
unitIndx = spikesel(iUnit);
ts = spike.time{unitIndx}(:); % get the times
latencySel = ts>=cfg.latency(1) & ts<=cfg.latency(2); % select timestamps within latency
trialNums = spike.trial{unitIndx}(latencySel);% trial indices
% use the fact that trial numbers are integers >=1 apart, so we can use histc
trialBins = sort([cfg.trials-0.5; cfg.trials+0.5]);
trialRate = histc(trialNums(:),trialBins);
trialRate = trialRate(1:2:end-1); % the uneven bins correspond to the trial integers
if isempty(trialRate), trialRate = zeros(nTrials,1); end
% convert to firing rates if requested
if strcmp(cfg.outputunit,'rate') ,trialRate = trialRate(:)./trialDur(:); end
% store and compute sum, just fill the single trials up with nans
if keepTrials, singleTrials(:,iUnit) = trialRate(:); end
s(iUnit) = sum(trialRate);
ss(iUnit) = sum(trialRate.^2);
end
% compute the average rate
rate.avg = s ./ dof;
rate.var = (ss - s.^2./dof)./(dof); % since sumrate.^2 ./ dof = dof .* (sumrate/dof).^2
rate.var(dof<2) = 0;
% gather the rest of the results
rate.dof = dof;
rate.label = spike.label(spikesel);
rate.dimord = 'chan';
if (strcmp(cfg.keeptrials,'yes'))
rate.trial = singleTrials;
rate.dimord = 'rpt_chan';
end
% add version information to the configuration
try
% get the full name of the function
cfg.version.name = mfilename('fullpath');
catch
% required for compatibility with Matlab versions prior to release 13 (6.5)
[st, i] = dbstack;
cfg.version.name = st(i);
end
% remember the configuration details of the input data
try, cfg.previous = spike.cfg; end
% remember the exact configuration details in the output
rate.cfg = cfg;
%%%%%%%%% SUB FUNCTIONS %%%%%%%%%
function [cfg] = latencyselection(cfg,begTrialLatency,endTrialLatency)
if strcmp(cfg.latency,'minperiod')
cfg.latency = [max(begTrialLatency) min(endTrialLatency)];
elseif strcmp(cfg.latency,'maxperiod')
cfg.latency = [min(begTrialLatency) max(endTrialLatency)];
elseif strcmp(cfg.latency,'prestim')
cfg.latency = [min(begTrialLatency) 0];
elseif strcmp(cfg.latency,'poststim')
cfg.latency = [0 max(endTrialLatency)];
elseif ~isrealvec(cfg.latency)||length(cfg.latency)~=2
error('ft:spike_rate:cfg:latency',...
'cfg.latency should be "max", "min", "prestim", "poststim" or 1-by-2 numerical vector');
end
if cfg.latency(1)>cfg.latency(2), error('ft:spike_rate:incorrectLatencyWindow',...
'cfg.latency should be a vector in ascending order, i.e., cfg.latency(2)>cfg.latency(1)');
end
% check whether the time window fits with the data
if (cfg.latency(1) < min(begTrialLatency)), cfg.latency(1) = min(begTrialLatency);
warning('ft:spike_rate:incorrectLatencyWindow','%s %2.2f',...
'Correcting begin latency of averaging window to ', cfg.latency(1));
end
if (cfg.latency(2) > max(endTrialLatency)), cfg.latency(2) = max(endTrialLatency);
warning('ft:spike_rate:incorrectLatencyWindow','%s %2.2f',...
'Correcting end latency of averaging window to ',cfg.latency(2));
end
%%%
function [cfg] = trialselection(cfg,spike)
% get the number of trials or change DATA according to cfg.trials
nTrials = size(spike.trialtime,1);
if strcmp(cfg.trials,'all')
cfg.trials = 1:nTrials;
elseif islogical(cfg.trials)
cfg.trials = find(cfg.trials);
elseif ~isrealvec(cfg.trials);
error('ft:spike_rate:cfg:trials:unknownOption',...
'cfg.trials should be logical or numerical selection or string "all"');
end
cfg.trials = sort(cfg.trials(:));
if max(cfg.trials)>nTrials, error('ft:spike_rate:cfg:trials:maxExceeded',...
'maximum trial number in cfg.trials should not exceed length of DATA.trial')
end
if isempty(cfg.trials), error('ft:spike_rate:cfg:trials:noneSelected',...
'No trials were selected by you, rien ne va plus');
end
|
github
|
philippboehmsturm/antx-master
|
ft_megrealign.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_megrealign.m
| 18,970 |
utf_8
|
26effaa10bc2b32a00cc201f2126ce5b
|
function [interp] = ft_megrealign(cfg, data);
% FT_MEGREALIGN interpolates MEG data towards standard gradiometer locations
% by projecting the individual timelocked data towards a coarse source
% reconstructed representation and computing the magnetic field on
% the standard gradiometer locations.
%
% Use as
% [interp] = ft_megrealign(cfg, data)
%
% Required configuration options:
% cfg.template
% cfg.inwardshift
%
% The new gradiometer definition is obtained from a template dataset,
% or can be constructed by averaging the gradiometer positions over
% multiple datasets.
% cfg.template = single dataset that serves as template
% cfg.template(1..N) = datasets that are averaged into the standard
%
% The realignment is done by computing a minumum current estimate using a
% large number of dipoles that are placed in the upper layer of the brain
% surface, followed by a forward computation towards the template
% gradiometer array. This requires the specification of a volume conduction
% model of the head and of a source model.
%
% A head model must be specified with
% cfg.hdmfile = string, file containing the volume conduction model
% or alternatively manually using
% cfg.vol.r = radius of sphere
% cfg.vol.o = [x, y, z] position of origin
%
% A source model (i.e. a superficial layer with distributed sources) can be
% constructed from a headshape file, or from the volume conduction model
% cfg.spheremesh = number of dipoles in the source layer (default = 642)
% cfg.inwardshift = depth of the source layer relative to the headshape
% surface or volume conduction model (no default
% supplied, see below)
% cfg.headshape = a filename containing headshape, a structure containing a
% single triangulated boundary, or a Nx3 matrix with surface
% points
%
% If you specify a headshape and it describes the skin surface, you should specify an
% inward shift of 2.5 cm.
%
% For a single-sphere or a local-spheres volume conduction model based on the skin
% surface, an inward shift of 2.5 cm is reasonable.
%
% For a single-sphere or a local-spheres volume conduction model based on the brain
% surface, you should probably use an inward shift of about 1 cm.
%
% For a realistic single-shell volume conduction model based on the brain surface, you
% should probably use an inward shift of about 1 cm.
%
% Other options are
% cfg.pruneratio = for singular values, default is 1e-3
% cfg.verify = 'yes' or 'no', show the percentage difference (default = 'yes')
% cfg.feedback = 'yes' or 'no' (default = 'no')
% cfg.channel = Nx1 cell-array with selection of channels (default = 'MEG'),
% see FT_CHANNELSELECTION for details
% cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all')
%
% This implements the method described by T.R. Knosche, Transformation
% of whole-head MEG recordings between different sensor positions.
% Biomed Tech (Berl). 2002 Mar;47(3):59-62.
%
% To facilitate data-handling and distributed computing with the peer-to-peer
% module, this function has the following options:
% cfg.inputfile = ...
% cfg.outputfile = ...
% If you specify one of these (or both) the input data will be read from a *.mat
% file on disk and/or the output data will be written to a *.mat file. These mat
% files should contain only a single variable, corresponding with the
% input/output structure.
%
% See also FT_PREPARE_LOCALSPHERES, FT_PREPARE_SINGLESHELL
% This function depends on FT_PREPARE_DIPOLE_GRID
%
% This function depends on FT_PREPARE_VOL_SENS which has the following options:
% cfg.channel
% cfg.elec
% cfg.elecfile
% cfg.grad
% cfg.gradfile
% cfg.hdmfile, documented
% cfg.order
% cfg.vol, documented
% Copyright (C) 2004-2007, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_megrealign.m 3766 2011-07-04 10:44:39Z eelspa $
ft_defaults
% record start time and total processing time
ftFuncTimer = tic();
ftFuncClock = clock();
cfg = ft_checkconfig(cfg, 'trackconfig', 'on');
% set the default configuration
if ~isfield(cfg, 'headshape'), cfg.headshape = []; end
if ~isfield(cfg, 'pruneratio'), cfg.pruneratio = 1e-3; end
if ~isfield(cfg, 'spheremesh'), cfg.spheremesh = 642; end
if ~isfield(cfg, 'verify'), cfg.verify = 'yes'; end
if ~isfield(cfg, 'feedback'), cfg.feedback = 'yes'; end
if ~isfield(cfg, 'trials'), cfg.trials = 'all'; end
if ~isfield(cfg, 'channel'), cfg.channel = 'MEG'; end
if ~isfield(cfg, 'topoparam'), cfg.topoparam = 'rms'; end
if ~isfield(cfg, 'inputfile'), cfg.inputfile = []; end
if ~isfield(cfg, 'outputfile'), cfg.outputfile = []; end
% load optional given inputfile as data
hasdata = (nargin>1);
if ~isempty(cfg.inputfile)
% the input data should be read from file
if hasdata
error('cfg.inputfile should not be used in conjunction with giving input data to this function');
else
data = loadvar(cfg.inputfile, 'data');
end
end
% store original datatype
dtype = ft_datatype(data);
% check if the input data is valid for this function
data = ft_checkdata(data, 'datatype', 'raw', 'feedback', 'yes', 'hassampleinfo', 'yes', 'ismeg', 'yes');
% check if the input cfg is valid for this function
cfg = ft_checkconfig(cfg, 'renamed', {'plot3d', 'feedback'});
cfg = ft_checkconfig(cfg, 'renamedval', {'headshape', 'headmodel', []});
cfg = ft_checkconfig(cfg, 'required', {'inwardshift', 'template'});
%do realignment per trial
pertrial = all(ismember({'nasX';'nasY';'nasZ';'lpaX';'lpaY';'lpaZ';'rpaX';'rpaY';'rpaZ'}, data.label));
% put the low-level options pertaining to the dipole grid in their own field
cfg = ft_checkconfig(cfg, 'createsubcfg', {'grid'});
% select trials of interest
if ~strcmp(cfg.trials, 'all')
fprintf('selecting %d trials\n', length(cfg.trials));
data = ft_selectdata(data, 'rpt', cfg.trials);
end
Ntrials = length(data.trial);
% retain only the MEG channels in the data and temporarily store
% the rest, these will be added back to the transformed data later.
cfg.channel = ft_channelselection(cfg.channel, data.label);
dataindx = match_str(data.label, cfg.channel);
restindx = setdiff(1:length(data.label),dataindx);
if ~isempty(restindx)
fprintf('removing %d non-MEG channels from the data\n', length(restindx));
rest.label = data.label(restindx); % first remember the rest
data.label = data.label(dataindx); % then reduce the data
for i=1:Ntrials
rest.trial{i} = data.trial{i}(restindx,:); % first remember the rest
data.trial{i} = data.trial{i}(dataindx,:); % then reduce the data
end
else
rest.label = {};
rest.trial = {};
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% construct the average template gradiometer array
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Ntemplate = length(cfg.template);
for i=1:Ntemplate
if ischar(cfg.template{i}),
fprintf('reading template sensor position from %s\n', cfg.template{i});
template(i) = ft_read_sens(cfg.template{i});
elseif isstruct(cfg.template{i}) && isfield(cfg.template{i}, 'pnt') && isfield(cfg.template{i}, 'ori') && isfield(cfg.template{i}, 'tra'),
template(i) = cfg.template{i};
end
end
grad = ft_average_sens(template);
% construct the final template gradiometer definition
template = [];
template.grad = grad;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% FT_PREPARE_VOL_SENS will match the data labels, the gradiometer labels and the
% volume model labels (in case of a multisphere model) and result in a gradiometer
% definition that only contains the gradiometers that are present in the data.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
volcfg = [];
if isfield(cfg, 'hdmfile')
volcfg.hdmfile = cfg.hdmfile;
elseif isfield(cfg, 'vol')
volcfg.vol = cfg.vol;
end
volcfg.grad = data.grad;
volcfg.channel = data.label; % this might be a subset of the MEG channels
[volold, data.grad] = prepare_headmodel(volcfg);
% note that it is neccessary to keep the two volume conduction models
% seperate, since the single-shell Nolte model contains gradiometer specific
% precomputed parameters. Note that this is not guaranteed to result in a
% good projection for local sphere models.
volcfg.grad = template.grad;
volcfg.channel = 'MEG'; % include all MEG channels
[volnew, template.grad] = prepare_headmodel(volcfg);
if strcmp(ft_senstype(data.grad), ft_senstype(template.grad))
[id, it] = match_str(data.grad.label, template.grad.label);
fprintf('mean distance towards template gradiometers is %.2f %s\n', mean(sum((data.grad.pnt(id,:)-template.grad.pnt(it,:)).^2, 2).^0.5), template.grad.unit);
else
% the projection is from one MEG system to another MEG system, which makes a comparison of the data difficult
cfg.feedback = 'no';
cfg.verify = 'no';
end
% create the dipole grid on which the data will be projected
tmpcfg = [];
tmpcfg.vol = volold;
tmpcfg.grad = data.grad;
% copy all options that are potentially used in ft_prepare_sourcemodel
try, tmpcfg.grid = cfg.grid; end
try, tmpcfg.mri = cfg.mri; end
try, tmpcfg.headshape = cfg.headshape; end
try, tmpcfg.tightgrid = cfg.tightgrid; end
try, tmpcfg.symmetry = cfg.symmetry; end
try, tmpcfg.smooth = cfg.smooth; end
try, tmpcfg.threshold = cfg.threshold; end
try, tmpcfg.spheremesh = cfg.spheremesh; end
try, tmpcfg.inwardshift = cfg.inwardshift; end
try, tmpcfg.sourceunits = cfg.sourceunits; end
[grid, tmpcfg] = ft_prepare_sourcemodel(tmpcfg);
pos = grid.pos;
% sometimes some of the dipole positions are nan, due to problems with the headsurface triangulation
% remove them to prevent problems with the forward computation
sel = find(any(isnan(pos(:,1)),2));
pos(sel,:) = [];
% compute the forward model for the new gradiometer positions
fprintf('computing forward model for %d dipoles\n', size(pos,1));
lfnew = ft_compute_leadfield(pos, template.grad, volnew);
if ~pertrial,
%this needs to be done only once
lfold = ft_compute_leadfield(pos, data.grad, volold);
[realign, noalign, bkalign] = computeprojection(lfold, lfnew, cfg.pruneratio, cfg.verify);
else
%the forward model and realignment matrices have to be computed for each trial
%this also goes for the singleshell volume conductor model
%x = which('rigidbodyJM'); %this function is needed
%if isempty(x),
% error('you are trying out experimental code for which you need some extra functionality which is currently not in the release version of fieldtrip. if you are interested in trying it out, contact jan-mathijs');
%end
end
% interpolate the data towards the template gradiometers
for i=1:Ntrials
fprintf('realigning trial %d\n', i);
if pertrial,
%warp the gradiometer array according to the motiontracking data
sel = match_str(rest.label, {'nasX';'nasY';'nasZ';'lpaX';'lpaY';'lpaZ';'rpaX';'rpaY';'rpaZ'});
hmdat = rest.trial{i}(sel,:);
if ~all(hmdat==repmat(hmdat(:,1),[1 size(hmdat,2)]))
error('only one position per trial is at present allowed');
else
%M = rigidbodyJM(hmdat(:,1))
M = headcoordinates(hmdat(1:3,1),hmdat(4:6,1),hmdat(7:9,1));
grad = ft_transform_sens(M, data.grad);
end
volcfg.grad = grad;
%compute volume conductor
[volold, grad] = prepare_headmodel(volcfg);
%compute forward model
lfold = ft_compute_leadfield(pos, grad, volold);
%compute projection matrix
[realign, noalign, bkalign] = computeprojection(lfold, lfnew, cfg.pruneratio, cfg.verify);
end
data.realign{i} = realign * data.trial{i};
if strcmp(cfg.verify, 'yes')
% also compute the residual variance when interpolating
[id,it] = match_str(data.grad.label, template.grad.label);
rvrealign = rv(data.trial{i}(id,:), data.realign{i}(it,:));
fprintf('original -> template RV %.2f %%\n', 100 * mean(rvrealign));
datnoalign = noalign * data.trial{i};
datbkalign = bkalign * data.trial{i};
rvnoalign = rv(data.trial{i}, datnoalign);
rvbkalign = rv(data.trial{i}, datbkalign);
fprintf('original -> original RV %.2f %%\n', 100 * mean(rvnoalign));
fprintf('original -> template -> original RV %.2f %%\n', 100 * mean(rvbkalign));
end
end
% plot the topography before and after the realignment
if strcmp(cfg.feedback, 'yes')
warning('showing MEG topography (RMS value over time) in the first trial only');
Nchan = length(data.grad.label);
[id,it] = match_str(data.grad.label, template.grad.label);
pnt1 = data.grad.pnt(id,:);
pnt2 = template.grad.pnt(it,:);
prj1 = elproj(pnt1); tri1 = delaunay(prj1(:,1), prj1(:,2));
prj2 = elproj(pnt2); tri2 = delaunay(prj2(:,1), prj2(:,2));
switch cfg.topoparam
case 'rms'
p1 = sqrt(mean(data.trial{1}(id,:).^2, 2));
p2 = sqrt(mean(data.realign{1}(it,:).^2, 2));
case 'svd'
[u, s, v] = svd(data.trial{1}(id,:)); p1 = u(:,1);
[u, s, v] = svd(data.realign{1}(it,:)); p2 = u(:,1);
otherwise
error('unsupported cfg.topoparam');
end
X = [pnt1(:,1) pnt2(:,1)]';
Y = [pnt1(:,2) pnt2(:,2)]';
Z = [pnt1(:,3) pnt2(:,3)]';
% show figure with old an new helmets, volume model and dipole grid
figure
tmpcfg = [];
tmpcfg.vol = volold;
tmpcfg.grad = data.grad;
tmpcfg.grid = grid;
tmpcfg.plotsensors = 'no'; % these are plotted seperately below
ft_headmodelplot(tmpcfg);
hold on
plot3(pnt1(:,1), pnt1(:,2), pnt1(:,3), 'r.') % original positions
plot3(pnt2(:,1), pnt2(:,2), pnt2(:,3), 'g.') % template positions
line(X,Y,Z, 'color', 'black');
view(-90, 90);
% show figure with data on old helmet location
figure
hold on
plot3(pnt1(:,1), pnt1(:,2), pnt1(:,3), 'r.') % original positions
plot3(pnt2(:,1), pnt2(:,2), pnt2(:,3), 'g.') % template positions
line(X,Y,Z, 'color', 'black');
axis equal; axis vis3d
triplot(pnt1, tri1, p1);
title('RMS, before realignment')
view(-90, 90)
% show figure with data on new helmet location
figure
hold on
plot3(pnt1(:,1), pnt1(:,2), pnt1(:,3), 'r.') % original positions
plot3(pnt2(:,1), pnt2(:,2), pnt2(:,3), 'g.') % template positions
line(X,Y,Z, 'color', 'black');
axis equal; axis vis3d
triplot(pnt2, tri2, p2);
title('RMS, after realignment')
view(-90, 90)
end
% store the realigned data in a new structure
interp.label = template.grad.label;
interp.grad = template.grad; % replace with the template gradiometer array
interp.trial = data.realign; % remember the processed data
interp.fsample = data.fsample;
interp.time = data.time;
% add the rest channels back to the data, these were not interpolated
if ~isempty(rest.label)
fprintf('adding %d non-MEG channels back to the data (', length(rest.label));
fprintf('%s, ', rest.label{1:end-1});
fprintf('%s)\n', rest.label{end});
for trial=1:length(rest.trial)
interp.trial{trial} = [interp.trial{trial}; rest.trial{trial}];
end
interp.label = [interp.label; rest.label];
end
% accessing this field here is needed for the configuration tracking
% by accessing it once, it will not be removed from the output cfg
cfg.outputfile;
% get the output cfg
cfg = ft_checkconfig(cfg, 'trackconfig', 'off', 'checksize', 'yes');
% store the configuration of this function call, including that of the previous function call
cfg.version.name = mfilename('fullpath');
cfg.version.id = '$Id: ft_megrealign.m 3766 2011-07-04 10:44:39Z eelspa $';
% add information about the Matlab version used to the configuration
cfg.callinfo.matlab = version();
% add information about the function call to the configuration
cfg.callinfo.proctime = toc(ftFuncTimer);
cfg.callinfo.calltime = ftFuncClock;
cfg.callinfo.user = getusername();
% remember the configuration details of the input data
try, cfg.previous = data.cfg; end
% remember the exact configuration details in the output
interp.cfg = cfg;
% copy the trial specific information into the output
if isfield(data, 'trialinfo')
interp.trialinfo = data.trialinfo;
end
% copy the sampleinfo field as well
if isfield(data, 'sampleinfo')
interp.sampleinfo = data.sampleinfo;
end
% convert back to input type if necessary
switch dtype
case 'timelock'
interp = ft_checkdata(interp, 'datatype', 'timelock');
otherwise
% keep the output as it is
end
% the output data should be saved to a MATLAB file
if ~isempty(cfg.outputfile)
savevar(cfg.outputfile, 'data', interp); % use the variable name "data" in the output file
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% subfunction that computes the projection matrix(ces)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [realign, noalign, bkalign] = computeprojection(lfold, lfnew, pruneratio, verify)
% compute this inverse only once, although it is used twice
tmp = prunedinv(lfold, pruneratio);
% compute the three interpolation matrices
fprintf('computing interpolation matrix #1\n');
realign = lfnew * tmp;
if strcmp(verify, 'yes')
fprintf('computing interpolation matrix #2\n');
noalign = lfold * tmp;
fprintf('computing interpolation matrix #3\n');
bkalign = lfold * prunedinv(lfnew, pruneratio) * realign;
else
noalign = [];
bkalign = [];
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% subfunction that computes the inverse using a pruned SVD
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [lfi] = prunedinv(lf, r)
[u, s, v] = svd(lf);
if r<1,
% treat r as a ratio
p = find(s<(s(1,1)*r) & s~=0);
else
% treat r as the number of spatial components to keep
diagels = 1:(min(size(s))+1):(min(size(s)).^2);
p = diagels((r+1):end);
end
fprintf('pruning %d from %d, i.e. removing the %d smallest spatial components\n', length(p), min(size(s)), length(p));
s(p) = 0;
s(find(s~=0)) = 1./s(find(s~=0));
lfi = v * s' * u';
|
github
|
philippboehmsturm/antx-master
|
ft_volumelookup.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_volumelookup.m
| 11,255 |
utf_8
|
0c598c2c597ea0a8c5584aaa8fed4178
|
function [output] = ft_volumelookup(cfg, volume)
% FT_VOLUMELOOKUP can be used in to combine an anatomical or functional
% atlas with source recunstruction. You can use it for forward and reverse
% lookup.
%
% Given the anatomical or functional label, it looks up the locations and
% creates a mask (as a binary volume) based on the label, or creates a
% sphere or box around a point of interest. In this case the function is to
% be used as:
% mask = ft_volumelookup(cfg, volume)
%
% Given a binary volume that indicates a region of interest, it looks up
% the corresponding anatomical or functional labels from a given atlas. In
% this case the function is to be used as follows:
% labels = ft_volumelookup(cfg, volume)
%
% In both cases the input volume can be:
% mri is the output of FT_READ_MRI
% source is the output of FT_SOURCEANALYSIS
% stat is the output of FT_SOURCESTATISTICS
%
% The configuration options for a mask according to an atlas:
% cfg.inputcoord = 'mni' or 'tal', coordinate system of the mri/source/stat
% cfg.atlas = string, filename of atlas to use, either the AFNI
% brik file that is available from http://afni.nimh.nih.gov/afni/doc/misc/ttatlas_tlrc,
% or the WFU atlasses available from http://fmri.wfubmc.edu. see FT_PREPARE_ATLAS
% cfg.roi = string or cell of strings, region(s) of interest from anatomical atlas
%
% The configuration options for a spherical/box mask around a point of interest:
% cfg.roi = Nx3 vector, coordinates of the points of interest
% cfg.sphere = radius of each sphere in cm/mm dep on unit of input
% cfg.box = Nx3 vector, size of each box in cm/mm dep on unit of input
% cfg.round2nearestvoxel = 'yes' or 'no' (default = 'no'), voxel closest to point of interest is calculated
% and box/sphere is centered around coordinates of that voxel
%
% The configuration options for labels from a mask:
% cfg.inputcoord = 'mni' or 'tal', coordinate system of the mri/source/stat
% cfg.atlas = string, filename of atlas to use, either the AFNI
% brik file that is available from http://afni.nimh.nih.gov/afni/doc/misc/ttatlas_tlrc,
% or the WFU atlasses available from http://fmri.wfubmc.edu. see FT_PREPARE_ATLAS
% cfg.maskparameter = string, field in volume to be lookedup, data in field should be logical
% cfg.maxqueryrange = number, should be 1, 3, 5 (default = 1)
%
% The label output has a field "names", a field "count" and a field "usedqueryrange"
% To get a list of areas of the given mask you can do for instance:
% [tmp ind] = sort(labels.count,1,'descend');
% sel = find(tmp);
% for j = 1:length(sel)
% found_areas{j,1} = [num2str(labels.count(ind(j))) ': ' labels.name{ind(j)}];
% end
% in found_areas you can then see how many times which labels are found
% NB in the AFNI brick one location can have 2 labels!
%
% Dependent on the input coordinates and the coordinates of the atlas, the
% input MRI is transformed betweem MNI and Talairach-Tournoux coordinates
% See http://www.mrc-cbu.cam.ac.uk/Imaging/Common/mnispace.shtml for more details.
%
% See also FT_PREPARE_ATLAS, FT_SOURCEPLOT
% Copyright (C) 2008, Robert Oostenveld, Ingrid Nieuwenhuis
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_volumelookup.m 2439 2010-12-15 16:33:34Z johzum $
ft_defaults
roi2mask = 0;
mask2label = 0;
if isfield(cfg, 'roi');
roi2mask = 1;
elseif isfield(cfg, 'maskparameter')
mask2label = 1;
else
error('either specify cfg.roi, or cfg.maskparameter')
end
if roi2mask
% only for volume data
volume = ft_checkdata(volume, 'datatype', 'volume');
% set the defaults
if ~isfield(cfg, 'round2nearestvoxel'), cfg.round2nearestvoxel = 'no'; end
if iscell(cfg.roi) || ischar(cfg.roi)
ft_checkconfig(cfg, 'forbidden', {'sphere' 'box'}, 'required', {'atlas' 'inputcoord'});
isatlas = 1;
ispoi = 0;
elseif isnumeric(cfg.roi)
ft_checkconfig(cfg, 'forbidden', {'atlas' 'inputcoord'});
isatlas = 0;
ispoi = 1;
else
error('do not understand cfg.roi')
end
% determine location of each anatomical voxel in its own voxel coordinates
dim = volume.dim;
i = 1:dim(1);
j = 1:dim(2);
k = 1:dim(3);
[I, J, K] = ndgrid(i, j, k);
ijk = [I(:) J(:) K(:) ones(prod(dim),1)]';
% determine location of each anatomical voxel in head coordinates
xyz = volume.transform * ijk; % note that this is 4xN
if isatlas
atlas = ft_prepare_atlas(cfg.atlas);
if ischar(cfg.roi)
cfg.roi = {cfg.roi};
end
sel = [];
for i = 1:length(cfg.roi)
sel = [sel; strmatch(cfg.roi{i}, atlas.descr.name, 'exact')];
end
fprintf('found %d matching anatomical labels\n', length(sel));
brick = atlas.descr.brick(sel);
value = atlas.descr.value(sel);
% convert between MNI head coordinates and TAL head coordinates
% coordinates should be expressed compatible with the atlas
if strcmp(cfg.inputcoord, 'mni') && strcmp(atlas.coord, 'tal')
xyz(1:3,:) = mni2tal(xyz(1:3,:));
elseif strcmp(cfg.inputcoord, 'mni') && strcmp(atlas.coord, 'mni')
% nothing to do
elseif strcmp(cfg.inputcoord, 'tal') && strcmp(atlas.coord, 'tal')
% nothing to do
elseif strcmp(cfg.inputcoord, 'tal') && strcmp(atlas.coord, 'mni')
xyz(1:3,:) = tal2mni(xyz(1:3,:));
end
% determine location of each anatomical voxel in atlas voxel coordinates
ijk = inv(atlas.transform) * xyz;
ijk = round(ijk(1:3,:))';
inside_vol = ijk(:,1)>=1 & ijk(:,1)<=atlas.dim(1) & ...
ijk(:,2)>=1 & ijk(:,2)<=atlas.dim(2) & ...
ijk(:,3)>=1 & ijk(:,3)<=atlas.dim(3);
inside_vol = find(inside_vol);
% convert the selection inside the atlas volume into linear indices
ind = sub2ind(atlas.dim, ijk(inside_vol,1), ijk(inside_vol,2), ijk(inside_vol,3));
brick0_val = zeros(prod(dim),1);
brick1_val = zeros(prod(dim),1);
% search the two bricks for the value of each voxel
brick0_val(inside_vol) = atlas.brick0(ind);
brick1_val(inside_vol) = atlas.brick1(ind);
mask = zeros(prod(dim),1);
for i=1:length(sel)
fprintf('constructing mask for %s\n', atlas.descr.name{sel(i)});
if brick(i)==0
mask = mask | (brick0_val==value(i));
elseif brick(i)==1
mask = mask | (brick1_val==value(i));
end
end
elseif ispoi
if strcmp(cfg.round2nearestvoxel, 'yes')
for i=1:size(cfg.roi,1)
cfg.roi(i,:) = poi2voi(cfg.roi(i,:), xyz);
end
end
% sphere(s)
if isfield(cfg, 'sphere')
mask = zeros(1,prod(dim));
for i=1:size(cfg.roi,1)
dist = sqrt( (xyz(1,:) - cfg.roi(i,1)).^2 + (xyz(2,:) - cfg.roi(i,2)).^2 + (xyz(3,:) - cfg.roi(i,3)).^2 );
mask = mask | (dist <= cfg.sphere(i));
end
% box(es)
elseif isfield(cfg, 'box')
mask = zeros(1, prod(dim));
for i=1:size(cfg.roi,1)
mask = mask | ...
(xyz(1,:) <= (cfg.roi(i,1) + cfg.box(i,1)./2) & xyz(1,:) >= (cfg.roi(i,1) - cfg.box(i,1)./2)) & ...
(xyz(2,:) <= (cfg.roi(i,2) + cfg.box(i,2)./2) & xyz(2,:) >= (cfg.roi(i,2) - cfg.box(i,2)./2)) & ...
(xyz(3,:) <= (cfg.roi(i,3) + cfg.box(i,3)./2) & xyz(3,:) >= (cfg.roi(i,3) - cfg.box(i,3)./2));
end
else
error('either specify cfg.sphere or cfg.box')
end
end
mask = reshape(mask, dim);
fprintf('%i voxels in mask, which is %.3f %% of total volume\n', sum(mask(:)), 100*mean(mask(:)));
output = mask;
elseif mask2label
% convert to source representation (easier to work with)
volume = ft_checkdata(volume, 'datatype', 'source');
ft_checkconfig(cfg, 'required', {'atlas' 'inputcoord'});
% set defaults
if ~isfield(cfg, 'maxqueryrange'), cfg.maxqueryrange = 1; end
if isempty(intersect(cfg.maxqueryrange, [1 3 5]))
error('incorrect query range, should be one of [1 3 5]');
end
atlas = ft_prepare_atlas(cfg.atlas);
sel = find(volume.(cfg.maskparameter)(:));
labels.name = atlas.descr.name;
labels.name{end+1} = 'no_label_found';
labels.count = zeros(length(labels.name),1);
for iLab = 1:length(labels.name)
labels.usedqueryrange{iLab} = [];
end
for iVox = 1:length(sel)
usedQR = 1;
label = atlas_lookup(atlas, [volume.pos(sel(iVox),1) volume.pos(sel(iVox),2) volume.pos(sel(iVox),3)], 'inputcoord', cfg.inputcoord, 'queryrange', 1);
if isempty(label) && cfg.maxqueryrange > 1
label = atlas_lookup(atlas, [volume.pos(sel(iVox),1) volume.pos(sel(iVox),2) volume.pos(sel(iVox),3)], 'inputcoord', cfg.inputcoord, 'queryrange', 3);
usedQR = 3;
end
if isempty(label) && cfg.maxqueryrange > 3
label = atlas_lookup(atlas, [volume.pos(sel(iVox),1) volume.pos(sel(iVox),2) volume.pos(sel(iVox),3)], 'inputcoord', cfg.inputcoord, 'queryrange', 5);
usedQR = 5;
end
if isempty(label)
label = {'no_label_found'};
elseif length(label) == 1
label = {label};
end
ind_lab = [];
for iLab = 1:length(label)
ind_lab = [ind_lab find(strcmp(label{iLab}, labels.name))];
end
labels.count(ind_lab) = labels.count(ind_lab) + (1/length(ind_lab));
for iFoundLab = 1:length(ind_lab)
if isempty(labels.usedqueryrange{ind_lab(iFoundLab)})
labels.usedqueryrange{ind_lab(iFoundLab)} = usedQR;
else
labels.usedqueryrange{ind_lab(iFoundLab)} = [labels.usedqueryrange{ind_lab(iFoundLab)} usedQR];
end
end
end %iVox
output = labels;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION point of interest to voxel of interest
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function voi = poi2voi(poi, xyz)
xmin = min(abs(xyz(1,:) - poi(1))); xcl = round(abs(xyz(1,:) - poi(1))) == round(xmin);
ymin = min(abs(xyz(2,:) - poi(2))); ycl = round(abs(xyz(2,:) - poi(2))) == round(ymin);
zmin = min(abs(xyz(3,:) - poi(3))); zcl = round(abs(xyz(3,:) - poi(3))) == round(zmin);
xyzcls = xcl + ycl + zcl; ind_voi = xyzcls == 3;
if sum(ind_voi) > 1;
fprintf('%i voxels at same distance of poi, taking first voxel\n', sum(ind_voi))
ind_voi_temp = find(ind_voi); ind_voi_temp = ind_voi_temp(1);
ind_voi = zeros(size(ind_voi));
ind_voi(ind_voi_temp) = 1;
ind_voi = logical(ind_voi);
end
voi = xyz(1:3,ind_voi);
fprintf('coordinates of voi: %.1f %.1f %.1f\n', voi(1), voi(2), voi(3));
|
github
|
philippboehmsturm/antx-master
|
ft_freqanalysis_tfr.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_freqanalysis_tfr.m
| 8,844 |
utf_8
|
1a8fc9097d265161321abe1a02974fb5
|
function [freq] = ft_freqanalysis_tfr(cfg, data);
% FT_FREQANALYSIS_TFR computes time-frequency representations of single-trial
% data using a convolution in the time-domain with Morlet's wavelets.
%
% Use as
% [freq] = ft_freqanalysis(cfg, data)
%
% The data should be organised in a structure as obtained from
% the FT_PREPROCESSING function. The configuration should be according to
% cfg.method = method used for frequency or time-frequency decomposition
% see FT_FREQANALYSIS for details
% cfg.foi = vector 1 x numfoi, frequencies of interest
% cfg.waveletwidth = 'width' of wavelets expressed in cycles (default = 7)
% cfg.channel = Nx1 cell-array with selection of channels (default = 'all'),
% see FT_CHANNELSELECTION for details
% cfg.downsample = ratio for downsampling, which occurs after convolution (default = 1)
% cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all')
% cfg.keeptrials = 'yes' or 'no', return individual trials or average (default = 'no')
%
% See also FT_FREQANALYSIS
% Undocumented local options:
% cfg.latency
% cfg.output
% Copyright (C) 2003, Ole Jensen, FCDC
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_freqanalysis_tfr.m 3710 2011-06-16 14:04:19Z eelspa $
ft_defaults
% record start time and total processing time
ftFuncTimer = tic();
ftFuncClock = clock();
% ensure that this function is started as a subfunction of the FT_FREQANALYSIS wrapper
if ~exist('OCTAVE_VERSION')
[s, i] = dbstack;
if length(s)>1
[caller_path, caller_name, caller_ext] = fileparts(s(2).name);
else
caller_path = '';
caller_name = '';
caller_ext = '';
end
% evalin('caller', 'mfilename') does not work for Matlab 6.1 and 6.5
if ~strcmp(caller_name, 'ft_freqanalysis')
error(['you should call FREQANALYSIS, instead of the ' upper(mfilename) ' subfunction']);
end
end
% set the defaults
if ~isfield(cfg, 'method'), cfg.method = 'tfr'; end
if ~isfield(cfg, 'channel'), cfg.channel = 'all'; end
if ~isfield(cfg, 'latency'), cfg.latency = 'minperlength'; end
if ~isfield(cfg, 'keeptrials'), cfg.keeptrials = 'no'; end
if ~isfield(cfg, 'waveletwidth'), cfg.waveletwidth = 7; end
if ~isfield(cfg, 'downsample'), cfg.downsample = 1; end
if ~isfield(cfg, 'feedback'), cfg.feedback = 'text'; end
if isfield(cfg, 'output') && strcmp(cfg.output, 'powandcsd'),
error('This function does not compute cross-spectra\n');
end
% determine the channels of interest
cfg.channel = ft_channelselection(cfg.channel, data.label);
chansel = match_str(data.label, cfg.channel);
% determine the duration of each trial
ntrial = length(data.trial);
nchan = size(data.trial{1}, 1);
for i=1:ntrial
nsampl(i) = size(data.trial{i}, 2);
begsamplatency(i) = min(data.time{i});
endsamplatency(i) = max(data.time{i});
end;
if cfg.downsample > 1
% perform a decimation of the input data
warning('decimating the input data, better is to use RESAMPLEDATA');
for k=1:ntrial
dTmp = data.trial{k};
data.trial{k} = dTmp(:,1:cfg.downsample:end);
tTmp = data.time{k};
data.time{k} = tTmp(1:cfg.downsample:end);
end
data.fsample = data.fsample / cfg.downsample;
end
% automatically determine the latency window which is possible in all trials
minperlength = [max(begsamplatency) min(endsamplatency)];
% latency window for averaging and variance computation is given in seconds
if (strcmp(cfg.latency, 'minperlength'))
cfg.latency = [];
cfg.latency(1) = minperlength(1);
cfg.latency(2) = minperlength(2);
end
if (strcmp(cfg.latency, 'prestim'))
cfg.latency = [];
cfg.latency(1) = minperlength(1);
cfg.latency(2) = 0;
end
if (strcmp(cfg.latency, 'poststim'))
cfg.latency = [];
cfg.latency(1) = 0;
cfg.latency(2) = minperlength(2);
end
M = waveletfam(cfg.foi,data.fsample,cfg.waveletwidth);
ft_progress('init', cfg.feedback, 'convolving wavelets');
for i=1:ntrial
indicvect = data.time{i};
ft_progress(i/ntrial, 'convolving wavelets, trial %d of %d\n', i, ntrial);
%for average and variance
begsampl = nearest(indicvect,cfg.latency(1));
endsampl = nearest(indicvect,cfg.latency(2));
numsamples(i) = endsampl-begsampl+1;
if (i==1)
% allocate memory to hold the resulting powerspectra
if strcmp(cfg.keeptrials, 'yes')
freq.powspctrm = zeros(ntrial,nchan,length(cfg.foi),ceil((endsampl-begsampl+1)/cfg.downsample));
else
freq.powspctrm = zeros(nchan,length(cfg.foi),ceil((endsampl-begsampl+1)/cfg.downsample));
end
end;
dat = data.trial{i}(chansel,begsampl:endsampl);
for k=1:size(dat,1)
for j=1:length(cfg.foi)
cTmp = conv(dat(k,:),M{j});
cTmp = 2*(abs(cTmp).^2)/data.fsample;
cTmp = cTmp(ceil(length(M{j})/2):length(cTmp)-floor(length(M{j})/2));
cTmp = cTmp(:,1:cfg.downsample:end);
if strcmp(cfg.keeptrials, 'yes')
freq.powspctrm(i,k,j,:) = cTmp';
else
freq.powspctrm(k,j,:) = squeeze(freq.powspctrm(k,j,:)) + cTmp'; % compute the running sum
end
end
end
end %for ntrial
ft_progress('close');
if strcmp(cfg.keeptrials, 'yes')
freq.dimord = 'rpt_chan_freq_time';
else
freq.dimord = 'chan_freq_time';
freq.powspctrm = freq.powspctrm / ntrial; % compute the average
end
freq.label = cfg.channel;
freq.freq = cfg.foi;
freq.time = indicvect(1:cfg.downsample:end);
% get the output cfg
cfg = ft_checkconfig(cfg, 'trackconfig', 'off', 'checksize', 'yes');
% add version information to the configuration
try
% get the full name of the function
cfg.version.name = mfilename('fullpath');
catch
% required for compatibility with Matlab versions prior to release 13 (6.5)
[st, i] = dbstack;
cfg.version.name = st(i);
end
cfg.version.id = '$Id: ft_freqanalysis_tfr.m 3710 2011-06-16 14:04:19Z eelspa $';
% add information about the Matlab version used to the configuration
cfg.callinfo.matlab = version();
% add information about the function call to the configuration
cfg.callinfo.proctime = toc(ftFuncTimer);
cfg.callinfo.calltime = ftFuncClock;
cfg.callinfo.user = getusername();
% remember the configuration details of the input data
try, cfg.previous = data.cfg; end
% remember the exact configuration details in the output
freq.cfg = cfg;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION for waveletanalysis
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function M = waveletfam(foi,Fs,width)
dt = 1/Fs;
for k=1:length(foi)
sf = foi(k)/width;
st = 1/(2*pi*sf);
toi=-3.5*st:dt:3.5*st;
A = 1/sqrt(st*sqrt(pi));
M{k}= A*exp(-toi.^2/(2*st^2)).*exp(i*2*pi*foi(k).*toi);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION for waveletanalysis
%
% Return a vector containing the energy as a
% function of time for frequency f. The energy
% is calculated using Morlet's wavelets.
% s : signal
% Fs: sampling frequency
% width: width of Morlet wavelet (>= 5 suggested).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function y = energyvec(f,s,Fs,width)
dt = 1/Fs;
sf = f/width;
st = 1/(2*pi*sf);
t=-3.5*st:dt:3.5*st;
m = morlet(f,t,width);
size(m)
y = conv(s,m);
y = (2*abs(y)/Fs).^2;
y = y(ceil(length(m)/2):length(y)-floor(length(m)/2));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% subfunction for waveletanalysis
%
% Morlet's wavelet for frequency f and time t.
% The wavelet will be normalized so the total energy is 1.
% width defines the ``width'' of the wavelet.
% A value >= 5 is suggested.
%
% Ref: Tallon-Baudry et al., J. Neurosci. 15, 722-734 (1997)
%
% See also: PHASEGRAM, PHASEVEC, WAVEGRAM, ENERGY
%
% Ole Jensen, August 1998
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function y = morlet(f,t,width)
sf = f/width;
st = 1/(2*pi*sf);
A = 1/sqrt(st*sqrt(pi));
y = A*exp(-t.^2/(2*st^2)).*exp(i*2*pi*f.*t);
|
github
|
philippboehmsturm/antx-master
|
ft_multiplotTFR.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_multiplotTFR.m
| 27,659 |
utf_8
|
e73168c92f7898f4de31ba530431bcf3
|
function [cfg] = ft_multiplotTFR(cfg, data)
% ft_multiplotTFR plots time-frequency representations of power or coherence in a
% topographical layout. The plots of the indivual sensors are arranged according
% to their location specified in the layout.
%
% Use as:
% ft_multiplotTFR(cfg, data)
%
% The data can be a time-frequency representation of power or coherence
% that
% was computed using the FT_FREQANALYSIS or FT_FREQDESCRIPTIVES functions.
%
% The configuration can have the following parameters:
% cfg.xparam = field to be plotted on x-axis (default depends on
% data.dimord)
% 'time'
% cfg.yparam = field to be plotted on y-axis (default depends on data.dimord)
% 'freq'
% cfg.zparam = field to be represented as color (default depends on data.dimord)
% 'powspctrm' or 'cohspctrm'
% cfg.maskparameter = field in the data to be used for opacity masking of data
% cfg.maskstyle = style used to mask nans, 'opacity' or 'saturation' (default = 'opacity')
% use 'saturation' when saving to vector-format (like *.eps) to avoid all
% sorts of image-problems (currently only possible with a white backgroud)
% cfg.maskalpha = alpha value used for masking areas dictated by cfg.maskparameter (0 - 1, default = 1)
% cfg.xlim = 'maxmin' or [xmin xmax] (default = 'maxmin')
% cfg.ylim = 'maxmin' or [ymin ymax] (default = 'maxmin')
% cfg.zlim = 'maxmin','maxabs' or [zmin zmax] (default = 'maxmin')
% cfg.gradscale = number, scaling to apply to the MEG gradiometer channels prior to display
% cfg.magscale = number, scaling to apply to the MEG magnetometer channels prior to display
% cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), see FT_CHANNELSELECTION for details
% cfg.refchannel = name of reference channel for visualising connectivity, can be 'gui'
% cfg.baseline = 'yes','no' or [time1 time2] (default = 'no'), see FT_FREQBASELINE
% cfg.baselinetype = 'absolute' or 'relative' (default = 'absolute')
% cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all')
% cfg.box = 'yes', 'no' (default = 'no' if maskparameter given default = 'yes')
% Draw a box around each graph
% cfg.hotkeys = enables hotkeys (up/down arrows) for dynamic colorbar adjustment
% cfg.colorbar = 'yes', 'no' (default = 'no')
% cfg.colormap = any sized colormap, see COLORMAP
% cfg.comment = string of text (default = date + zlimits)
% Add 'comment' to graph (according to COMNT in the layout)
% cfg.showlabels = 'yes', 'no' (default = 'no')
% cfg.showoutline = 'yes', 'no' (default = 'no')
% cfg.fontsize = font size of comment and labels (if present) (default = 8)
% cfg.interactive = Interactive plot 'yes' or 'no' (default = 'no')
% In a interactive plot you can select areas and produce a new
% interactive plot when a selected area is clicked. Multiple areas
% can be selected by holding down the SHIFT key.
% cfg.masknans = 'yes' or 'no' (default = 'yes')
% cfg.renderer = 'painters', 'zbuffer',' opengl' or 'none' (default = [])
% cfg.layout = specify the channel layout for plotting using one of
% the following ways:
%
% The layout defines how the channels are arranged and what the size of each
% subplot is. You can specify the layout in a variety of ways:
% - you can provide a pre-computed layout structure (see ft_prepare_layout)
% - you can give the name of an ascii layout file with extension *.lay
% - you can give the name of an electrode file
% - you can give an electrode definition, i.e. "elec" structure
% - you can give a gradiometer definition, i.e. "grad" structure
% If you do not specify any of these and the data structure contains an
% electrode or gradiometer structure (common for MEG data, since the header
% of the MEG datafile contains the gradiometer information), that will be
% used for creating a layout. If you want to have more fine-grained control
% over the layout of the subplots, you should create your own layout file.
%
% To facilitate data-handling and distributed computing with the peer-to-peer
% module, this function has the following option:
% cfg.inputfile = ...
% If you specify this option the input data will be read from a *.mat
% file on disk. This mat files should contain only a single variable named 'data',
% corresponding to the input structure. For this particular function, the
% data should be provided as a cell array.
%
% See also:
% FT_MULTIPLOTER, FT_SINGLEPLOTER, FT_SINGLEPLOTTFR, FT_TOPOPLOTER, FT_TOPOPLOTTFR,
% FT_PREPARE_LAYOUT
% Undocumented local options:
% cfg.channel
% cfg.layoutname
% cfg.xparam
% cfg.zparam
%
% This function depends on FT_FREQBASELINE which has the following options:
% cfg.baseline, documented
% cfg.baselinetype, documented
% Copyright (C) 2003-2006, Ole Jensen
% Copyright (C) 2007-2011, Roemer van der Meij & Jan-Mathijs Schoffelen
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_multiplotTFR.m 3883 2011-07-20 13:21:04Z eelspa $
ft_defaults
cfg = ft_checkconfig(cfg, 'trackconfig', 'on');
cfg = ft_checkconfig(cfg, 'unused', {'cohtargetchannel'});
cfg = ft_checkconfig(cfg, 'renamedval', {'zlim', 'absmax', 'maxabs'});
cfg = ft_checkconfig(cfg, 'renamedval', {'matrixside', 'feedforward', 'outflow'});
cfg = ft_checkconfig(cfg, 'renamedval', {'matrixside', 'feedback', 'inflow'});
cfg = ft_checkconfig(cfg, 'renamed', {'cohrefchannel', 'refchannel'});
% set default for inputfile
if ~isfield(cfg, 'inputfile'), cfg.inputfile = []; end
hasdata = (nargin>1);
hasinputfile = ~isempty(cfg.inputfile);
if hasdata && hasinputfile
error('cfg.inputfile should not be used in conjunction with giving input data to this function');
end
if hasdata
% do nothing
elseif hasinputfile
data = loadvar(cfg.inputfile, 'data');
end
% Set the defaults:
if ~isfield(cfg,'baseline'), cfg.baseline = 'no'; end
if ~isfield(cfg,'baselinetype'), cfg.baselinetype = 'absolute'; end
if ~isfield(cfg,'trials'), cfg.trials = 'all'; end
if ~isfield(cfg,'xlim'), cfg.xlim = 'maxmin'; end
if ~isfield(cfg,'ylim'), cfg.ylim = 'maxmin'; end
if ~isfield(cfg,'zlim'), cfg.zlim = 'maxmin'; end
if ~isfield(cfg,'magscale'), cfg.magscale = 1; end
if ~isfield(cfg,'gradscale'), cfg.gradscale = 1; end
if ~isfield(cfg,'colorbar'), cfg.colorbar = 'no'; end
if ~isfield(cfg,'comment'), cfg.comment = date; end
if ~isfield(cfg,'showlabels'), cfg.showlabels = 'no'; end
if ~isfield(cfg,'showoutline'), cfg.showoutline = 'no'; end
if ~isfield(cfg,'channel'), cfg.channel = 'all'; end
if ~isfield(cfg,'fontsize'), cfg.fontsize = 8; end
if ~isfield(cfg,'interactive'), cfg.interactive = 'no'; end
if ~isfield(cfg,'hotkeys'), cfg.hotkeys = 'no'; end
if ~isfield(cfg,'renderer'), cfg.renderer = []; end % let matlab decide on default
if ~isfield(cfg,'maskalpha'), cfg.maskalpha = 1; end
if ~isfield(cfg,'masknans'), cfg.masknans = 'no'; end
if ~isfield(cfg,'maskparameter'), cfg.maskparameter = []; end
if ~isfield(cfg,'maskstyle'), cfg.maskstyle = 'opacity'; end
if ~isfield(cfg,'matrixside'), cfg.matrixside = 'outflow'; end
if ~isfield(cfg,'channel'), cfg.channel = 'all'; end
if ~isfield(cfg,'box')
if ~isempty(cfg.maskparameter)
cfg.box = 'yes';
else
cfg.box = 'no';
end
end
% for backward compatibility with old data structures
data = ft_checkdata(data, 'datatype', 'freq');
dimord = data.dimord;
dimtok = tokenize(dimord, '_');
% Set x/y/zparam defaults
if ~any(ismember(dimtok, 'time'))
error('input data needs a time dimension');
else
if ~isfield(cfg, 'xparam'), cfg.xparam='time'; end
if ~isfield(cfg, 'yparam'), cfg.yparam='freq'; end
if ~isfield(cfg, 'zparam'), cfg.zparam='powspctrm'; end
end
if isfield(cfg, 'channel') && isfield(data, 'label')
cfg.channel = ft_channelselection(cfg.channel, data.label);
elseif isfield(cfg, 'channel') && isfield(data, 'labelcmb')
cfg.channel = ft_channelselection(cfg.channel, unique(data.labelcmb(:)));
end
% perform channel selection but only allow this when cfg.interactive = 'no'
if isfield(data, 'label') && strcmp(cfg.interactive, 'no')
selchannel = ft_channelselection(cfg.channel, data.label);
elseif isfield(data, 'labelcmb') && strcmp(cfg.interactive, 'no')
selchannel = ft_channelselection(cfg.channel, unique(data.labelcmb(:)));
end
% check whether rpt/subj is present and remove if necessary and whether
hasrpt = any(ismember(dimtok, {'rpt' 'subj'}));
if hasrpt,
% this also deals with fourier-spectra in the input
% or with multiple subjects in a frequency domain stat-structure
% on the fly computation of coherence spectrum is not supported
if isfield(data, 'crsspctrm'),
data = rmfield(data, 'crsspctrm');
end
tmpcfg = [];
tmpcfg.trials = cfg.trials;
tmpcfg.jackknife = 'no';
if isfield(cfg, 'zparam') && ~strcmp(cfg.zparam,'powspctrm')
% freqdesctiptives will only work on the powspctrm field
% hence a temporary copy of the data is needed
tempdata.dimord = data.dimord;
tempdata.freq = data.freq;
tempdata.label = data.label;
tempdata.powspctrm = data.(cfg.zparam);
tempdata.cfg = data.cfg;
tempdata = ft_freqdescriptives(tmpcfg, tempdata);
data.(cfg.zparam) = tempdata.powspctrm;
clear tempdata
else
data = ft_freqdescriptives(tmpcfg, data);
end
dimord = data.dimord;
dimtok = tokenize(dimord, '_');
end % if hasrpt
% Read or create the layout that will be used for plotting:
clf;
lay = ft_prepare_layout(cfg, data);
cfg.layout = lay;
ft_plot_lay(lay, 'box', false,'label','no','point','no');
% Apply baseline correction:
if ~strcmp(cfg.baseline, 'no')
data = ft_freqbaseline(cfg, data);
end
% Handle the bivariate case
% Check for bivariate metric with 'chan_chan' in the dimord
selchan = strmatch('chan', dimtok);
isfull = length(selchan)>1;
% Check for bivariate metric with a labelcmb
haslabelcmb = isfield(data, 'labelcmb');
if (isfull || haslabelcmb) && isfield(data, cfg.zparam)
% A reference channel is required:
if ~isfield(cfg, 'refchannel')
error('no reference channel is specified');
end
% check for refchannel being part of selection
if ~strcmp(cfg.refchannel,'gui')
if (isfull && ~any(ismember(data.label, cfg.refchannel))) || ...
(haslabelcmb && ~any(ismember(data.labelcmb(:), cfg.refchannel)))
error('cfg.refchannel is a not present in the (selected) channels)')
end
end
% Interactively select the reference channel
if strcmp(cfg.refchannel, 'gui')
% Open a single figure with the channel layout, the user can click on a reference channel
h = clf;
ft_plot_lay(lay, 'box', false);
title('Select the reference channel by dragging a selection window, more than 1 channel can be selected...');
% add the channel information to the figure
info = guidata(gcf);
info.x = lay.pos(:,1);
info.y = lay.pos(:,2);
info.label = lay.label;
guidata(h, info);
%set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'callback', {@select_topoplotER, cfg, data}});
set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_multiplotTFR, cfg, data}, 'event', 'WindowButtonUpFcn'});
set(gcf, 'WindowButtonDownFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_multiplotTFR, cfg, data}, 'event', 'WindowButtonDownFcn'});
set(gcf, 'WindowButtonMotionFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_multiplotTFR, cfg, data}, 'event', 'WindowButtonMotionFcn'});
return
end
if ~isfull,
% Convert 2-dimensional channel matrix to a single dimension:
if isempty(cfg.matrixside)
sel1 = strmatch(cfg.refchannel, data.labelcmb(:,2), 'exact');
sel2 = strmatch(cfg.refchannel, data.labelcmb(:,1), 'exact');
elseif strcmp(cfg.matrixside, 'outflow')
sel1 = [];
sel2 = strmatch(cfg.refchannel, data.labelcmb(:,1), 'exact');
elseif strcmp(cfg.matrixside, 'inflow')
sel1 = strmatch(cfg.refchannel, data.labelcmb(:,2), 'exact');
sel2 = [];
end
fprintf('selected %d channels for %s\n', length(sel1)+length(sel2), cfg.zparam);
data.(cfg.zparam) = data.(cfg.zparam)([sel1;sel2],:,:);
data.label = [data.labelcmb(sel1,1);data.labelcmb(sel2,2)];
data.labelcmb = data.labelcmb([sel1;sel2],:);
data = rmfield(data, 'labelcmb');
else
% General case
sel = match_str(data.label, cfg.refchannel);
siz = [size(data.(cfg.zparam)) 1];
if strcmp(cfg.matrixside, 'inflow') || isempty(cfg.matrixside)
%the interpretation of 'inflow' and 'outflow' depend on
%the definition in the bivariate representation of the data
%in FieldTrip the row index 'causes' the column index channel
%data.(cfg.zparam) = reshape(mean(data.(cfg.zparam)(:,sel,:),2),[siz(1) 1 siz(3:end)]);
sel1 = 1:siz(1);
sel2 = sel;
meandir = 2;
elseif strcmp(cfg.matrixside, 'outflow')
%data.(cfg.zparam) = reshape(mean(data.(cfg.zparam)(sel,:,:),1),[siz(1) 1 siz(3:end)]);
sel1 = sel;
sel2 = 1:siz(1);
meandir = 1;
elseif strcmp(cfg.matrixside, 'ff-fd')
error('cfg.matrixside = ''ff-fd'' is not supported anymore, you have to manually subtract the two before the call to ft_topoplotER');
elseif strcmp(cfg.matrixside, 'fd-ff')
error('cfg.matrixside = ''fd-ff'' is not supported anymore, you have to manually subtract the two before the call to ft_topoplotER');
end %if matrixside
end %if ~isfull
end %handle the bivariate data
% Get physical x-axis range:
if strcmp(cfg.xlim,'maxmin')
xmin = min(data.(cfg.xparam));
xmax = max(data.(cfg.xparam));
else
xmin = cfg.xlim(1);
xmax = cfg.xlim(2);
end
% Replace value with the index of the nearest bin
if ~isempty(cfg.xparam)
xmin = nearest(data.(cfg.xparam), xmin);
xmax = nearest(data.(cfg.xparam), xmax);
end
% Get physical y-axis range:
if strcmp(cfg.ylim,'maxmin')
ymin = min(data.(cfg.yparam));
ymax = max(data.(cfg.yparam));
else
ymin = cfg.ylim(1);
ymax = cfg.ylim(2);
end
% Replace value with the index of the nearest bin
if ~isempty(cfg.yparam)
ymin = nearest(data.(cfg.yparam), ymin);
ymax = nearest(data.(cfg.yparam), ymax);
end
% test if X and Y are linearly spaced (to within 10^-12): % FROM UIMAGE
x = data.(cfg.xparam)(xmin:xmax);
y = data.(cfg.yparam)(ymin:ymax);
dx = min(diff(x)); % smallest interval for X
dy = min(diff(y)); % smallest interval for Y
evenx = all(abs(diff(x)/dx-1)<1e-12); % true if X is linearly spaced
eveny = all(abs(diff(y)/dy-1)<1e-12); % true if Y is linearly spaced
if ~evenx || ~eveny
warning('(one of the) axis is/are not evenly spaced, but plots are made as if axis are linear')
end
% Take subselection of channels, this only works
% in the interactive mode
if exist('selchannel', 'var')
sellab = match_str(data.label, selchannel);
label = data.label(sellab);
else
sellab = 1:numel(data.label);
label = data.label;
end
dat = data.(cfg.zparam);
if isfull
dat = dat(sel1, sel2, ymin:ymax, xmin:xmax);
dat = nanmean(dat, meandir);
siz = size(dat);
dat = reshape(dat, [max(siz(1:2)) siz(3) siz(4)]);
dat = dat(sellab, :, :);
elseif haslabelcmb
dat = dat(sellab, ymin:ymax, xmin:xmax);
else
dat = dat(sellab, ymin:ymax, xmin:xmax);
end
if ~isempty(cfg.maskparameter)
mask = data.(cfg.maskparameter);
if isfull && cfg.maskalpha == 1
mask = mask(sel1, sel2, ymin:ymax, xmin:xmax);
mask = nanmean(nanmean(nanmean(mask, meandir), 4), 3);
elseif haslabelcmb && cfg.maskalpha == 1
mask = mask(sellab, ymin:ymax, xmin:xmax);
mask = nanmean(nanmean(mask, 3), 2);
elseif cfg.maskalpha == 1
mask = mask(sellab, ymin:ymax, xmin:xmax);
mask = nanmean(nanmean(mask, 3), 2);
elseif isfull && cfg.maskalpha ~= 1
maskl = mask(sel1, sel2, ymin:ymax, xmin:xmax); %% check this for full representation
mask = zeros(size(maskl));
mask(maskl) = 1;
mask(~maskl) = cfg.maskalpha;
elseif haslabelcmb && cfg.maskalpha ~= 1
maskl = mask(sellab, ymin:ymax, xmin:xmax);
mask = zeros(size(maskl));
mask(maskl) = 1;
mask(~maskl) = cfg.maskalpha;
elseif cfg.maskalpha ~= 1
maskl = mask(sellab, ymin:ymax, xmin:xmax);
mask = zeros(size(maskl));
mask(maskl) = 1;
mask(~maskl) = cfg.maskalpha;
end
end
% Select the channels in the data that match with the layout:
[seldat, sellay] = match_str(label, lay.label);
if isempty(seldat)
error('labels in data and labels in layout do not match');
end
% if magnetometer/gradiometer scaling is requested, get indices for
% channels
if (cfg.magscale ~= 1)
magInd = match_str(label, ft_channelselection('MEGMAG', label));
end
if (cfg.gradscale ~= 1)
gradInd = match_str(label, ft_channelselection('MEGGRAD', label));
end
datavector = dat(seldat,:,:);
if ~isempty(cfg.maskparameter)
maskvector = mask(seldat,:,:);
end
% Select x and y coordinates and labels of the channels in the data
chanX = lay.pos(sellay, 1);
chanY = lay.pos(sellay, 2);
chanWidth = lay.width(sellay);
chanHeight = lay.height(sellay);
chanLabels = lay.label(sellay);
% Get physical z-axis range (color axis):
if strcmp(cfg.zlim,'maxmin')
zmin = min(datavector(:));
zmax = max(datavector(:));
elseif strcmp(cfg.zlim,'maxabs')
zmin = -max(abs(datavector(:)));
zmax = max(abs(datavector(:)));
else
zmin = cfg.zlim(1);
zmax = cfg.zlim(2);
end
hold on;
if isfield(lay, 'outline') && strcmp(cfg.showoutline, 'yes')
for i=1:length(lay.outline)
if ~isempty(lay.outline{i})
tmpX = lay.outline{i}(:,1);
tmpY = lay.outline{i}(:,2);
h = line(tmpX, tmpY);
set(h, 'color', 'k');
set(h, 'linewidth', 2);
end
end
end
% set colormap
if isfield(cfg,'colormap')
if size(cfg.colormap,2)~=3, error('multiplotTFR(): Colormap must be a n x 3 matrix'); end
set(gcf,'colormap',cfg.colormap);
end;
% Plot channels:
for k=1:length(seldat)
% Get cdata:
cdata = squeeze(datavector(k,:,:));
if ~isempty(cfg.maskparameter)
mdata = squeeze(maskvector(k,:,:));
end
% scale if needed
if (cfg.magscale ~= 1 && any(magInd == seldat(k)))
cdata = cdata .* cfg.magscale;
end
if (cfg.gradscale ~= 1 && any(gradInd == seldat(k)))
cdata = cdata .* cfg.gradscale;
end
% Get axes for this panel
xas = (chanX(k) + linspace(0,1,size(cdata,2))*chanWidth(k)) - chanWidth(k)/2;
yas = (chanY(k) + linspace(0,1,size(cdata,1))*chanHeight(k)) - chanHeight(k)/2;
% Draw plot (and mask Nan's with maskfield if requested)
if isequal(cfg.masknans,'yes') && isempty(cfg.maskparameter)
nans_mask = ~isnan(cdata);
mask = double(nans_mask);
patch([min(xas) min(xas) max(xas) max(xas)],[min(yas) max(yas) max(yas) min(yas)],'k');
ft_plot_matrix(xas, yas, cdata,'clim',[zmin zmax],'tag','cip','highlightstyle',cfg.maskstyle,'highlight', mask)
elseif isequal(cfg.masknans,'yes') && ~isempty(cfg.maskparameter)
nans_mask = ~isnan(cdata);
mask = nans_mask .* mdata;
mask = double(mask);
patch([min(xas) min(xas) max(xas) max(xas)],[min(yas) max(yas) max(yas) min(yas)],'k');
ft_plot_matrix(xas, yas, cdata,'clim',[zmin zmax],'tag','cip','highlightstyle',cfg.maskstyle,'highlight', mask)
elseif isequal(cfg.masknans,'no') && ~isempty(cfg.maskparameter)
mask = mdata;
mask = double(mask);
patch([min(xas) min(xas) max(xas) max(xas)],[min(yas) max(yas) max(yas) min(yas)],'k');
ft_plot_matrix(xas, yas, cdata,'clim',[zmin zmax],'tag','cip','highlightstyle',cfg.maskstyle,'highlight', mask)
else
ft_plot_matrix(xas, yas, cdata,'clim',[zmin zmax],'tag','cip')
end
% Currently the handle isn't being used below, this is here for possible use in the future
h = findobj('tag','cip');
% Draw box around plot
if strcmp(cfg.box,'yes')
xstep = xas(2) - xas(1); ystep = yas(2) - yas(1);
xvalmin(1:length(yas)+2) = min(xas)-(0.5*xstep); xvalmax(1:length(yas)+2) = max(xas)+(0.5*xstep); yvalmin(1:length(xas)+2) = min(yas)-(0.5*ystep); yvalmax(1:length(xas)+2) = max(yas)+(0.5*ystep);
xas2 = [xvalmin(1) xas xvalmax(1)]; yas2 = [yvalmin(1) yas yvalmax(1)];
ft_plot_box([min(xas2) max(xas2) min(yas2) max(yas2)])
end
% Draw channel labels:
if strcmp(cfg.showlabels,'yes')
ft_plot_text(chanX(k)-chanWidth(k)/2, chanY(k)+chanHeight(k)/2, sprintf(' %0s\n ', chanLabels{k}), 'Fontsize', cfg.fontsize);
end
end
% write comment:
k = cellstrmatch('COMNT',lay.label);
if ~isempty(k)
comment = cfg.comment;
comment = sprintf('%0s\nxlim=[%.3g %.3g]', comment, data.(cfg.xparam)(xmin), data.(cfg.xparam)(xmax));
comment = sprintf('%0s\nylim=[%.3g %.3g]', comment, data.(cfg.yparam)(ymin), data.(cfg.yparam)(ymax));
comment = sprintf('%0s\nzlim=[%.3g %.3g]', comment, zmin, zmax);
ft_plot_text(lay.pos(k,1), lay.pos(k,2), sprintf(comment), 'Fontsize', cfg.fontsize);
end
% plot scale:
k = cellstrmatch('SCALE',lay.label);
if ~isempty(k)
% Get average cdata across channels:
cdata = squeeze(mean(datavector, 1));
% Get axes for this panel:
xas = (lay.pos(k,1) + linspace(0,1,size(cdata,2))*lay.width(k));
yas = (lay.pos(k,2) + linspace(0,1,size(cdata,1))*lay.height(k));
% Draw plot (and mask Nan's with maskfield if requested)
if isequal(cfg.masknans,'yes') && isempty(cfg.maskparameter)
mask = ~isnan(cdata);
mask = double(mask);
ft_plot_matrix(xas, yas, cdata,'clim',[zmin zmax],'tag','cip','highlightstyle',cfg.maskstyle,'highlight', mask)
elseif isequal(cfg.masknans,'yes') && ~isempty(cfg.maskparameter)
mask = ~isnan(cdata);
mask = mask .* mdata;
mask = double(mask);
ft_plot_matrix(xas, yas, cdata,'clim',[zmin zmax],'tag','cip','highlightstyle',cfg.maskstyle,'highlight', mask)
elseif isequal(cfg.masknans,'no') && ~isempty(cfg.maskparameter)
mask = mdata;
mask = double(mask);
ft_plot_matrix(xas, yas, cdata,'clim',[zmin zmax],'tag','cip','highlightstyle',cfg.maskstyle,'highlight', mask)
else
ft_plot_matrix(xas, yas, cdata,'clim',[zmin zmax],'tag','cip')
end
% Currently the handle isn't being used below, this is here for possible use in the future
h = findobj('tag','cip');
end
% plot colorbar:
if isfield(cfg, 'colorbar') && (strcmp(cfg.colorbar, 'yes'))
colorbar;
end
% Set colour axis
caxis([zmin zmax]);
if strcmp('yes',cfg.hotkeys)
% Attach data and cfg to figure and attach a key listener to the figure
set(gcf, 'KeyPressFcn', {@key_sub, zmin, zmax})
end
% Make the figure interactive:
if strcmp(cfg.interactive, 'yes')
% add the channel information to the figure
info = guidata(gcf);
info.x = lay.pos(:,1);
info.y = lay.pos(:,2);
info.label = lay.label;
guidata(gcf, info);
set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_singleplotTFR, cfg, data}, 'event', 'WindowButtonUpFcn'});
set(gcf, 'WindowButtonDownFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_singleplotTFR, cfg, data}, 'event', 'WindowButtonDownFcn'});
set(gcf, 'WindowButtonMotionFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_singleplotTFR, cfg, data}, 'event', 'WindowButtonMotionFcn'});
end
axis tight
axis off
if strcmp(cfg.box, 'yes')
abc = axis;
axis(abc + [-1 +1 -1 +1]*mean(abs(abc))/10)
end
orient landscape
hold off
% Set renderer if specified
if ~isempty(cfg.renderer)
set(gcf, 'renderer', cfg.renderer)
end
% get the output cfg
cfg = ft_checkconfig(cfg, 'trackconfig', 'off', 'checksize', 'yes');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function l = cellstrmatch(str,strlist)
l = [];
for k=1:length(strlist)
if strcmp(char(str),char(strlist(k)))
l = [l k];
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION which is called by ft_select_channel in case cfg.refchannel='gui'
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function select_multiplotTFR(label, cfg, varargin)
cfg.refchannel = label;
fprintf('selected cfg.refchannel = ''%s''\n', join(',', cfg.refchannel));
p = get(gcf, 'Position');
f = figure;
set(f, 'Position', p);
ft_multiplotTFR(cfg, varargin{:});
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION which is called after selecting channels in case of cfg.interactive='yes'
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function select_singleplotTFR(label, cfg, varargin)
if ~isempty(label)
%cfg.xlim = 'maxmin';
cfg.ylim = 'maxmin';
cfg.channel = label;
fprintf('selected cfg.channel = {');
for i=1:(length(cfg.channel)-1)
fprintf('''%s'', ', cfg.channel{i});
end
fprintf('''%s''}\n', cfg.channel{end});
p = get(gcf, 'Position');
f = figure;
set(f, 'Position', p);
ft_singleplotTFR(cfg, varargin{:});
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function t = join(separator,cells)
if isempty(cells)
t = '';
return;
end
t = char(cells{1});
for i=2:length(cells)
t = [t separator char(cells{i})];
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION which handles hot keys in the current plot
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function key_sub(handle, eventdata, varargin)
incr = (max(caxis)-min(caxis)) /10;
% symmetrically scale color bar down by 10 percent
if strcmp(eventdata.Key,'uparrow')
caxis([min(caxis)-incr max(caxis)+incr]);
% symmetrically scale color bar up by 10 percent
elseif strcmp(eventdata.Key,'downarrow')
caxis([min(caxis)+incr max(caxis)-incr]);
% resort to minmax of data for colorbar
elseif strcmp(eventdata.Key,'m')
caxis([varargin{1} varargin{2}]);
end
|
github
|
philippboehmsturm/antx-master
|
ft_spike_spike2data.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_spike_spike2data.m
| 7,855 |
utf_8
|
99e4f74cba1a0d29f32d4dbf155682be
|
function [spikedata] = ft_spikestation_ets2data(cfg,spike,data)
% FT_SPIKESTATION_SPIKE2DATA converts a point representation SPIKE structure to a continuous
% representation DATA structure.
% Use as:
% [data] = ft_spikestation_spike2data(cfg,spike,data)
% or
% [data] = ft_spikestation_spike2data(cfg,spike)
%
% Inputs:
%
% DATA is a standard continuous structure. DATA is an optionary input. If DATA
% is given as input, the output structure will be using the time-axis as given in DATA,
% where each spike is assigned a sample on that time-axis.
% Note that in this case, it is very important that for both DATA and SPIKE, the trial definitions
% should be synchronized, i.e., t = 0 has the same meaning, and there are equal amount of trials.
%
% Configurations options (CFG):
%
% Configuration options related to selection of spike channel and trials:
%
% cfg.fsample = number in Hz. If DATA.fsample is given as input, cfg.fsample is
% not used and set to DATA.fsample. Otherwise, the default is 1000 (hz).
% cfg.sparse = 'yes' (default) or 'no'.
%
% Outputs:
% SPIKEDATA is a continuous representation standard spikestation structure.
% If requested, SPIKEDATA.trial contains sparse matrices.
% Appending should take place with FT_APPENDDATA!
% Copyright (c), Martin Vinck (2010)
if nargin<2, error('MATLAB:ft_spike_spike2data','Minimal twoinputs required'), end
% set the defaults
try
defaults.fsample = {data.fsample};
catch
try
defaults.fsample = {cfg.fsample};
catch % user should be aware that this is not safe, so issue a warning
warning('MATLAB:ft_spike_spike2data:cfg:fsample','%s\n%s',...
'fsample can not be determined from cfg.fsample or data.fsample, setting',...
'cfg.fsample to 1000 by default')
defaults.fsample = {1000};
end
end
defaults.sparse = {'yes' 'no'};
cfg = ft_spike_sub_defaultcfg(cfg,defaults);
% check whether the data has the right structure
hasAllFields = all(isfield(spike, {'time', 'trial', 'trialtime', 'label'}));
if ~hasAllFields, error('MATLAB:ft_spike_spike2data:wrongStructInput',...
'input SPIKE should be struct with .time, .trial, .trialtime, .label fields')
end
% check whether all are of right format
correctInp = iscell(spike.time) & iscell(spike.trial) & iscell(spike.label) & size(spike.trialtime,2)==2;
if ~correctInp, error('MATLAB:ft_spike_spike2data:wrongStructInput',...
'.timestamp, .trial and .label should be cell arrays, time should be nTrials-by-2 matrix')
end
% check whether the data should be appended
doSparse = strcmp(cfg.sparse, 'yes');
% get some sizes
nUnits = length(spike.label);
nTrials = size(spike.trialtime,1);
% check whether number of trials of DATA matches that of SPIKE: it should
if nargin==3
nTrialsData = length(data.trial);
if nTrials~=nTrialsData
error('MATLAB:ft_spike_spike2data:numberOfTrials',...
'number trials SPIKE should match number trials of input DATA')
end
end
% preallocate
spikedata.trial(1:nTrials) = {[]};
spikedata.time(1:nTrials) = {[]};
for iTrial = 1:nTrials
% create the time-axis that belongs to this trial
if nargin==3
timeAx = data.time{iTrial};
else
timeAx = spike.trialtime(iTrial,1):(1/cfg.fsample):spike.trialtime(iTrial,2);
end
% convert to continuous
trialData = zeros(nUnits,length(timeAx));
for iUnit = 1:nUnits
% get the timestamps and only select those timestamps that are in the trial
ts = spike.time{iUnit};
hasTrial = spike.trial{iUnit}==iTrial;
ts = ts(hasTrial);
% get all the samples at once without using loops
sample = nearest_nd(timeAx,ts);
% because we have duplicates, simply get our vector by using histc trick
[N] = histc(sample,1:length(timeAx));
% store it in a matrix
trialData(iUnit,:) = N;
end
% put the created data in the original DATA, which is empty if doAppend==0
if doSparse, trialData = sparse(trialData); end
spikedata.trial{iTrial} = [spikedata.trial{iTrial};trialData];
spikedata.time{iTrial} = timeAx;
end
% create the associated labels and other aspects of data such as the header
spikedata.label = spike.label;
if nargin~=3
spikedata.fsample = cfg.fsample;
end
try
spikedata.hdr = spike.hdr;
catch
spikedata.hdr = struct([]);
end
% add version information to the configuration
try
% get the full name of the function
cfg.version.name = mfilename('fullpath');
catch
% required for compatibility with Matlab versions prior to release 13 (6.5)
[st, i] = dbstack;
cfg.version.name = st(i);
end
% remember the configuration details of the input data
cfg.previous = [];
try, cfg.previous = spike.cfg; end
% remember the exact configuration details in the output
spikedata.cfg = cfg;
function [indx] = nearest_nd(x,y)
% NEAREST return the index of an n-d matrix to an n-d matrix.
%
% [indx] = nearest_nd(x, y)
%
% Inputs:
% X can be a n-d matrix of any size (scalar, vector, n-d matrix).
% Y can be an n-d matrix of any size (scalar, vector, n-d matrix).
%
% If Y is larger than any X, we return the last index that the maximum value of X occurred.
% Otherwise, we return the first occurence of the nearest X.
%
% If Y contains NaNs, we return a NaN for every NaN in Y.
%
% Outputs:
% INDX is a vector of size Y and contains the indices of the values in X that are
% closest to the respective value of Y. INDX is a linear index, such that x(INDX) gives
% the nearest values of X to Y. To convert INDX to subscripts, see IND2SUB.
%
% Example:
% y = 100*rand(5,10);
% x = 1:100;
% indx = nearest_nd(x,y);
% disp(max(max(y-x(indx))))
%
% x = reshape([1:100 100*ones(1,20)],[20 6]);
% y = rand(5,10)*max(x(:));
% y(1) = 100.2;
% indx = nearest_nd(x,y);
% disp(max(max(y-x(indx))))
% Note that indx(1) returns the last occurence and indx is a linear index to 2-d X.
%
% Demonstrate the use with a 3-D x and y array.
% x = reshape([1:100],[10 5 2]);
% y = rand(5,10,2)*max(x(:));
% indx = nearest_nd(x,y);
% d = x(indx)-y; disp(max(d(:)));
% y(1) = NaN;
% indx = nearest_nd(x,y);
% disp(indx(1))
%
% Copyright, Martin Vinck, 2009.
% store the sizes of x and y, this is used to reshape INDX later on
szY = size(y);
% vectorize both x and y
x = x(:);
y = y(:);
% from now on we can treat X and Y as vectors
nY = length(y);
nX = length(x);
hasNan = isnan(y); % indices with nans in y, indx(hasNaN) will be set to NaN later.
if nX==1,
indx = ones(1,nY); % only one x value, so nearest is always only element
else
if nY==1 % in this case only one y value, so use the old NEAREST code
if y>max(x)
% return the last occurence of the nearest number
[dum, indx] = max(flipud(x));
indx = nX + 1 - indx;
else
% return the first occurence of the nearest number
[mindist, indx] = min(abs(x(:) - y));
end
else
if any(y>max(x))
% for these return the last occurence of every number as in NEAREST
indx = zeros(1,nY);
i = y>max(x);
[dum,indx] = max(flipud(x));
indx(i) = nX + 1 - indx;
% for the rest return the first occurence of every number
x = x(:);
y = y(~i)';
xRep = x(:,ones(1,length(y)));
yRep = y(ones(nX,1),:);
[mindist,indx(~i)] = min(abs(xRep-yRep));
else
x = x(:);
y = y';
xRep = x(:,ones(1,nY));
yRep = y(ones(nX,1),:);
[mindist,indx] = min(abs(xRep-yRep));
end
end
end
% return a NaN in INDX for a NaN in Y
indx(hasNan) = NaN;
% reshape the indx back to the y format
if (sum(szY>1)>1 || length(szY)>2) % in this case we are dealing with a matrix
indx = reshape(indx,[szY]);
end
|
github
|
philippboehmsturm/antx-master
|
ft_connectivityanalysis.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_connectivityanalysis.m
| 36,072 |
utf_8
|
f78d6c55b565a6fd2c80168cc398abca
|
function [stat] = ft_connectivityanalysis(cfg, data)
% FT_CONNECTIVITYANALYIS computes various measures of connectivity
% between MEG/EEG channels or between source-level signals.
%
% Use as
% stat = ft_connectivityanalysis(cfg, data)
% stat = ft_connectivityanalysis(cfg, timelock)
% stat = ft_connectivityanalysis(cfg, freq)
% stat = ft_connectivityanalysis(cfg, source)
% where the first input argument is a configuration structure (see
% below) and the second argument is the output of FT_PREPROCESSING,
% FT_TIMELOCKANLAYSIS, FT_FREQANALYSIS, FT_MVARANALYSIS,
% FT_SOURCEANALYSIS or FT_CONNECTIVITYANALYSIS depending on the
% connectivity metric that you want to compute.
%
% The configuration structure has to contain
% cfg.method = 'coh', coherence, support for freq, freqmvar and
% source data. For partial coherence also
% specify cfg.partchannel
% 'csd', cross-spectral density matrix, can also
% calculate partial csds -
% if cfg.partchannel is specified, support for freq and
% freqmvar data
% 'plv', phase-locking value, support for freq and freqmvar data
% 'powcorr', power correlation, support for freq and source data
% 'amplcorr', amplitude correlation, support for freq and source data
% 'granger', granger causality, support for freq and freqmvar data
% 'dtf', directed transfer function, support for freq and freqmvar data
% 'pdc', partial directed coherence, support for freq and freqmvar data
% 'psi', phaseslope index, support for freq and freqmvar data
% 'wpli', weighted phase lag index (signed one,
% still have to take absolute value to get indication of
% strength of interaction. Note: measure has
% positive bias. Use wpli_debiased to avoid
% this.
% 'wpli_debiased' debiased weighted phase lag index
% (estimates squared wpli)
% 'ppc' pairwise phase consistency
% 'wppc' weighted pairwise phase consistency
%
% The following methods can be used on channel-level data which already contains
% a connectivity measure (i.e. with dimord 'chan_chan_XXX'). These methods are
% implemented using the brain connectivity toolbox developed by Olaf Sporns and
% colleagues: www.brain-connectivity-toolbox.net.
%
% 'clustering_coef' clustering coefficient.
% 'degrees'
%
%
% To facilitate data-handling and distributed computing with the peer-to-peer
% module, this function has the following options:
% cfg.inputfile = ...
% cfg.outputfile = ...
% If you specify one of these (or both) the input data will be read from a *.mat
% file on disk and/or the output data will be written to a *.mat file. These mat
% files should contain only a single variable, corresponding with the
% input/output structure.
%
% Methods to be implemented
%
% 'xcorr', cross correlation function
% 'di', directionality index
% 'spearman' spearman's rank correlation
% 'corr' pearson correlation
%
% Copyright (C) 2009, Jan-Mathijs Schoffelen, Andre Bastos, Martin Vinck, Robert Oostenveld
% Copyright (C) 2010-2011, Jan-Mathijs Schoffelen, Martin Vinck
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_connectivityanalysis.m 3875 2011-07-20 06:31:44Z jansch $
%ft_defaults
% record start time and total processing time
ftFuncTimer = tic();
ftFuncClock = clock();
% check if the input cfg is valid for this function
cfg = ft_checkconfig(cfg, 'trackconfig', 'on');
% set the defaults
%FIXME do method specific calls to ft_checkconfig
cfg.feedback = ft_getopt(cfg, 'feedback', 'none');
cfg.channel = ft_getopt(cfg, 'channel', 'all');
cfg.channelcmb = ft_getopt(cfg, 'channelcmb', {'all' 'all'});
cfg.refindx = ft_getopt(cfg, 'refindx', 'all');
cfg.trials = ft_getopt(cfg, 'trials', 'all');
cfg.complex = ft_getopt(cfg, 'complex', 'abs');
cfg.jackknife = ft_getopt(cfg, 'jackknife', 'no');
cfg.removemean = ft_getopt(cfg, 'removemean', 'yes');
cfg.partchannel = ft_getopt(cfg, 'partchannel', '');
cfg.conditional = ft_getopt(cfg, 'conditional', []);
cfg.blockindx = ft_getopt(cfg, 'blockindx', {});
cfg.inputfile = ft_getopt(cfg, 'inputfile', []);
cfg.outputfile = ft_getopt(cfg, 'outputfile', []);
cfg.parameter = ft_getopt(cfg, 'parameter', []);
% load optional given inputfile as data
hasdata = (nargin>1);
if ~isempty(cfg.inputfile)
% the input data should be read from file
if hasdata
error('cfg.inputfile should not be used in conjunction with giving input data to this function');
else
data = loadvar(cfg.inputfile, 'data');
end
end
hasjack = (isfield(data, 'method') && strcmp(data.method, 'jackknife')) || (isfield(data, 'dimord') && strcmp(data.dimord(1:6), 'rptjck'));
hasrpt = (isfield(data, 'dimord') && ~isempty(strfind(data.dimord, 'rpt'))) || ...
(isfield(data, 'avg') && isfield(data.avg, 'mom')); %FIXME old-fashioned pcc data
dojack = strcmp(cfg.jackknife, 'yes');
normrpt = 0; % default, has to be overruled e.g. in plv, because of single replicate normalisation
normpow = 1; % default, has to be overruled e.g. in csd,
% select trials of interest
if ~strcmp(cfg.trials, 'all')
data = ft_selectdata(data, 'rpt', cfg.trials);
end
% select channels/channelcombination of interest and set the cfg-options accordingly
if isfield(data, 'label'),
selchan = cell(0,1);
if ~isempty(cfg.channelcmb) && ~isequal(cfg.channelcmb, {'all' 'all'}),
tmpcmb = ft_channelcombination(cfg.channelcmb, data.label);
tmpchan = unique(tmpcmb(:));
cfg.channelcmb = ft_channelcombination(cfg.channelcmb, tmpchan, 1);
selchan = [selchan;unique(cfg.channelcmb(:))];
end
cfg.channel = ft_channelselection(cfg.channel, data.label);
selchan = [selchan;cfg.channel];
if ~isempty(cfg.partchannel)
cfg.partchannel = ft_channelselection(cfg.partchannel, data.label);
selchan = [selchan; cfg.partchannel];
end
data = ft_selectdata(data, 'channel', unique(selchan));
elseif isfield(data, 'labelcmb')
cfg.channel = ft_channelselection(cfg.channel, unique(data.labelcmb(:)));
if ~isempty(cfg.partchannel)
error('partialisation is only possible without linearly indexed bivariate data');
end
if ~isempty(cfg.channelcmb),
%FIXME do something extra here
end
%FIXME call selectdata
end
% FIXME check which methods require hasrpt
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% data bookkeeping:
% ensure that the input data is appropriate for the method
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
needrpt = 1; % logical flag to specify whether (pseudo)-repetitions are required in the lower level
% connectivity function (can be singleton)
switch cfg.method
case {'coh' 'csd'}
if ~isempty(cfg.partchannel)
if hasrpt && ~hasjack,
warning('partialisation on single trial observations is not supported, removing trial dimension');
try
data = ft_checkdata(data, 'datatype', {'freqmvar' 'freq'}, 'cmbrepresentation', 'fullfast');
inparam = 'crsspctrm';
hasrpt = 0;
catch
error('partial coherence/csd is only supported for input allowing for a all-to-all csd representation');
end
else
try
data = ft_checkdata(data, 'datatype', {'freqmvar' 'freq'}, 'cmbrepresentation', 'full');
inparam = 'crsspctrm';
catch
error('partial coherence/csd is only supported for input allowing for a all-to-all csd representation');
end
end
else
data = ft_checkdata(data, 'datatype', {'freqmvar' 'freq' 'source'});
inparam = 'crsspctrm';
end
if strcmp(cfg.method, 'csd'),
normpow = 0;
end
dtype = ft_datatype(data);
switch dtype
case 'source'
if isempty(cfg.refindx), error('indices of reference voxels need to be specified'); end
% if numel(cfg.refindx)>1, error('more than one reference voxel is not yet supported'); end
otherwise
end
% FIXME think of accommodating partial coherence for source data with only a few references
case {'wpli'}
data = ft_checkdata(data, 'datatype', {'freqmvar' 'freq'});
inparam = 'crsspctrm';
debiaswpli = 0;
if hasjack, error('to compute wpli, data should be in rpt format'); end
case {'wpli_debiased'}
data = ft_checkdata(data, 'datatype', {'freqmvar' 'freq'});
inparam = 'crsspctrm';
debiaswpli = 1;
if hasjack, error('to compute wpli, data should be in rpt format'); end
case {'ppc'}
data = ft_checkdata(data, 'datatype', {'freqmvar' 'freq'});
inparam = 'crsspctrm';
weightppc = 0;
if hasjack, error('to compute ppc, data should be in rpt format'); end
case {'wppc'}
data = ft_checkdata(data, 'datatype', {'freqmvar' 'freq'});
inparam = 'crsspctrm';
weightppc = 1;
if hasjack, error('to compute wppc, data should be in rpt format'); end
case {'plv'}
data = ft_checkdata(data, 'datatype', {'freqmvar' 'freq'});
inparam = 'crsspctrm';
normrpt = 1;
case {'corr' 'xcorr'}
data = ft_checkdata(data, 'datatype', 'raw');
case {'amplcorr' 'powcorr'}
data = ft_checkdata(data, 'datatype', {'freqmvar' 'freq' 'source'});
dtype = ft_datatype(data);
switch dtype
case {'freq' 'freqmvar'}
inparam = 'powcovspctrm';
case 'source'
inparam = 'powcov';
if isempty(cfg.refindx), error('indices of reference voxels need to be specified'); end
% if numel(cfg.refindx)>1, error('more than one reference voxel is not yet supported'); end
otherwise
end
case {'granger'}
data = ft_checkdata(data, 'datatype', {'mvar' 'freqmvar' 'freq'});
inparam = {'transfer', 'noisecov', 'crsspctrm'};
% FIXME could also work with time domain data
case {'instantaneous_causality'}
data = ft_checkdata(data, 'datatype', {'mvar' 'freqmvar' 'freq'});
inparam = {'transfer', 'noisecov', 'crsspctrm'};
case {'total_interdependence'}
data = ft_checkdata(data, 'datatype', {'freqmvar' 'freq'});
inparam = 'crsspctrm';
case {'dtf' 'pdc'}
data = ft_checkdata(data, 'datatype', {'freqmvar' 'freq'});
inparam = 'transfer';
case {'psi'}
if ~isfield(cfg, 'normalize'), cfg.normalize = 'no'; end
data = ft_checkdata(data, 'datatype', {'freqmvar' 'freq'});
inparam = 'crsspctrm';
case {'di'}
%wat eigenlijk?
case {'clustering_coef' 'degrees'}
ft_hastoolbox('BCT', 1);
if ~strcmp(data.dimord(1:9), 'chan_chan'),
error('the dimord of the input data should start with ''chan_chan''');
end
if isempty(cfg.parameter)
error('when using functions from the brain connectivity toolbox you should give a parameter for which the metric is to be computed');
else
inparam = cfg.parameter;
end
needrpt = 0;
otherwise
error('unknown method %s', cfg.method);
end
dtype = ft_datatype(data);
% ensure that source data is in 'new' representation
if strcmp(dtype, 'source'),
data = ft_checkdata(data, 'sourcerepresentation', 'new');
end
% FIXME throw an error if cfg.complex~='abs', and dojack==1
% FIXME throw an error if no replicates and cfg.method='plv'
% FIXME trial selection has to be implemented still
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% data bookkeeping:
% check whether the required inparam is present in the data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if any(~isfield(data, inparam)) || (isfield(data, 'crsspctrm') && (ischar(inparam) && strcmp(inparam, 'crsspctrm'))),
if iscell(inparam)
% in the case of multiple inparams, use the first one to check the
% input data (e.g. checking for 'transfer' for requested granger)
inparam = inparam{1};
end
switch dtype
case {'freq' 'freqmvar'}
if strcmp(inparam, 'crsspctrm')
if isfield(data, 'fourierspctrm')
[data, powindx, hasrpt] = univariate2bivariate(data, 'fourierspctrm', 'crsspctrm', dtype, 'cmb', cfg.channelcmb, 'keeprpt', normrpt);
elseif strcmp(inparam, 'crsspctrm') && isfield(data, 'powspctrm')
% if input data is old-fashioned, i.e. contains powandcsd
[data, powindx, hasrpt] = univariate2bivariate(data, 'powandcsd', 'crsspctrm', dtype, 'cmb', cfg.channelcmb, 'keeprpt', normrpt);
elseif isfield(data, 'labelcmb')
powindx = labelcmb2indx(data.labelcmb);
else
powindx = [];
end
elseif strcmp(inparam, 'powcovspctrm')
if isfield(data, 'powspctrm'),
[data, powindx] = univariate2bivariate(data, 'powspctrm', 'powcovspctrm', dtype, 'demeanflag', strcmp(cfg.removemean,'yes'), 'cmb', cfg.channelcmb, 'sqrtflag', strcmp(cfg.method,'amplcorr'));
elseif isfield(data, 'fourierspctrm'),
[data, powindx] = univariate2bivariate(data, 'fourierspctrm', 'powcovspctrm', dtype, 'demeanflag', strcmp(cfg.removemean,'yes'), 'cmb', cfg.channelcmb, 'sqrtflag', strcmp(cfg.method,'amplcorr'));
end
elseif strcmp(inparam, 'transfer')
if isfield(data, 'fourierspctrm')
%FIXME this is fast but throws away the trial dimension, consider
%a way to keep trial information if needed, but use the fast way
%if possible
data = ft_checkdata(data, 'cmbrepresentation', 'fullfast');
hasrpt = 0;
elseif isfield(data, 'powspctrm')
data = ft_checkdata(data, 'cmbrepresentation', 'full');
end
tmpcfg = ft_checkconfig(cfg, 'createsubcfg', {'npsf'});
% check whether multiple pairwise decomposition is required (this
% can most conveniently be handled at this level
%tmpcfg.npsf = rmfield(tmpcfg.npsf, 'channelcmb');
try,tmpcfg.npsf = rmfield(tmpcfg.npsf, 'block'); end
try,tmpcfg.npsf = rmfield(tmpcfg.npsf, 'blockindx'); end
% end
optarg = ft_cfg2keyval(tmpcfg.npsf);
data = csd2transfer(data, optarg{:});
% convert the inparam back to cell array in the case of granger
if strcmp(cfg.method, 'granger')
inparam = {'transfer' 'noisecov' 'crsspctrm'};
end
end
case 'source'
if strcmp(inparam, 'crsspctrm')
[data, powindx, hasrpt] = univariate2bivariate(data, 'mom', 'crsspctrm', dtype, 'cmb', cfg.refindx, 'keeprpt', 0);
%[data, powindx, hasrpt] = univariate2bivariate(data, 'fourierspctrm', 'crsspctrm', dtype, 0, cfg.refindx, [], 1);
elseif strcmp(inparam, 'powcov')
data = ft_checkdata(data, 'sourcerepresentation', 'new', 'haspow', 'yes');
[data, powindx, hasrpt] = univariate2bivariate(data, 'pow', 'powcov', dtype, 'demeanflag', strcmp(cfg.removemean,'yes'), 'cmb', cfg.refindx, 'sqrtflag', strcmp(cfg.method,'amplcorr'), 'keeprpt', 0);
end
otherwise
end
elseif (isfield(data, 'crsspctrm') && (ischar(inparam) && strcmp(inparam, 'crsspctrm')))
% this means that there is a sparse crsspctrm in the data
else
powindx = [];
end
% do some additional work if single trial normalisation is required
% for example when plv needs to be computed
if normrpt && hasrpt,
if strcmp(inparam, 'crsspctrm'),
tmp = data.(inparam);
nrpt = size(tmp,1);
ft_progress('init', cfg.feedback, 'normalising...');
for k = 1:nrpt
ft_progress(k/nrpt, 'normalising amplitude of replicate %d from %d to 1\n', k, nrpt);
tmp(k,:,:,:,:) = tmp(k,:,:,:,:)./abs(tmp(k,:,:,:,:));
end
ft_progress('close');
data.(inparam) = tmp;
end
end
% convert the labels for the partialisation channels into indices
% do the same for the labels of the channels that should be kept
% convert the labels in the output to reflect the partialisation
if ~isempty(cfg.partchannel)
allchannel = ft_channelselection(cfg.channel, data.label);
pchanindx = match_str(allchannel,cfg.partchannel);
kchanindx = setdiff(1:numel(allchannel), pchanindx);
keepchn = allchannel(kchanindx);
cfg.pchanindx = pchanindx;
cfg.allchanindx = kchanindx;
partstr = '';
for k = 1:numel(cfg.partchannel)
partstr = [partstr,'-',cfg.partchannel{k}];
end
for k = 1:numel(keepchn)
keepchn{k} = [keepchn{k},'\',partstr(2:end)];
end
data.label = keepchn; % update labels to remove the partialed channels
% FIXME consider keeping track of which channels have been partialised
else
cfg.pchanindx = [];
cfg.allchanindx = [];
end
% check if jackknife is required
if hasrpt && dojack && hasjack,
% do nothing
elseif hasrpt && dojack && ~(exist('debiaswpli', 'var') || exist('weightppc', 'var')),
% compute leave-one-outs
data = ft_selectdata(data, 'jackknife', 'yes');
hasjack = 1;
elseif hasrpt && ~(exist('debiaswpli', 'var') || exist('weightppc', 'var'))
% create dof variable
if isfield(data, 'dof')
dof = data.dof;
elseif isfield(data, 'cumtapcnt')
dof = sum(data.cumtapcnt);
end
data = ft_selectdata(data, 'avgoverrpt', 'yes');
hasrpt = 0;
else
% nothing required
end
% ensure that the first dimension is singleton if ~hasrpt
if hasrpt
% nothing required
elseif needrpt
if ischar(inparam)
data.(inparam) = reshape(data.(inparam), [1 size(data.(inparam))]);
else
for k = 1:numel(inparam)
data.(inparam{k}) = reshape(data.(inparam{k}), [1 size(data.(inparam{k}))]);
end
end
if isfield(data, 'dimord')
data.dimord = ['rpt_',data.dimord];
else
data.([inparam,'dimord']) = ['rpt_',data.([inparam,'dimord'])];
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% compute the desired connectivity metric by
% calling the appropriate ft_connectivity_XXX
% function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
switch cfg.method
case 'coh'
% coherence (unsquared), if cfg.complex = 'imag' imaginary part of
% coherency
optarg = {'complex', cfg.complex, 'dimord', data.dimord, 'feedback', cfg.feedback, ...
'pownorm', normpow, 'hasjack', hasjack};
if ~isempty(cfg.pchanindx),
optarg = cat(2, optarg, {'pchanindx', cfg.pchanindx, 'allchanindx', cfg.allchanindx});
end
if exist('powindx', 'var'),
optarg = cat(2, optarg, {'powindx', powindx});
end
[datout, varout, nrpt] = ft_connectivity_corr(data.(inparam), optarg{:});
outparam = 'cohspctrm';
case 'csd'
% cross-spectral density (e.g. useful if partialisation is required)
optarg = {'complex', cfg.complex, 'dimord', data.dimord, 'feedback', cfg.feedback, ...
'pownorm', normpow, 'hasjack', hasjack};
if ~isempty(cfg.pchanindx),
optarg = cat(2, optarg, {'pchanindx', cfg.pchanindx, 'allchanindx', cfg.allchanindx});
end
if exist('powindx', 'var'),
optarg = cat(2, optarg, {'powindx', powindx});
end
[datout, varout, nrpt] = ft_connectivity_corr(data.(inparam), optarg{:});
outparam = 'crsspctrm';
case {'wpli' 'wpli_debiased'}
% weighted pli or debiased weighted phase lag index.
tmpcfg = [];
tmpcfg.feedback = cfg.feedback;
tmpcfg.dojack = dojack;
tmpcfg.debias = debiaswpli;
optarg = ft_cfg2keyval(tmpcfg);
[datout, varout, nrpt] = ft_connectivity_wpli(data.(inparam), optarg{:});
if debiaswpli
outparam = 'wpli_debiasedspctrm';
else
outparam = 'wplispctrm';
end
case {'wppc' 'ppc'}
% weighted pairwise phase consistency or pairwise phase consistency
tmpcfg = [];
tmpcfg.feedback = cfg.feedback;
tmpcfg.dojack = dojack;
tmpcfg.weighted = weightppc;
optarg = ft_cfg2keyval(tmpcfg);
[datout, varout, nrpt] = ft_connectivity_ppc(data.(inparam), optarg{:});
if weightppc
outparam = 'wppcspctrm';
else
outparam = 'ppcspctrm';
end
case 'plv'
% phase locking value
optarg = {'complex', cfg.complex, 'dimord', data.dimord, 'feedback', cfg.feedback, ...
'pownorm', normpow, 'hasjack', hasjack};
if ~isempty(cfg.pchanindx),
optarg = cat(2, optarg, {'pchanindx', cfg.pchanindx, 'allchanindx', cfg.allchanindx});
end
if exist('powindx', 'var'),
optarg = cat(2, optarg, {'powindx', powindx});
end
[datout, varout, nrpt] = ft_connectivity_corr(data.(inparam), optarg{:});
outparam = 'plvspctrm';
case 'corr'
% pearson's correlation coefficient
case 'xcorr'
% cross-correlation function
case 'spearman'
% spearman's rank correlation
case 'amplcorr'
% amplitude correlation
tmpcfg = [];
tmpcfg.feedback = cfg.feedback;
if isfield(data, 'dimord'),
tmpcfg.dimord = data.dimord;
else
tmpcfg.dimord = data.([inparam,'dimord']);
end
tmpcfg.complex = 'real';
tmpcfg.pownorm = 1;
tmpcfg.pchanindx = [];
tmpcfg.hasjack = hasjack;
if exist('powindx', 'var'), tmpcfg.powindx = powindx; end
optarg = ft_cfg2keyval(tmpcfg);
[datout, varout, nrpt] = ft_connectivity_corr(data.(inparam), optarg{:});
outparam = 'amplcorrspctrm';
case 'powcorr'
% power correlation
tmpcfg = [];
tmpcfg.feedback = cfg.feedback;
if isfield(data, 'dimord'),
tmpcfg.dimord = data.dimord;
else
tmpcfg.dimord = data.([inparam,'dimord']);
end
tmpcfg.complex = 'real';
tmpcfg.pownorm = 1;
tmpcfg.pchanindx = [];
tmpcfg.hasjack = hasjack;
if exist('powindx', 'var'), tmpcfg.powindx = powindx; end
optarg = ft_cfg2keyval(tmpcfg);
[datout, varout, nrpt] = ft_connectivity_corr(data.(inparam), optarg{:});
outparam = 'powcorrspctrm';
case 'granger'
% granger causality
if sum(ft_datatype(data, {'freq' 'freqmvar'})),
if isfield(data, 'labelcmb') && isempty(cfg.conditional),
% multiple pairwise non-parametric transfer functions
% linearly indexed
% The following is very slow, one may make assumptions regarding
% the order of the channels -> csd2transfer gives combinations in
% quadruplets, where the first and fourth are auto-combinations,
% and the second and third are cross-combinations
%powindx = labelcmb2indx(data.labelcmb);
powindx = zeros(size(data.labelcmb));
for k = 1:size(powindx,1)/4
ix = ((k-1)*4+1):k*4;
powindx(ix,:) = [1 1;4 1;1 4;4 4] + (k-1)*4;
end
elseif isfield(data, 'labelcmb')
% conditional (blockwise) needs linearly represented cross-spectra
for k = 1:size(cfg.conditional,1)
tmp{k,1} = cfg.conditional(k,:);
tmp{k,2} = cfg.conditional(k,[1 3]);
end
[cmbindx, n] = blockindx2cmbindx(data.labelcmb, cfg.blockindx, tmp);
powindx.cmbindx = cmbindx;
powindx.n = n;
elseif isfield(cfg, 'block') && ~isempty(cfg.block)
% blockwise granger
powindx = cfg.block;
for k = 1:2
newlabel{k,1} = cat(2,powindx{k});
end
data.label = newlabel;
else
powindx = [];
end
%fs = cfg.fsample; %FIXME do we really need this, or is this related to how
%noisecov is defined and normalised?
fs = 1;
if ~exist('powindx', 'var'), powindx = []; end
[datout, varout, nrpt] = ft_connectivity_granger(data.transfer, data.noisecov, data.crsspctrm, fs, hasjack, powindx);
outparam = 'grangerspctrm';
else
error('granger for time domain data is not yet implemented');
end
case 'instantaneous_causality'
% instantaneous ft_connectivity between the series, requires the same elements as granger
if sum(ft_datatype(data, {'freq' 'freqmvar'})),
if isfield(data, 'labelcmb'),
% multiple pairwise non-parametric transfer functions
% linearly indexed
powindx = labelcmb2indx(data.labelcmb);
elseif isfield(cfg, 'block') && ~isempty(cfg.block)
% blockwise granger
powindx = cfg.block;
for k = 1:2
newlabel{k,1} = cat(2,powindx{k});
end
data.label = newlabel;
else
% do nothing
end
%fs = cfg.fsample; %FIXME do we really need this, or is this related to how
%noisecov is defined and normalised?
if ~exist('powindx', 'var'), powindx = []; end
fs = 1;
[datout, varout, nrpt] = ft_connectivity_instantaneous(data.transfer, data.noisecov, data.crsspctrm, fs, hasjack, powindx);
outparam = 'instantspctrm';
else
error('instantaneous causality for time domain data is not yet implemented');
end
case 'total_interdependence'
%total interdependence
tmpcfg = [];
tmpcfg.complex = 'abs';
tmpcfg.feedback = cfg.feedback;
tmpcfg.dimord = data.dimord;
tmpcfg.pownorm = normpow;
tmpcfg.pchanindx = cfg.pchanindx;
tmpcfg.allchanindx = cfg.allchanindx;
tmpcfg.hasrpt = hasrpt;
tmpcfg.hasjack = hasjack;
if exist('powindx', 'var'), tmpcfg.powindx = powindx; end
optarg = ft_cfg2keyval(tmpcfg);
[datout, varout, nrpt] = ft_connectivity_toti(tmpcfg, data.(inparam), hasrpt, hasjack);
outparam = 'totispctrm';
case 'dtf'
% directed transfer function
if isfield(data, 'labelcmb'),
powindx = labelcmb2indx(data.labelcmb);
else
powindx = [];
end
tmpcfg = [];
tmpcfg.feedback = cfg.feedback;
tmpcfg.powindx = powindx;
tmpcfg.hasjack = hasjack;
optarg = ft_cfg2keyval(tmpcfg);
hasrpt = ~isempty(strfind(data.dimord, 'rpt'));
if hasrpt,
nrpt = size(data.(inparam),1);
datin = data.(inparam);
else
nrpt = 1;
datin = reshape(data.(inparam), [1 size(data.(inparam))]);
end
[datout, varout, nrpt] = ft_connectivity_dtf(datin, optarg{:});
outparam = 'dtfspctrm';
case 'pdc'
% partial directed coherence
if isfield(data, 'labelcmb'),
powindx = labelcmb2indx(data.labelcmb);
else
powindx = [];
end
tmpcfg = [];
tmpcfg.feedback = cfg.feedback;
tmpcfg.powindx = powindx;
tmpcfg.hasjack = hasjack;
optarg = ft_cfg2keyval(tmpcfg);
hasrpt = ~isempty(strfind(data.dimord, 'rpt'));
if hasrpt,
nrpt = size(data.(inparam),1);
datin = data.(inparam);
else
nrpt = 1;
datin = reshape(data.(inparam), [1 size(data.(inparam))]);
end
[datout, varout, nrpt] = ft_connectivity_pdc(datin, optarg{:});
outparam = 'pdcspctrm';
case 'psi'
% phase slope index
tmpcfg = [];
tmpcfg.feedback = cfg.feedback;
tmpcfg.dimord = data.dimord;
tmpcfg.nbin = nearest(data.freq, data.freq(1)+cfg.bandwidth)-1;
tmpcfg.normalize = cfg.normalize;
tmpcfg.hasrpt = hasrpt;
tmpcfg.hasjack = hasjack;
if exist('powindx', 'var'), tmpcfg.powindx = powindx; end
optarg = ft_cfg2keyval(tmpcfg);
[datout, varout, nrpt] = ft_connectivity_psi(data.(inparam), optarg{:});
outparam = 'psispctrm';
case 'di'
% directionality index
case {'clustering_coef' 'degrees'}
[datout, outdimord] = ft_connectivity_bct(data.(inparam), 'method', cfg.method);
varout = [];
outparam = [cfg.method,'spctrm'];
data.dimord = outdimord;
otherwise
error('unknown method %s', cfg.method);
end
%remove the auto combinations if necessary
if exist('powindx', 'var') && ~isempty(powindx),
switch dtype
case {'freq' 'freqmvar'}
if isfield(data, 'labelcmb') && ~isstruct(powindx),
keepchn = powindx(:,1) ~= powindx(:,2);
datout = datout(keepchn,:,:,:,:);
if ~isempty(varout),
varout = varout(keepchn,:,:,:,:);
end
data.labelcmb = data.labelcmb(keepchn,:);
end
case 'source'
nvox = size(unique(data.pos(:,1:3),'rows'),1);
ncmb = size(data.pos,1)/nvox-1;
remove = (powindx(:,1) == powindx(:,2)) & ((1:size(powindx,1))' > nvox*ncmb);
keepchn = ~remove;
datout = datout(keepchn,:,:,:,:);
if ~isempty(varout),
varout = varout(keepchn,:,:,:,:);
end
inside = logical(zeros(1,size(data.pos,1)));
inside(data.inside) = true;
inside = inside(keepchn);
data.inside = find(inside)';
data.outside = find(inside==0)';
data.pos = data.pos(keepchn,:);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% create the output structure
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
switch dtype
case {'freq' 'freqmvar'},
stat = [];
if isfield(data, 'label'),
stat.label = data.label;
end
if isfield(data, 'labelcmb'),
stat.labelcmb = data.labelcmb;
end
tok = tokenize(data.dimord, '_');
dimord = '';
for k = 1:numel(tok)
if isempty(strfind(tok{k}, 'rpt'))
dimord = [dimord, '_', tok{k}];
end
end
stat.dimord = dimord(2:end);
stat.(outparam) = datout;
if ~isempty(varout),
stat.([outparam,'sem']) = (varout./nrpt).^0.5;
end
case 'source'
stat = [];
stat.pos = data.pos;
stat.dim = data.dim;
stat.inside = data.inside;
stat.outside = data.outside;
stat.(outparam) = datout;
if ~isempty(varout),
stat.([outparam,'sem']) = (varout/nrpt).^0.5;
end
end
if isfield(data, 'freq'), stat.freq = data.freq; end
if isfield(data, 'frequency'), stat.frequency = data.frequency; end
if isfield(data, 'time'), stat.time = data.time; end
if isfield(data, 'grad'), stat.grad = data.grad; end
if isfield(data, 'elec'), stat.elec = data.elec; end
if exist('dof', 'var'), stat.dof = dof; end
%FIXME this needs to be implemented still
% accessing this field here is needed for the configuration tracking
% by accessing it once, it will not be removed from the output cfg
cfg.outputfile;
% get the output cfg
cfg = ft_checkconfig(cfg, 'trackconfig', 'off', 'checksize', 'yes');
% add version information to the configuration
cfg.version.name = mfilename('fullpath');
cfg.version.id = '$Id: ft_connectivityanalysis.m 3875 2011-07-20 06:31:44Z jansch $';
% add information about the Matlab version used to the configuration
cfg.version.matlab = version();
% add information about the function call to the configuration
cfg.callinfo.proctime = toc(ftFuncTimer);
cfg.callinfo.calltime = ftFuncClock;
cfg.callinfo.user = getusername();
% remember the configuration details of the input data
try cfg.previous = data.cfg; end
% remember the exact configuration details in the output
stat.cfg = cfg;
% the output data should be saved to a MATLAB file
if ~isempty(cfg.outputfile)
savevar(cfg.outputfile, 'data', stat); % use the variable name "data" in the output file
end
%-------------------------------------------------------------
function [c, v, n] = ft_connectivity_toti(cfg, input, hasrpt, hasjack)
% FIXME move functionality into ft_connectivity_granger
cfg.hasrpt = hasrpt;
cfg.hasjack = hasjack;
optarg = ft_cfg2keyval(cfg);
[c, v, n] = ft_connectivity_corr(input, optarg{:});
c = -log(1-c.^2);
v = -log(1-v.^2); %FIXME this is probably not correct
%----------------------------------------------------------------
function [instc, v, n] = ft_connectivity_instantaneous(H, Z, S, fs, hasjack,powindx)
% FIXME move functionality into ft_connectivity_granger
%Usage: causality = hz2causality(H,S,Z,fs);
%Inputs: transfer = transfer function,
% crsspctrm = 3-D spectral matrix;
% noisecov = noise covariance,
% fs = sampling rate
%Outputs: instantaneous causality spectrum between the channels.
%Total Interdependence = Granger (X->Y) + Granger (Y->X) + Instantaneous Causality
% : auto-causality spectra are set to zero
% Reference: Brovelli, et. al., PNAS 101, 9849-9854 (2004), Rajagovindan
% and Ding, PLoS One Vol. 3, 11, 1-8 (2008)
%M. Dhamala, UF, August 2006.
%FIXME speed up code and check
siz = size(H);
if numel(siz)==4,
siz(5) = 1;
end
n = siz(1);
Nc = siz(2);
outsum = zeros(siz(2:end));
outssq = zeros(siz(2:end));
if isempty(powindx)
%clear S; for k = 1:size(H,3), h = squeeze(H(:,:,k)); S(:,:,k) = h*Z*h'/fs; end;
for kk = 1:n
for ii = 1:Nc
for jj = 1:Nc
if ii ~=jj,
zc1 = reshape(Z(kk,jj,jj,:) - Z(kk,ii,jj,:).^2./Z(kk,ii,ii,:),[1 1 1 1 siz(5)]);
zc1 = repmat(zc1,[1 1 1 siz(4) 1]);
zc2 = reshape(Z(kk,ii,ii,:) - Z(kk,jj,ii,:).^2./Z(kk,jj,jj,:),[1 1 1 1 siz(5)]);
zc2 = repmat(zc2,[1 1 1 siz(4) 1]);
CTH1 = reshape(ctranspose(squeeze(H(kk,ii,jj,:,:))),1,1,1,siz(4));
CTH2 = reshape(ctranspose(squeeze(H(kk,jj,ii,:,:))),1,1,1,siz(4));
term1 = (S(kk,ii,ii,:,:) - H(kk,ii,jj,:,:).*zc1.*CTH1);
term2 = (S(kk,jj,jj,:,:) - H(kk,jj,ii,:,:).*zc2.*CTH2);
Sdet = (S(kk,ii,ii,:,:).*S(kk,jj,jj,:,:)) - (S(kk,ii,jj,:,:).*S(kk,jj,ii,:,:));
outsum(jj,ii,:) = outsum(jj,ii) + log((term1.*term2)./Sdet(kk,:,:,:));
outssq(jj,ii,:) = outssq(jj,ii) + log((term1.*term2)./Sdet(kk,:,:,:)).^2;
end
end
outsum(ii,ii,:,:) = 0;%self-granger set to zero
end
end
elseif ~iscell(powindx)
% data are linearly indexed
for k = 1:Nc
for j = 1:n
iauto1 = find(sum(powindx==powindx(k,1),2)==2);
iauto2 = find(sum(powindx==powindx(k,2),2)==2);
icross1 = k;
icross2 = find(sum(powindx==powindx(ones(Nc,1)*k,[2 1]),2)==2);
if iauto1 ~= iauto2
zc1 = Z(j,iauto1) - Z(j,icross2).^2./Z(j,iauto2);
zc1 = repmat(zc1,[1 1 siz(3)]);
zc2 = Z(j,iauto2) - Z(j,icross1).^2./Z(j,iauto1);
zc2 = repmat(zc2,[1 1 siz(3)]);
CTH1 = reshape(ctranspose(squeeze(H(j,icross2,:))),1,1,siz(3));
CTH2 = reshape(ctranspose(squeeze(H(j,icross1,:))),1,1,siz(3));
term1 = (S(j,iauto2,:) - H(j,icross2,:).*zc1.*CTH1);
term2 = (S(j,iauto1,:) - H(j,icross1,:).*zc2.*CTH2);
Sdet = (S(j,iauto2,:).*S(j,iauto1,:)) - (S(j,icross2,:).*S(j,icross1,:));
outsum(k,:) = outsum(k) + log((term1.*term2)./Sdet(j,:,:));
outssq(k,:) = outssq(k) + log((term1.*term2)./Sdet(j,:,:)).^2;
end
end
end
end
instc = outsum./n;
if n>1,
if hasjack
bias = (n-1).^2;
else
bias = 1;
end
v = bias*(outssq - (outsum.^2)./n)./(n - 1);
else
v = [];
end
|
github
|
philippboehmsturm/antx-master
|
ft_spiketriggeredspectrum.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_spiketriggeredspectrum.m
| 10,372 |
utf_8
|
265b67d97bf3022ba71efd52ec02f999
|
function [freq] = ft_spiketriggeredspectrum(cfg, data)
% FT_SPIKETRIGGEREDSPECTRUM computes the Fourier spectrup of the LFP around the spikes.
%
% Use as
% [freq] = ft_spiketriggeredspectrum(cfg, data)
%
% The input data should be organised in a structure as obtained from
% the FT_APPENDSPIKE function. The configuration should be according to
%
% cfg.timwin = [begin end], time around each spike (default = [-0.1 0.1])
% cfg.foilim = [begin end], frequency band of interest (default = [0 150])
% cfg.taper = 'dpss', 'hanning' or many others, see WINDOW (default = 'hanning')
% cfg.tapsmofrq = number, the amount of spectral smoothing through
% multi-tapering. Note that 4 Hz smoothing means
% plus-minus 4 Hz, i.e. a 8 Hz smoothing box.
% Note: multitapering rotates phases (no problem for consistency)
% cfg.spikechannel = string, name of single spike channel to trigger on
% cfg.channel = Nx1 cell-array with selection of channels (default = 'all'),
% see FT_CHANNELSELECTION for details
% cfg.feedback = 'no', 'text', 'textbar', 'gui' (default = 'no')
%
% If the triggered spike leads a spike in another channel, then the angle
% of the Fourier spectrum of that other channel will be negative. NOTE that
% this should be checked for consistency.
%
% NOTE: Function should be merged with ft_spike_triggeredspectrum
%
% Copyright (C) 2008, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_spiketriggeredspectrum.m 3710 2011-06-16 14:04:19Z eelspa $
% This function uses a NaN-aware spectral estimation technique, which will
% default to the standard Matlab FFT routine if no NaNs are present. The
% fft_along_rows subfunction below demonstrates the expected function
% behaviour.
ft_defaults
% record start time and total processing time
ftFuncTimer = tic();
ftFuncClock = clock();
% set the defaults
if ~isfield(cfg, 'timwin'), cfg.timwin = [-0.1 0.1]; end
if ~isfield(cfg, 'foilim'), cfg.foilim = [0 150]; end
if ~isfield(cfg, 'taper'), cfg.taper = 'hanning'; end
if ~isfield(cfg, 'channel'), cfg.channel = 'all'; end
if ~isfield(cfg, 'spikechannel'), cfg.spikechannel = []; end
if ~isfield(cfg, 'feedback'), cfg.feedback = 'no'; end
if ~isfield(cfg, 'tapsmofrq'), cfg.tapsmofrq = 4; end
if strcmp(cfg.taper, 'sine')
error('sorry, sine taper is not yet implemented');
end
% autodetect the spike channels
ntrial = length(data.trial);
nchans = length(data.label);
spikechan = zeros(nchans,1);
for i=1:ntrial
for j=1:nchans
spikechan(j) = spikechan(j) + all(data.trial{i}(j,:)==0 | data.trial{i}(j,:)==1 | data.trial{i}(j,:)==2);
end
end
spikechan = (spikechan==ntrial);
% determine the channels to be averaged
cfg.channel = ft_channelselection(cfg.channel, data.label);
chansel = match_str(data.label, cfg.channel);
nchansel = length(cfg.channel); % number of channels
% determine the spike channel on which will be triggered
cfg.spikechannel = ft_channelselection(cfg.spikechannel, data.label);
spikesel = match_str(data.label, cfg.spikechannel);
nspikesel = length(cfg.spikechannel); % number of channels
if nspikesel==0
error('no spike channel selected');
end
if nspikesel>1
error('only supported for a single spike channel');
end
if ~spikechan(spikesel)
error('the selected spike channel seems to contain continuous data');
end
begpad = round(cfg.timwin(1)*data.fsample);
endpad = round(cfg.timwin(2)*data.fsample);
numsmp = endpad - begpad + 1;
if ~strcmp(cfg.taper,'dpss')
taper = window(cfg.taper, numsmp);
taper = taper./norm(taper);
else
% not implemented yet: keep tapers, or selecting only a subset of them.
taper = dpss(numsmp, cfg.tapsmofrq);
taper = taper(:,1:end-1); % we get 2*NW-1 tapers
taper = sum(taper,2)./size(taper,2); % using the linearity of multitapering
end
taper = sparse(diag(taper));
spectrum = cell(1,ntrial);
spiketime = cell(1,ntrial);
spiketrial = cell(1,ntrial);
cumsum = zeros(nchansel, numsmp);
cumcnt = 0;
timeaxis = linspace(cfg.timwin(1),cfg.timwin(2), numsmp);
freqaxis = linspace(0, data.fsample, numsmp);
fbeg = nearest(freqaxis, cfg.foilim(1));
fend = nearest(freqaxis, cfg.foilim(2));
% update the configuration to acocunt for rounding off differences
cfg.foilim(1) = freqaxis(fbeg);
cfg.foilim(2) = freqaxis(fend);
% make a representation of the spike, this is used for the phase rotation
spike = zeros(1,numsmp);
time = randn(1,numsmp); % this is actually not used
spike(1-begpad) = 1;
spike_fft = specest_nanfft(spike, time);
spike_fft = spike_fft(fbeg:fend);
spike_fft = spike_fft./abs(spike_fft);
rephase = sparse(diag(conj(spike_fft)));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% compute the spectra
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for i=1:ntrial
spikesmp = find(data.trial{i}(spikesel,:));
spikecnt = data.trial{i}(spikesel,spikesmp);
if any(spikecnt>5) || any(spikecnt<0)
error('the spike count lies out of the regular bounds');
end
% instead of doing the bookkeeping of double spikes below, replicate the double spikes by looking at spikecnt
sel = find(spikecnt>1);
tmp = zeros(1,sum(spikecnt(sel)));
n = 1;
for j=1:length(sel)
for k=1:spikecnt(sel(j))
tmp(n) = spikesmp(sel(j));
n = n + 1;
end
end
spikesmp(sel) = []; % remove the double spikes
spikecnt(sel) = []; % remove the double spikes
spikesmp = [spikesmp tmp]; % add the double spikes as replicated single spikes
spikecnt = [spikecnt ones(size(tmp))]; % add the double spikes as replicated single spikes
spikesmp = sort(spikesmp); % sort them to keep the original ordering (not needed on spikecnt, since that is all ones)
spiketime{i} = data.time{i}(spikesmp);
spiketrial{i} = i*ones(size(spikesmp));
fprintf('processing trial %d of %d (%d spikes)\n', i, ntrial, sum(spikecnt));
spectrum{i} = zeros(length(spikesmp), nchansel, fend-fbeg+1);
ft_progress('init', cfg.feedback, 'spectrally decomposing data around spikes');
for j=1:length(spikesmp)
ft_progress(i/ntrial, 'spectrally decomposing data around spike %d of %d\n', j, length(spikesmp));
begsmp = spikesmp(j) + begpad;
endsmp = spikesmp(j) + endpad;
if (begsmp<1)
segment = nan*zeros(nchansel, numsmp);
elseif endsmp>size(data.trial{i},2)
segment = nan*zeros(nchansel, numsmp);
else
segment = data.trial{i}(chansel,begsmp:endsmp);
end
% substract the DC component from every segment, to avoid any leakage of the taper
segmentMean = repmat(nanmean(segment,2),1,numsmp); % nChan x Numsmp
segment = segment - segmentMean; % LFP has average of zero now (no DC)
time = randn(size(segment)); % this is actually not used
% taper the data segment around the spike and compute the fft
segment_fft = specest_nanfft(segment * taper, time);
% select the desired output frquencies and normalize
segment_fft = segment_fft(:,fbeg:fend) ./ sqrt(numsmp/2);
% rotate the estimated phase at each frequency to correct for the segment t=0 not being at the first sample
segment_fft = segment_fft * rephase;
% store the result for this spike in this trial
spectrum{i}(j,:,:) = segment_fft;
end % for each spike in this trial
ft_progress('close');
end % for each trial
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% collect the results
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
freq.label = data.label(chansel);
freq.freq = freqaxis(fbeg:fend);
freq.dimord = 'rpt_chan_freq';
freq.fourierspctrm = cat(1, spectrum{:});
freq.origtime = cat(2,spiketime{:})'; % this deviates from the standard output, but is included for reference
freq.origtrial = cat(2,spiketrial{:})'; % this deviates from the standard output, but is included for reference
% select all trials that do not contain data in the first sample
sel = isnan(freq.fourierspctrm(:,1,1));
fprintf('removing %d trials from the output that do not contain data\n', sum(sel));
% remove the selected trials from the output
freq.fourierspctrm = freq.fourierspctrm(~sel,:,:);
freq.origtime = freq.origtime(~sel);
freq.origtrial = freq.origtrial(~sel);
% add version information to the configuration
cfg.version.name = mfilename('fullpath');
cfg.version.id = '$Id: ft_spiketriggeredspectrum.m 3710 2011-06-16 14:04:19Z eelspa $';
% add information about the Matlab version used to the configuration
cfg.callinfo.matlab = version();
% add information about the function call to the configuration
cfg.callinfo.proctime = toc(ftFuncTimer);
cfg.callinfo.calltime = ftFuncClock;
cfg.callinfo.user = getusername();
% remember the configuration details of the input data
try, cfg.previous = data.cfg; end
% remember the exact configuration details in the output
freq.cfg = cfg;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION for demonstration purpose
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function y = fft_along_rows(x)
y = fft(x, [], 2); % use normal Matlab function to compute the fft along 2nd dimension
|
github
|
philippboehmsturm/antx-master
|
ft_conjunctionanalysis.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_conjunctionanalysis.m
| 9,072 |
utf_8
|
58afcd8bb20e28e073829a3e2c688a99
|
function [Cval] = ft_conjunctionanalysis(cfg, varargin)
% FT_CONJUNCTIONANALYSIS finds minimalistic (maximum common) T values,
% clusters and probabilities in the input contrasts (n>=2).
% Furthermore, the output mask structure shows the overlap of sensors/voxels
% that are significantly different (logical AND).
%
% Alternatively, it finds minimalistic mean power values in the input datasets.
% Here, a type 'relative change' baselinecorrection prior to conjunction is advised.
%
% Use as:
% [stat] = ft_conjunctionanalysis(cfg, data1, data2, .., dataN)
%
% where data comes from
% - ft_sourcestatistics post ft_sourceanalysis
% with or without ft_sourceinterpolate
% - ft_freqstatistics post ft_freqanalysis
% - ft_sourceanalysis
% - ft_freqanalysis
%
% No configuration options are yet implemented.
%
% Copyright (C) 2010-2011, Arjen Stolk
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
ft_defaults
% record start time and total processing time
ftFuncTimer = tic();
ftFuncClock = clock();
% input check
if nargin < 3
error('not enough input arguments; there should be at least two');
elseif nargin >= 3
ndatasets = nargin - 1;
fprintf('performing conjunction analysis on %s input datasets \n', num2str(ndatasets));
Cval = [];
end
% output check
voxflag = 0;
sensflag = 0;
% conjunction loop, in case ndatasets > 2
for i = 1:ndatasets-1
% align input arguments for conjunction
if isempty(Cval)
data1 = varargin{i};
data2 = varargin{i+1};
else
data1 = Cval; % use already conjunct output
data2 = varargin{i+1};
end
%% SOURCE DATA
if isfield(data1, 'inside') % check
voxflag = 1;
if isfield(data1, 'stat') % conjunction on t-values
fprintf('minimum statistics on voxel T values \n');
% equal size input check
if ~isequal(size(data1.stat), size(data2.stat))
error('the input arguments have different sizes');
end
Cval = data1;
Cval.stat = minimumstatistics(data1.stat, data2.stat);
if isfield(data1, 'posclusterslabelmat') % conjunction on cluster values
fprintf('minimum statistics on positive clusters \n');
Cval.posclusterslabelmat = minimumstatistics(data1.posclusterslabelmat, data2.posclusterslabelmat);
end
if isfield(data1, 'negclusterslabelmat') % conjunction on cluster values
fprintf('minimum statistics on negative clusters \n');
Cval.negclusterslabelmat = minimumstatistics(data1.negclusterslabelmat, data2.negclusterslabelmat);
end
if isfield(data1, 'prob') % conjunction on probabilities
fprintf('minimum statistics on probabilities \n');
Cval.prob = maximumprobabilities(data1.prob, data2.prob);
end
if isfield(data1, 'mask') % conjunction on mask parameters
fprintf('logical AND on masking parameters \n');
Cval.mask = logicalAND(data1.mask, data2.mask);
end
elseif isfield(data1, 'avg') % conjunction on mean power values
fprintf('minimum statistics on mean voxel power \n');
% equal size input check
if ~isequal(size(data1.avg.pow), size(data2.avg.pow))
error('the input arguments have different sizes');
end
Cval = data1;
Cval.avg.pow = minimumstatistics(data1.avg.pow, data2.avg.pow);
elseif isfield(data1, 'trial')
fprintf('please first compute the averages with ft_sourcedescriptives \n');
else
fprintf('this source level data does not fit conjunction analysis \n');
end
end % end of source level conjunction
%% SENSOR DATA
if isfield(data1, 'dimord') && ...
(strcmp(data1.dimord, 'chan_freq') || ...
strcmp(data1.dimord, 'chan_freq_time') || ...
strcmp(data1.dimord, 'subj_chan_freq') || ...
strcmp(data1.dimord, 'subj_chan_freq_time') || ...
strcmp(data1.dimord, 'rpt_chan_freq') || ...
strcmp(data1.dimord, 'rpt_chan_freq_time')); % check
sensflag = 1;
if isfield(data1, 'stat') % conjunction on t-values
fprintf('minimum statistics on sensor T values \n');
% equal size input check
if ~isequal(size(data1.stat), size(data2.stat))
error('the input arguments have different sizes');
end
Cval = data1;
Cval.stat = minimumstatistics(data1.stat, data2.stat);
if isfield(data1, 'posclusterslabelmat') % conjunction on cluster values
fprintf('minimum statistics on positive clusters \n');
Cval.posclusterslabelmat = minimumstatistics(data1.posclusterslabelmat, data2.posclusterslabelmat);
end
if isfield(data1, 'negclusterslabelmat') % conjunction on cluster values
fprintf('minimum statistics on negative clusters \n');
Cval.negclusterslabelmat = minimumstatistics(data1.negclusterslabelmat, data2.negclusterslabelmat);
end
if isfield(data1, 'prob') % conjunction on probabilities
fprintf('minimum statistics on probabilities \n');
Cval.prob = maximumprobabilities(data1.prob, data2.prob);
end
if isfield(data1, 'mask') % conjunction on mask parameters
fprintf('logical AND on masking parameters \n');
Cval.mask = logicalAND(data1.mask, data2.mask);
end
elseif isfield(data1, 'powspctrm') % conjunction on mean power values
fprintf('minimum statistics on mean sensor power \n');
% equal size input check
if ~isequal(size(data1.powspctrm), size(data2.powspctrm))
error('the input arguments have different sizes');
end
Cval = data1;
Cval.powspctrm = minimumstatistics(data1.powspctrm, data2.powspctrm);
else
fprintf('this sensor level data does not fit conjunction analysis \n');
end
end % end of sensor level conjunction
clear data1; clear data2;
end % end of conjunction loop
%% UNIDENTIFIED DATA
if voxflag == 0 && sensflag == 0
fprintf('this data does not fit conjunction analysis \n');
Cval = [];
end
% add the version details of this function call to the configuration
Cval.cfg.version.name = mfilename('fullpath');
Cval.cfg.version.id = '$Id: ft_conjunctionanalysis.m 3710 2011-06-16 14:04:19Z eelspa $';
Cval.cfg.callinfo.matlab = version();
% add information about the function call to the configuration
cfg.callinfo.proctime = toc(ftFuncTimer);
cfg.callinfo.calltime = ftFuncClock;
cfg.callinfo.user = getusername(); % Matlab version used
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [minstat] = minimumstatistics(variable1, variable2)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
minAbsT = min(abs(variable1), abs(variable2)); % minimum of the absolute values
equalSign = (sign(variable1) == sign(variable2)); % 1 is signs are equal, 0 otherwise
origSign = sign(variable1); % sign(varagin2) gives same result
minstat = minAbsT.*equalSign.*origSign;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [maxprob] = maximumprobabilities(variable1, variable2)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
maxprob = max(variable1, variable2); % maximum of the probabilities
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [logic] = logicalAND(variable1, variable2)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
logic = (variable1 & variable2); % compute logical AND
|
github
|
philippboehmsturm/antx-master
|
ft_spike_plot_psth.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_spike_plot_psth.m
| 6,101 |
utf_8
|
6d81db6e1cbd9184978d301b0120b096
|
function [hdl] = ft_spike_plot_psth(cfg,psth)
% FT_SPIKE_PLOT_PSTH makes a bar plot of PSTH structure (output from FT_SPIKE_PSTH)
% with error bars.
%
% Inputs:
% PSTH typically is a structure from FT_SPIKE_PSTH.
%
% Configurations (cfg):
%
% cfg.latency = [begin end] in seconds, 'maxperiod' (default), 'prestim'(t<=0), or
% 'poststim' (t>=0).
% cfg.errorbars = 'no', 'std', 'sem' (default), 'conf95%' (requires statistic toolbox,
% according to student-T distribution), 'var'
% cfg.spikechannel = string or index of single spike channel to trigger on (default = 1)
% Only one spikechannel can be plotted at a time.
% cfg.ylim = [min max] or 'auto' (default)
% If 'standard', we plot from 0 to 110% of maximum plotted value);
% Outputs:
% HDL.avg = figure handle for the bar plot, psth average. Use SET and GET to access.
% HDL.var = figure handle for the error lines. Use GET and SET to access.
%
% Martin Vinck (C) 2010.
defaults.latency = {'maxperiod'};
defaults.errorbars = {'sem' 'std' 'conf95%', 'no' 'var'};
defaults.spikechannel = {1};
defaults.ylim = {'auto'};
cfg = ft_spike_sub_defaultcfg(cfg,defaults);% change prefix
% select the latencies
if ischar(cfg.latency)
if strcmp(cfg.latency, 'maxperiod')
cfg.latency = [min(psth.time) max(psth.time)];
elseif strcmp(cfg.latency, 'prestim')
cfg.latency = [min(psth.time) 0];
elseif strcmp(cfg.latency, 'poststim')
cfg.latency = [0 max(psth.time)];
end
elseif ~isnumeric(cfg.latency)||length(cfg.latency)~=2
error('MATLAB:ft_spike_plot_psth:cfg:latency',...
'cfg.latency should be "maxperiod", "prestim", "poststim" or 1-by-2 numerical vector');
end
if cfg.latency(1)>=cfg.latency(2), error('MATLAB:spikestation:plot_psth:incorrectLatencyWindow',...
'cfg.latency should be a vector in ascending order, i.e., cfg.latency(2)>cfg.latency(1)');
end
% check whether the time window fits with the data
if cfg.latency(1) < min(psth.time), cfg.latency(1) = min(psth.time);
warning('MATLAB:ft_spike_plot_psth:incorrectLatencyWindow',...
'Correcting begin latency of averaging window');
end
if (cfg.latency(2) > max(psth.time)), cfg.latency(2) = max(psth.time);
warning('MATLAB:ft_spike_plot_psth:incorrectLatencyWindow',...
'Correcting begin latency of averaging window');
end
% get the spikechannels
cfg.channel = ft_channelselection(cfg.spikechannel, psth.label);
spikesel = match_str(psth.label, cfg.channel);
nUnits = length(spikesel);
if nUnits~=1, error('MATLAB:ft_spike_plot_psth:cfg:spikechannel:wrongInput',...
'You selected more or less than one spikechannel by means of cfg.spikechannel');
end
% select the timepoints within the latencies
timeSel = psth.time>=cfg.latency(1) & psth.time <= cfg.latency(2);
if isempty(timeSel), error('MATLAB:ft_spike_plot_psth:cfg:latency',...
'no time points selected, please change cfg.latency or inspect input PSTH');
end
% plot the average psth
psthHdl = bar(psth.time(timeSel),psth.avg(spikesel,timeSel),'k');
set(psthHdl,'BarWidth', 1)
% check if fields .dof and .var are correct given cfg.errorbars
if ~strcmp(cfg.errorbars,'no')
if ~isfield(psth,'var') || ~any(isfinite(psth.var(spikesel,:)))
error('MATLAB:ft_spike_plot_psth:cfg:var',...
'PSTH should contain field .var that contain numbers. If you do not want the variance',...
'please specify cfg.errorbars = "no"');
end
if ~ (strcmp(cfg.errorbars,'std') || strcmp(cfg.errorbars,'var'))
if ~isfield(psth,'dof') || ~any(isfinite(psth.dof(spikesel,:)))
error('MATLAB:ft_spike_plot_psth:cfg:dof',...
'psth should contain field dof that contains numbers. Use cfg.errorbars = "no" if you do not',...
'want the variance plotted');
end
end
end
% add standard error bars to it
x = [psth.time(timeSel);psth.time(timeSel)]; % create x doublets
if strcmp(cfg.errorbars, 'sem')
err = sqrt(psth.var(spikesel,timeSel)./psth.dof(timeSel));
elseif strcmp(cfg.errorbars, 'std')
err = sqrt(psth.var(spikesel,timeSel));
elseif strcmp(cfg.errorbars, 'var')
err = psth.var(spikesel,timeSel);
elseif strcmp(cfg.errorbars, 'conf95%')
% use a try statement just in case the statistics toolbox doesn't work.
try
tCrit = tinv(0.975,psth.dof(timeSel));
err = tCrit.*sqrt(psth.var(spikesel,timeSel)./psth.dof(timeSel)); % assuming normal distribution, SHOULD BE REPLACED BY STUDENTS-T!
end
else
err = 0;
end
y = psth.avg(spikesel,timeSel) + err; % create the error values
% plot the errorbars as line plot on top of the bar plot
if ~strcmp(cfg.errorbars,'no')
hold on
y = [zeros(1,length(y));y]; % let lines run from 0 to error values
psthSemHdl = plot(x,y,'k'); % plot the error bars
end
% create labels
xlabel('bin centers (sec)')
try
ylabel(psth.cfg.outputunit)
catch
ylabel('firing activity')
end
% set the axis
if strcmp(cfg.ylim, 'auto'), cfg.ylim = [0 max(y(:))*1.1+eps]; end
if ~isnumeric(cfg.ylim)||length(cfg.ylim)~=2 || cfg.ylim(2)<=cfg.ylim(1)
error('MATLAB:spikestation:plot_psth:cfg:ylim',...
'cfg.ylim should be "auto" or ascending order 1-by-2 vector in seconds');
end
set(gca,'YLim', cfg.ylim, 'XLim', cfg.latency)
set(gca,'TickDir','out', 'Box', 'off')
% store the handles
hdl.avg = psthHdl;
if ~strcmp(cfg.errorbars,'no'), hdl.error = psthSemHdl; end
% as usual, make sure that panning and zooming does not distort the y limits
set(zoom,'ActionPostCallback',{@mypostcallback,cfg.ylim,cfg.latency});
set(pan,'ActionPostCallback',{@mypostcallback,cfg.ylim,cfg.latency});
function [] = mypostcallback(fig,evd,limY,limX)
% get the x limits and reset them
ax = evd.Axes;
xlim = get(ax(1), 'XLim');
ylim = get(ax(1), 'YLim');
if limX(1)>xlim(1), xlim(1) = limX(1); end
if limX(2)<xlim(2), xlim(2) = limX(2); end
if limY(1)>ylim(1), ylim(1) = limY(1); end
if limY(2)<ylim(2), ylim(2) = limY(2); end
set(ax(1), 'XLim',xlim)
set(ax(1), 'YLim',ylim);
|
github
|
philippboehmsturm/antx-master
|
ft_sliceinterp.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_sliceinterp.m
| 18,011 |
utf_8
|
5faba7a0b4387433ccdcfa79d195336e
|
function [outim]=ft_sliceinterp(cfg, ininterp)
% FT_SLICEINTERP plots a 2D-montage of source reconstruction and anatomical MRI
% after these have been interpolated onto the same grid.
%
% Use as
% ft_sliceinterp(cfg, interp)
% or
% [rgbimage] = ft_sliceinterp(cfg, interp), rgbimage is the monatage image
%
% where interp is the output of sourceinterpolate and cfg is a structure
% with any of the following fields:
%
% cfg.funparameter string with the functional parameter of interest (default = 'source')
% cfg.maskparameter parameter used as opacity mask (default = 'none')
% cfg.clipmin value or 'auto' (clipping of source data)
% cfg.clipmax value or 'auto' (clipping of source data)
% cfg.clipsym 'yes' or 'no' (default) symmetrical clipping
% cfg.colormap colormap for source overlay (default is jet(128))
% cfg.colmin source value mapped to the lowest color (default = 'auto')
% cfg.colmax source value mapped to the highest color (default = 'auto')
% cfg.maskclipmin value or 'auto' (clipping of mask data)
% cfg.maskclipmax value or 'auto' (clipping of mask data)
% cfg.maskclipsym 'yes' or 'no' (default) symmetrical clipping
% cfg.maskmap opacitymap for source overlay
% (default is linspace(0,1,128))
% cfg.maskcolmin mask value mapped to the lowest opacity, i.e.
% completely transparent (default ='auto')
% cfg.maskcolmin mask value mapped to the highest opacity, i.e.
% non-transparent (default = 'auto')
% cfg.alpha value between 0 and 1 or 'adaptive' (default)
% cfg.nslices integer value, default is 20
% cfg.dim integer value, default is 3 (dimension to slice)
% cfg.spacemin 'auto' (default) or integer (first slice position)
% cfg.spacemax 'auto' (default) or integer (last slice position)
% cfg.resample integer value, default is 1 (for resolution reduction)
% cfg.rotate number of ccw 90 deg slice rotations (default = 0)
% cfg.title optional title (default is '')
% cfg.whitebg 'yes' or 'no' (default = 'yes')
% cfg.flipdim flip data along the sliced dimension, 'yes' or 'no'
% (default = 'no')
% cfg.marker [Nx3] array defining N marker positions to display
% cfg.markersize radius of markers (default = 5);
% cfg.markercolor [1x3] marker color in RGB (default = [1 1 1], i.e. white)
% cfg.interactive 'yes' or 'no' (default), interactive coordinates
% and source values
%
% if cfg.alpha is set to 'adaptive' the opacity of the source overlay
% linearly follows the source value: maxima are opaque and minima are
% transparent.
%
% if cfg.spacemin and/or cfg.spacemax are set to 'auto' the sliced
% space is automatically restricted to the evaluated source-space
%
% if cfg.colmin and/or cfg.colmax are set to 'auto' the colormap is mapped
% to source values the following way: if source values are either all
% positive or all negative the colormap is mapped to from
% min(source) to max(source). If source values are negative and positive
% the colormap is symmetrical mapped around 0 from -max(abs(source)) to
% +max(abs(source)).
%
% If cfg.maskparameter specifies a parameter to be used as an opacity mask
% cfg.alpha is not used. Instead the mask values are maped to an opacitymap
% that can be specified using cfg.maskmap. The mapping onto that
% opacitymap is controlled as for the functional data using the
% corresponding clipping and min/max options.
%
% if cfg.whitebg is set to 'yes' the function estimates the head volume and
% displays a white background outside the head, which can save a lot of black
% printer toner.
%
% if cfg.interactive is set to 'yes' a button will be displayed for
% interactive data evaluation and coordinate reading. After clicking the
% button named 'coords' you can click on any position in the slice montage.
% After clicking these coordinates and their source value are displayed in
% a text box below the button. The coordinates correspond to indeces in the
% input data array:
%
% f = interp.source(coord_1,coord_2,coord_3)
%
% The coordinates are not affected by any transformations used for displaying
% the data such as cfg.dim, cfg.rotate,cfg.flipdim or cfg.resample.
% Copyright (C) 2004, Markus Siegel, [email protected]
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_sliceinterp.m 2439 2010-12-15 16:33:34Z johzum $
ft_defaults
% check if the input data is valid for this function
ininterp = ft_checkdata(ininterp, 'datatype', 'volume', 'feedback', 'yes');
if ~isfield(cfg, 'clipmin'); cfg.clipmin = 'auto'; end
if ~isfield(cfg, 'clipmax'); cfg.clipmax = 'auto'; end
if ~isfield(cfg, 'clipsym'); cfg.clipsym = 'no'; end
if ~isfield(cfg, 'alpha'); cfg.alpha = 'adaptive'; end
if ~isfield(cfg, 'nslices'); cfg.nslices = 20; end
if ~isfield(cfg, 'dim'); cfg.dim = 3; end
if ~isfield(cfg, 'colormap'); cfg.colormap = jet(128); end
if ~isfield(cfg, 'spacemin'); cfg.spacemin = 'auto'; end
if ~isfield(cfg, 'spacemax'); cfg.spacemax = 'auto'; end
if ~isfield(cfg, 'colmin'); cfg.colmin = 'auto'; end
if ~isfield(cfg, 'colmax'); cfg.colmax = 'auto'; end
if ~isfield(cfg, 'resample'); cfg.resample = 1; end
if ~isfield(cfg, 'rotate'); cfg.rotate = 0; end
if ~isfield(cfg, 'title'); cfg.title = ''; end
if ~isfield(cfg, 'whitebg'); cfg.whitebg = 'no'; end
if ~isfield(cfg, 'flipdim'); cfg.flipdim = 'no'; end
if ~isfield(cfg, 'marker'); cfg.marker = []; end
if ~isfield(cfg, 'markersize'); cfg.markersize = 5; end
if ~isfield(cfg, 'markercolor'); cfg.markercolor = [1,1,1]; end
if ~isfield(cfg, 'interactive'); cfg.interactive = 'no'; end
if ~isfield(cfg, 'maskclipmin'); cfg.maskclipmin = 'auto'; end
if ~isfield(cfg, 'maskclipmax'); cfg.maskclipmax = 'auto'; end
if ~isfield(cfg, 'maskclipsym'); cfg.maskclipsym = 'no'; end
if ~isfield(cfg, 'maskmap'); cfg.maskmap = linspace(0,1,128); end
if ~isfield(cfg, 'maskcolmin'); cfg.maskcolmin = 'auto'; end
if ~isfield(cfg, 'maskcolmax'); cfg.maskcolmax = 'auto'; end
if ~isfield(cfg, 'maskparameter');cfg.maskparameter = []; end
% perform some checks on the configuration for backward compatibility
if ~isfield(cfg, 'funparameter') && isfield(ininterp, 'source')
% if present, the default behavior should be to use this field for plotting
cfg.funparameter = 'source';
end
% make the selection of functional and mask data consistent with the data
cfg.funparameter = parameterselection(cfg.funparameter, ininterp);
cfg.maskparameter = parameterselection(cfg.maskparameter, ininterp);
% only a single parameter should be selected
try, cfg.funparameter = cfg.funparameter{1}; end
try, cfg.maskparameter = cfg.maskparameter{1}; end
% check anatomical data
if isfield(ininterp,'anatomy');
interp.anatomy = reshape(ininterp.anatomy, ininterp.dim);
else
error('no anatomical data supplied');
end
% check functional data
if ~isempty(cfg.funparameter)
interp.source = double(reshape(getsubfield(ininterp, cfg.funparameter), ininterp.dim));
else
error('no functional data supplied');
end
% check mask data
if ~isempty(cfg.maskparameter)
interp.mask = double(reshape(getsubfield(ininterp,cfg.maskparameter), ininterp.dim));
maskdat = 1;
else
fprintf('no opacity mask data supplied\n');
interp.mask = [];
maskdat = 0;
end
% only work with the copy of the relevant parameters in "interp"
clear ininterp;
% convert anatomy data type and optimize contrast
if isa(interp.anatomy, 'uint8') || isa(interp.anatomy, 'uint16')
fprintf('converting anatomy to floating point values...');
interp.anatomy = double(interp.anatomy);
fprintf('done\n');
end
fprintf('optimizing contrast of anatomical data ...');
minana = min(interp.anatomy(:));
maxana = max(interp.anatomy(:));
interp.anatomy = (interp.anatomy-minana)./(maxana-minana);
fprintf('done\n');
% store original data if 'interactive' mode
if strcmp(cfg.interactive,'yes')
data.source = interp.source;
end
% place markers
marker = zeros(size(interp.anatomy));
if ~isempty(cfg.marker)
fprintf('placing markers ...');
[x,y,z] = ndgrid([1:size(interp.anatomy,1)],[1:size(interp.anatomy,2)],[1:size(interp.anatomy,3)]);
for imarker = 1:size(cfg.marker,1)
marker(find(sqrt((x-cfg.marker(imarker,1)).^2 + (y-cfg.marker(imarker,2)).^2 + (z-cfg.marker(imarker,3)).^2)<=cfg.markersize)) = 1;
end
fprintf('done\n');
end
% shift dimensions
fprintf('sorting dimensions...');
interp.anatomy = shiftdim(interp.anatomy,cfg.dim-1);
interp.source = shiftdim(interp.source,cfg.dim-1);
interp.mask = shiftdim(interp.mask,cfg.dim-1);
marker = shiftdim(marker,cfg.dim-1);
fprintf('done\n');
% flip dimensions
if strcmp(cfg.flipdim,'yes')
fprintf('flipping dimensions...');
interp.anatomy = flipdim(interp.anatomy,1);
interp.source = flipdim(interp.source,1);
interp.mask = flipdim(interp.mask,1);
marker = flipdim(marker,1);
fprintf('done\n');
end
% set slice space
if ischar(cfg.spacemin)
fprintf('setting first slice position...');
spacemin = min(find(~isnan(max(max(interp.source,[],3),[],2))));
fprintf('%d...done\n',spacemin);
else
spacemin = cfg.spacemin;
end
if ischar(cfg.spacemax)
fprintf('setting last slice position...');
spacemax = max(find(~isnan(max(max(interp.source,[],3),[],2))));
fprintf('%d...done\n',spacemax);
else
spacemax = cfg.spacemax;
end
% clip funtional data
if ~ischar(cfg.clipmin)
fprintf('clipping functional minimum...');
switch cfg.clipsym
case 'no'
interp.source(find(interp.source<cfg.clipmin)) = nan;
case 'yes'
interp.source(find(abs(interp.source)<cfg.clipmin)) = nan;
end
fprintf('done\n');
end
if ~ischar(cfg.clipmax)
fprintf('clipping functional maximum...');
switch cfg.clipsym
case 'no'
interp.source(find(interp.source>cfg.clipmax)) = nan;
case 'yes'
interp.source(find(abs(interp.source)>cfg.clipmax)) = nan;
end
fprintf('done\n');
end
% clip mask data
if maskdat
if ~ischar(cfg.maskclipmin)
fprintf('clipping mask minimum...');
switch cfg.maskclipsym
case 'no'
interp.mask(find(interp.mask<cfg.maskclipmin)) = nan;
case 'yes'
interp.mask(find(abs(interp.mask)<cfg.maskclipmin)) = nan;
end
fprintf('done\n');
end
if ~ischar(cfg.maskclipmax)
fprintf('clipping mask maximum...');
switch cfg.maskclipsym
case 'no'
interp.mask(find(interp.mask>cfg.maskclipmax)) = nan;
case 'yes'
interp.mask(find(abs(interp.mask)>cfg.maskclipmax)) = nan;
end
fprintf('done\n');
end
end
% scale functional data
fprintf('scaling functional data...');
fmin = min(interp.source(:));
fmax = max(interp.source(:));
if ~ischar(cfg.colmin)
fcolmin = cfg.colmin;
else
if sign(fmin)==sign(fmax)
fcolmin = fmin;
else
fcolmin = -max(abs([fmin,fmax]));
end
end
if ~ischar(cfg.colmax)
fcolmax = cfg.colmax;
else
if sign(fmin)==sign(fmax)
fcolmax = fmax;
else
fcolmax = max(abs([fmin,fmax]));
end
end
interp.source = (interp.source-fcolmin)./(fcolmax-fcolmin);
if ~ischar(cfg.colmax)
interp.source(find(interp.source>1)) = 1;
end
if ~ischar(cfg.colmin)
interp.source(find(interp.source<0)) = 0;
end
fprintf('done\n');
% scale mask data
if maskdat
fprintf('scaling mask data...');
fmin = min(interp.mask(:));
fmax = max(interp.mask(:));
if ~ischar(cfg.maskcolmin)
mcolmin = cfg.maskcolmin;
else
if sign(fmin)==sign(fmax)
mcolmin = fmin;
else
mcolmin = -max(abs([fmin,fmax]));
end
end
if ~ischar(cfg.maskcolmax)
mcolmax = cfg.maskcolmax;
else
if sign(fmin)==sign(fmax)
mcolmax = fmax;
else
mcolmax = max(abs([fmin,fmax]));
end
end
interp.mask = (interp.mask-mcolmin)./(mcolmax-mcolmin);
if ~ischar(cfg.maskcolmax)
interp.mask(find(interp.mask>1)) = 1;
end
if ~ischar(cfg.maskcolmin)
interp.mask(find(interp.mask<0)) = 0;
end
fprintf('done\n');
end
% merge anatomy, functional data and mask
fprintf('constructing overlay...');
if ischar(cfg.colormap)
% replace string by colormap using standard Matlab function
cfg.colormap = colormap(cfg.colormap);
end
cmap = cfg.colormap;
cmaplength = size(cmap,1);
maskmap = cfg.maskmap(:);
maskmaplength = size(maskmap,1);
indslice = round(linspace(spacemin,spacemax,cfg.nslices));
nvox1 = length(1:cfg.resample:size(interp.anatomy,2));
nvox2 = length(1:cfg.resample:size(interp.anatomy,3));
if mod(cfg.rotate,2)
dummy = nvox1;
nvox1 = nvox2;
nvox2 = dummy;
end
out = zeros(nvox1,nvox2,3,cfg.nslices);
for islice = 1:cfg.nslices
dummy1 = squeeze(interp.anatomy(indslice(islice),1:cfg.resample:end,1:cfg.resample:end));
dummy2 = squeeze(interp.source(indslice(islice),1:cfg.resample:end,1:cfg.resample:end));
indmarker = find(squeeze(marker(indslice(islice),1:cfg.resample:end,1:cfg.resample:end)));
indsource = find(~isnan(dummy2));
if maskdat
dummymask = squeeze(interp.mask(indslice(islice),1:cfg.resample:end,1:cfg.resample:end));
indsource = find(~isnan(dummy2) & ~isnan(dummymask));
end
for icol = 1:3
dummy3 = dummy1;
if not(maskdat)
if ~ischar(cfg.alpha)
try
dummy3(indsource) = ...
(1-cfg.alpha) * dummy3(indsource) + ...
cfg.alpha * cmap(round(dummy2(indsource)*(cmaplength-1))+1,icol);
end
else
try
dummy3(indsource) = ...
(1-dummy2(indsource)) .* dummy3(indsource) + ...
dummy2(indsource) .* cmap(round(dummy2(indsource)*(cmaplength-1))+1,icol);
end
end
else
dummy3(indsource) = ...
(1-maskmap(round(dummymask(indsource)*(maskmaplength-1))+1)).* ...
dummy3(indsource) + ...
maskmap(round(dummymask(indsource)*(maskmaplength-1))+1) .* ...
cmap(round(dummy2(indsource)*(cmaplength-1))+1,icol);
end
dummy3(indmarker) = cfg.markercolor(icol);
out(:,:,icol,islice) = rot90(dummy3,cfg.rotate);
end
if strcmp(cfg.whitebg,'yes')
bgmask = zeros(nvox1,nvox2);
bgmask(find(conv2(mean(out(:,:,:,islice),3),ones(round((nvox1+nvox2)/8))/(round((nvox1+nvox2)/8).^2),'same')<0.1)) = 1;
for icol = 1:3
out(:,:,icol,islice) = bgmask.*ones(nvox1,nvox2) + (1-bgmask).* out(:,:,icol,islice);
end
end
end
fprintf('done\n');
clf;
fprintf('plotting...');
axes('position',[0.9 0.3 0.02 0.4]);
image(permute(cmap,[1 3 2]));
set(gca,'YAxisLocation','right');
set(gca,'XTick',[]);
set(gca,'YDir','normal');
set(gca,'YTick',linspace(1,cmaplength,5));
set(gca,'YTickLabel',linspace(fcolmin,fcolmax,5));
set(gca,'Box','on');
axes('position',[0.01 0.01 0.88 0.90]);
[h,nrows,ncols]=slicemon(out);
xlim=get(gca,'XLim');
ylim=get(gca,'YLim');
text(diff(xlim)/2,-diff(ylim)/100,cfg.title,'HorizontalAlignment','center','Interpreter','none');
drawnow;
fprintf('done\n');
if nargout > 0
outim=get(h,'CData');
end
if strcmp(cfg.interactive,'yes')
data.sin = size(interp.source);
data.nrows = nrows;
data.ncols = ncols;
data.out = out;
data.indslice = indslice;
data.cfg = cfg;
data.hfig = gcf;
uicontrol('Units','norm', 'Position', [0.9 0.2 0.08 0.05], 'Style','pushbutton', 'String','coords',...
'Callback',@getcoords,'FontSize',7);
data.hcoords = uicontrol('Units','norm', 'Position', [0.9 0.05 0.08 0.13], 'Style','text', 'String','','HorizontalAlign','left','FontSize',7);
guidata(data.hfig,data);
end
% ---------------- subfunctions ----------------
function getcoords(h,eventdata,handles,varargin)
data = guidata(gcf);
[xi,yi] = ginput(1);
co(2,1) = round(mod(yi,size(data.out,1)));
co(3,1) = round(mod(xi,size(data.out,2)));
switch mod(data.cfg.rotate,4)
case 1,
t1 = co(2);
co(2) = co(3);
co(3) = data.sin(3)-t1;
case 2,
co(2) = data.sin(2)-co(2);
co(3) = data.sin(3)-co(3);
case 3,
t1 = co(3);
co(3) = co(2);
co(2) = data.sin(2)-t1;
end
try
co(1) = data.indslice(fix(xi/size(data.out,2)) + fix(yi/size(data.out,1))*data.ncols + 1);
catch
co(1) = NaN;
end
if strcmp(data.cfg.flipdim, 'yes')
co(1) = data.sin(1) - co(1) + 1;
end
co = co(:);
co(2:3) = round(co(2:3)*data.cfg.resample);
for ishift = 1:data.cfg.dim-1
co = [co(3);co(1);co(2)];
end
set(data.hcoords,'String',sprintf('1: %d\n2: %d\n3: %d\nf: %0.4f',co(1),co(2),co(3),data.source(co(1),co(2),co(3))));
function [h,nrows,ncols] = slicemon(a) % display the montage w/o image_toolbox
siz = [size(a,1) size(a,2) size(a,4)];
nn = sqrt(prod(siz))/siz(2);
mm = siz(3)/nn;
if (ceil(nn)-nn) < (ceil(mm)-mm),
nn = ceil(nn); mm = ceil(siz(3)/nn);
else
mm = ceil(mm); nn = ceil(siz(3)/mm);
end
b = a(1,1);
b(1,1) = 0;
b = repmat(b, [mm*siz(1), nn*siz(2), size(a,3), 1]);
rows = 1:siz(1); cols = 1:siz(2);
for i=0:mm-1,
for j=0:nn-1,
k = j+i*nn+1;
if k<=siz(3),
b(rows+i*siz(1),cols+j*siz(2),:) = a(:,:,:,k);
end
end
end
hh = image(b);
axis image;
box off;
set(gca,'XTick',[],'YTick',[],'Visible','off');
if nargout > 0
h = hh;
nrows = mm;
ncols = nn;
end
|
github
|
philippboehmsturm/antx-master
|
ft_clusterplot.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_clusterplot.m
| 16,490 |
utf_8
|
b8379032ebcbc79b3690053a475183fd
|
function ft_clusterplot(cfg, stat)
% FT_CLUSTERPLOT plots a series of topoplots with found clusters highlighted.
% stat is 2D or 1D data from FT_TIMELOCKSTATISTICS or FT_FREQSTATISTICS with 'cluster'
% as cfg.correctmc. 2D: stat from FT_TIMELOCKSTATISTICS not averaged over
% time, or stat from FT_FREQSTATISTICS averaged over frequency not averaged over
% time. 1D: averaged over time as well.
%
% use as: ft_clusterplot(cfg,stat)
%
% configuration options
% cfg.alpha = number, highest cluster p-value to be plotted
% max 0.3 (default = 0.05)
% cfg.highlightseries = 1x5 cell-array, highlight option series ('on','labels','numbers')
% default {'on','on','on','on','on'} for p < [0.01 0.05 0.1 0.2 0.3]
% cfg.highlightsymbolseries = 1x5 vector, highlight marker symbol series
% default ['*','x','+','o','.'] for p < [0.01 0.05 0.1 0.2 0.3]
% cfg.highlightsizeseries = 1x5 vector, highlight marker size series
% default [6 6 6 6 6] for p < [0.01 0.05 0.1 0.2 0.3]
% cfg.highlightcolorpos = color of highlight marker for positive clusters
% default = [0 0 0]
% cfg.highlightcolorneg = color of highlight marker for negative clusters
% default = [0 0 0]
% cfg.saveaspng = string, path where figure has to be saved to (default = 'no')
% When multiple figures figure gets extension with fignum
%
% It is also possible to specify other cfg options that apply to FT_TOPOPLOTER.
% You CANNOT specify cfg.xlim, any of the FT_TOPOPLOTER highlight
% options, cfg.comment and cfg.commentpos.
%
% To facilitate data-handling and distributed computing with the peer-to-peer
% module, this function has the following option:
% cfg.inputfile = ...
% If you specify this option the input data will be read from a *.mat
% file on disk. This mat files should contain only a single variable named 'data',
% corresponding to the input structure.
%
% See also:
% FT_TOPOPLOTER, FT_SINGLEPLOTER
% Copyright (C) 2007, Ingrid Nieuwenhuis, F.C. Donders Centre
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_clusterplot.m 3016 2011-03-01 19:09:40Z eelspa $
ft_defaults
% default for inputfile
if ~isfield(cfg, 'inputfile'), cfg.inputfile = []; end
% load optional given inputfile as data
hasdata = (nargin>1);
if ~isempty(cfg.inputfile)
% the input data should be read from file
if hasdata
error('cfg.inputfile should not be used in conjunction with giving input data to this function');
else
stat = loadvar(cfg.inputfile, 'stat');
end
end
% check if given data is appropriate
if isfield(stat,'freq') && length(stat.freq) > 1
error('stat contains multiple frequencies which is not allowed because it should be averaged over frequencies')
end
% old config options
cfg = ft_checkconfig(cfg, 'renamed', {'hlmarkerseries', 'highlightsymbolseries'});
cfg = ft_checkconfig(cfg, 'renamed', {'hlmarkersizeseries', 'highlightsizeseries'});
cfg = ft_checkconfig(cfg, 'renamed', {'hlcolorpos', 'highlightcolorpos'});
cfg = ft_checkconfig(cfg, 'renamed', {'hlcolorneg', 'highlightcolorneg'});
cfg = ft_checkconfig(cfg, 'deprecated', {'hllinewidthseries'});
% added several forbidden options
cfg = ft_checkconfig(cfg, 'forbidden', {'highlight'});
cfg = ft_checkconfig(cfg, 'forbidden', {'highlightchannel'});
cfg = ft_checkconfig(cfg, 'forbidden', {'highlightsymbol'});
cfg = ft_checkconfig(cfg, 'forbidden', {'highlightcolor'});
cfg = ft_checkconfig(cfg, 'forbidden', {'highlightsize'});
cfg = ft_checkconfig(cfg, 'forbidden', {'highlightfontsize'});
cfg = ft_checkconfig(cfg, 'forbidden', {'xlim'});
cfg = ft_checkconfig(cfg, 'forbidden', {'comment'});
cfg = ft_checkconfig(cfg, 'forbidden', {'commentpos'});
% set the defaults
if ~isfield(cfg,'alpha'), cfg.alpha = 0.05; end;
if ~isfield(cfg,'highlightseries'), cfg.highlightseries = {'on','on','on','on','on'}; end;
if ~isfield(cfg,'highlightsymbolseries'), cfg.highlightsymbolseries = ['*','x','+','o','.']; end;
if ~isfield(cfg,'highlightsizeseries'), cfg.highlightsizeseries = [6 6 6 6 6]; end;
if ~isfield(cfg,'hllinewidthseries'), cfg.hllinewidthseries = [1 1 1 1 1]; end;
if ~isfield(cfg,'highlightcolorpos'), cfg.highlightcolorpos = [0 0 0]; end;
if ~isfield(cfg,'highlightcolorneg'), cfg.highlightcolorneg = [0 0 0]; end;
if ~isfield(cfg,'zparam'), cfg.zparam = 'stat'; end;
if ~isfield(cfg,'saveaspng'), cfg.saveaspng = 'no'; end;
% error if cfg.highlightseries is not a cell, for possible confusion with cfg-options
if ~iscell(cfg.highlightseries)
error('cfg.highlightseries should be a cell-array of strings')
end
% set additional options for topoplotting
if isfield(cfg, 'marker'), cfgtopo.marker = cfg.marker ; end
if ~isfield(cfg,'marker'), cfgtopo.marker = 'off'; end
if isfield(cfg, 'markersymbol'), cfgtopo.markersymbol = cfg.markersymbol; end
if isfield(cfg, 'markercolor'), cfgtopo.markercolor = cfg.markercolor; end
if isfield(cfg, 'markersize'), cfgtopo.markersize = cfg.markersize; end
if isfield(cfg, 'markerfontsize'), cfgtopo.markerfontsize = cfg.markerfontsize; end
if isfield(cfg, 'style'), cfgtopo.style = cfg.style ; end
if isfield(cfg, 'gridscale'), cfgtopo.gridscale = cfg.gridscale; end
if isfield(cfg, 'interplimits'), cfgtopo.interplimits = cfg.interplimits; end
if isfield(cfg, 'interpolation'), cfgtopo.interpolation = cfg.interpolation; end
if isfield(cfg, 'contournum'), cfgtopo.contournum = cfg.contournum; end
if isfield(cfg, 'colorbar'), cfgtopo.colorbar = cfg.colorbar; end
if isfield(cfg, 'shading'), cfgtopo.shading = cfg.shading'; end
if isfield(cfg, 'zlim'), cfgtopo.zlim = cfg.zlim; end
cfgtopo.zparam = cfg.zparam;
% prepare the layout, this only has to be done once
cfgtopo.layout = ft_prepare_layout(cfg, stat);
% detect 2D or 1D
is2D = isfield(stat,'time');
% add .time field to 1D data, topoplotER wants it
if ~is2D
stat.time = 0; %doesn't matter what it is, so just choose 0
end;
% find significant clusters
sigpos = [];
signeg = [];
haspos = isfield(stat,'posclusters');
hasneg = isfield(stat,'negclusters');
if haspos == 0 && hasneg == 0
fprintf('%s\n','no significant clusters in data; nothing to plot')
else
if haspos
for iPos = 1:length(stat.posclusters)
sigpos(iPos) = stat.posclusters(iPos).prob < cfg.alpha;
end
end
if hasneg
for iNeg = 1:length(stat.negclusters)
signeg(iNeg) = stat.negclusters(iNeg).prob < cfg.alpha;
end
end
sigpos = find(sigpos == 1);
signeg = find(signeg == 1);
Nsigpos = length(sigpos);
Nsigneg = length(signeg);
Nsigall = Nsigpos + Nsigneg;
if Nsigall == 0
error('no clusters present with a p-value lower than the specified alpha, nothing to plot')
end
% make clusterslabel matrix per significant cluster
posCLM = squeeze(stat.posclusterslabelmat);
sigposCLM = zeros(size(posCLM));
probpos = [];
for iPos = 1:length(sigpos)
sigposCLM(:,:,iPos) = (posCLM == sigpos(iPos));
probpos(iPos) = stat.posclusters(iPos).prob;
hlsignpos(iPos) = prob2hlsign(probpos(iPos), cfg.highlightsymbolseries);
end
negCLM = squeeze(stat.negclusterslabelmat);
signegCLM = zeros(size(negCLM));
probneg = [];
for iNeg = 1:length(signeg)
signegCLM(:,:,iNeg) = (negCLM == signeg(iNeg));
probneg(iNeg) = stat.negclusters(iNeg).prob;
hlsignneg(iNeg) = prob2hlsign(probneg(iNeg), cfg.highlightsymbolseries);
end
fprintf('%s%i%s%g%s\n','There are ',Nsigall,' clusters smaller than alpha (',cfg.alpha,')')
if is2D
% define time window per cluster
for iPos = 1:length(sigpos)
possum_perclus = sum(sigposCLM(:,:,iPos),1); %sum over Chans for each timepoint
ind_min = min(find(possum_perclus~=0));
ind_max = max(find(possum_perclus~=0));
time_perclus = [stat.time(ind_min) stat.time(ind_max)];
fprintf('%s%s%s%s%s%s%s%s%s%s%s\n','Positive cluster: ',num2str(sigpos(iPos)),', pvalue: ',num2str(probpos(iPos)),' (',hlsignpos(iPos),')',', t = ',num2str(time_perclus(1)),' to ',num2str(time_perclus(2)))
end
for iNeg = 1:length(signeg)
negsum_perclus = sum(signegCLM(:,:,iNeg),1);
ind_min = min(find(negsum_perclus~=0));
ind_max = max(find(negsum_perclus~=0));
time_perclus = [stat.time(ind_min) stat.time(ind_max)];
fprintf('%s%s%s%s%s%s%s%s%s%s%s\n','Negative cluster: ',num2str(signeg(iNeg)),', pvalue: ',num2str(probneg(iNeg)),' (',hlsignneg(iNeg),')',', t = ',num2str(time_perclus(1)),' to ',num2str(time_perclus(2)))
end
% define timewindow containing all significant clusters
possum = sum(sigposCLM,3); %sum over Chans for timevector
possum = sum(possum,1);
negsum = sum(signegCLM,3);
negsum = sum(negsum,1);
allsum = possum + negsum;
ind_timewin_min = min(find(allsum~=0));
ind_timewin_max = max(find(allsum~=0));
timewin = stat.time(ind_timewin_min:ind_timewin_max);
else
for iPos = 1:length(sigpos)
fprintf('%s%s%s%s%s%s%s\n','Positive cluster: ',num2str(sigpos(iPos)),', pvalue: ',num2str(probpos(iPos)),' (',hlsignpos(iPos),')')
end
for iNeg = 1:length(signeg)
fprintf('%s%s%s%s%s%s%s\n','Negative cluster: ',num2str(signeg(iNeg)),', pvalue: ',num2str(probneg(iNeg)),' (',hlsignneg(iNeg),')')
end
end
% setup highlight options for all clusters and make comment for 1D data
compos = [];
comneg = [];
for iPos = 1:length(sigpos)
if stat.posclusters(sigpos(iPos)).prob < 0.01
cfgtopo.highlight{iPos} = cfg.highlightseries{1};
cfgtopo.highlightsymbol{iPos} = cfg.highlightsymbolseries(1);
cfgtopo.highlightsize{iPos} = cfg.highlightsizeseries(1);
elseif stat.posclusters(sigpos(iPos)).prob < 0.05
cfgtopo.highlight{iPos} = cfg.highlightseries{2};
cfgtopo.highlightsymbol{iPos} = cfg.highlightsymbolseries(2);
cfgtopo.highlightsize{iPos} = cfg.highlightsizeseries(2);
elseif stat.posclusters(sigpos(iPos)).prob < 0.1
cfgtopo.highlight{iPos} = cfg.highlightseries{3};
cfgtopo.highlightsymbol{iPos} = cfg.highlightsymbolseries(3);
cfgtopo.highlightsize{iPos} = cfg.highlightsizeseries(3);
elseif stat.posclusters(sigpos(iPos)).prob < 0.2
cfgtopo.highlight{iPos} = cfg.highlightseries{4};
cfgtopo.highlightsymbol{iPos} = cfg.highlightsymbolseries(4);
cfgtopo.highlightsize{iPos} = cfg.highlightsizeseries(4);
elseif stat.posclusters(sigpos(iPos)).prob < 0.3
cfgtopo.highlight{iPos} = cfg.highlightseries{5};
cfgtopo.highlightsymbol{iPos} = cfg.highlightsymbolseries(5);
cfgtopo.highlightsize{iPos} = cfg.highlightsizeseries(5);
end
cfgtopo.highlightcolor{iPos} = cfg.highlightcolorpos;
compos = strcat(compos,cfgtopo.highlightsymbol{iPos}, 'p=',num2str(probpos(iPos)),' '); % make comment, only used for 1D data
end
for iNeg = 1:length(signeg)
if stat.negclusters(signeg(iNeg)).prob < 0.01
cfgtopo.highlight{length(sigpos)+iNeg} = cfg.highlightseries{1};
cfgtopo.highlightsymbol{length(sigpos)+iNeg} = cfg.highlightsymbolseries(1);
cfgtopo.highlightsize{length(sigpos)+iNeg} = cfg.highlightsizeseries(1);
elseif stat.negclusters(signeg(iNeg)).prob < 0.05
cfgtopo.highlight{length(sigpos)+iNeg} = cfg.highlightseries{2};
cfgtopo.highlightsymbol{length(sigpos)+iNeg} = cfg.highlightsymbolseries(2);
cfgtopo.highlightsize{length(sigpos)+iNeg} = cfg.highlightsizeseries(2);
elseif stat.negclusters(signeg(iNeg)).prob < 0.1
cfgtopo.highlight{length(sigpos)+iNeg} = cfg.highlightseries{3};
cfgtopo.highlightsymbol{length(sigpos)+iNeg} = cfg.highlightsymbolseries(3);
cfgtopo.highlightsize{length(sigpos)+iNeg} = cfg.highlightsizeseries(3);
elseif stat.negclusters(signeg(iNeg)).prob < 0.2
cfgtopo.highlight{length(sigpos)+iNeg} = cfg.highlightseries{4};
cfgtopo.highlightsymbol{length(sigpos)+iNeg} = cfg.highlightsymbolseries(4);
cfgtopo.highlightsize{length(sigpos)+iNeg} = cfg.highlightsizeseries(4);
elseif stat.negclusters(signeg(iNeg)).prob < 0.3
cfgtopo.highlight{length(sigpos)+iNeg} = cfg.highlightseries{5};
cfgtopo.highlightsymbol{length(sigpos)+iNeg} = cfg.highlightsymbolseries(5);
cfgtopo.highlightsize{length(sigpos)+iNeg} = cfg.highlightsizeseries(5);
end
cfgtopo.highlightcolor{length(sigpos)+iNeg} = cfg.highlightcolorneg;
comneg = strcat(comneg,cfgtopo.highlightsymbol{length(sigpos)+iNeg}, 'p=',num2str(probneg(iNeg)),' '); % make comment, only used for 1D data
end
if is2D
Npl = length(timewin);
else
Npl = 1;
end
Nfig = ceil(Npl/15);
% put channel indexes in list
if is2D
for iPl = 1:Npl
for iPos = 1:length(sigpos)
list{iPl}{iPos} = find(sigposCLM(:,ind_timewin_min+iPl-1,iPos) == 1);
end
for iNeg = 1:length(signeg)
list{iPl}{length(sigpos)+iNeg} = find(signegCLM(:,ind_timewin_min+iPl-1,iNeg) == 1);
end
end
else
for iPl = 1:Npl
for iPos = 1:length(sigpos)
list{iPl}{iPos} = find(sigposCLM(:,iPos) == 1);
end
for iNeg = 1:length(signeg)
list{iPl}{length(sigpos)+iNeg} = find(signegCLM(:,iNeg) == 1);
end
end
end
% make plots
for iPl = 1:Nfig
figure;
if is2D
if iPl < Nfig
for iT = 1:15
PlN = (iPl-1)*15 + iT; %plotnumber
cfgtopo.xlim = [stat.time(ind_timewin_min+PlN-1) stat.time(ind_timewin_min+PlN-1)];
cfgtopo.highlightchannel = list{PlN};
cfgtopo.comment = strcat('time: ',num2str(stat.time(ind_timewin_min+PlN-1)), ' s');
cfgtopo.commentpos = 'title';
subplot(3,5,iT);
ft_topoplotER(cfgtopo, stat);
end
elseif iPl == Nfig
for iT = 1:Npl-(15*(Nfig-1))
PlN = (iPl-1)*15 + iT; %plotnumber
cfgtopo.xlim = [stat.time(ind_timewin_min+PlN-1) stat.time(ind_timewin_min+PlN-1)];
cfgtopo.highlightchannel = list{PlN};
cfgtopo.comment = strcat('time: ',num2str(stat.time(ind_timewin_min+PlN-1)), ' s');
cfgtopo.commentpos = 'title';
subplot(3,5,iT);
ft_topoplotER(cfgtopo, stat);
end
end
else
cfgtopo.highlightchannel = list{1};
cfgtopo.xparam = 'time';
cfgtopo.yparam = '';
cfgtopo.comment = strcat(compos,comneg);
cfgtopo.commentpos = 'title';
ft_topoplotER(cfgtopo, stat);
end
% save figure
if isequal(cfg.saveaspng,'no');
else
filename = strcat(cfg.saveaspng, '_fig', num2str(iPl));
print(gcf,'-dpng',filename);
end
end
end
%% subfunctions %%
function sign = prob2hlsign(prob, hlsign)
if prob < 0.01
sign = hlsign(1);
elseif prob < 0.05
sign = hlsign(2);
elseif prob < 0.1
sign = hlsign(3);
elseif prob < 0.2
sign = hlsign(4);
elseif prob < 0.3
sign = hlsign(5);
end
|
github
|
philippboehmsturm/antx-master
|
ft_sourcemovie.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_sourcemovie.m
| 8,106 |
utf_8
|
74b719b98fa2f7af869cfc332e70a7fa
|
function cfg = ft_sourcemovie(cfg, source)
% FT_SOURCEMOVIE displays the source reconstruction on a cortical mesh
% and allows the user to scroll through time with a movie
%
% Use as
% FT_SOURCEMOVIE(cfg, source)
% where indata is obtained from FT_SOURCEANALYSIS
% and cfg is a configuratioun structure that should contain
%
% cfg.xparam = string, parameter over which the movie unrolls (default = 'time')
% cfg.zparam = string, parameter that is color coded (default = 'avg.pow')
%
% To facilitate data-handling and distributed computing with the peer-to-peer
% module, this function has the following option:
% cfg.inputfile = ...
% If you specify this option the input data will be read from a *.mat
% file on disk. This mat files should contain only a single variable named 'data',
% corresponding to the input structure.
%
% See also FT_SOURCEPLOT, FT_SOURCEINTERPOLATE
% Copyright (C) 2011, Robert Oostenveld
%
% $Id: ft_sourcemovie.m 3710 2011-06-16 14:04:19Z eelspa $
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% the initial part deals with parsing the input options and data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
ft_defaults
% record start time and total processing time
ftFuncTimer = tic();
ftFuncClock = clock();
if isfield(cfg, 'inputfile') && ~isempty(cfg.inputfile)
% the input data should be read from file
if (nargin>1)
error('cfg.inputfile should not be used in conjunction with giving input data to this function');
else
source = loadvar(cfg.inputfile, 'source');
end
end
% ensure that the input data is valiud for this function, this will also do
% backward-compatibility conversions of old data that for example was
% read from an old *.mat file
source = ft_checkdata(source, 'datatype', 'source', 'feedback', 'yes');
% check if the input cfg is valid for this function
cfg = ft_checkconfig(cfg, 'trackconfig', 'on');
% get the options
xlim = ft_getopt(cfg, 'xlim');
zlim = ft_getopt(cfg, 'zlim');
xparam = ft_getopt(cfg, 'xparam', 'time'); % use time as default
zparam = ft_getopt(cfg, 'zparam', 'avg.pow'); % use power as default
mask = ft_getopt(cfg, 'mask', []);
% update the configuration
cfg.xparam = xparam;
cfg.zparam = zparam;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% the actual computation is done in the middle part
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
xparam = source.(xparam);
zparam = getsubfield(source, zparam); % might be avg.pow
if length(xparam)~=size(zparam,2)
error('inconsistent size of "%s" compared to "%s"', cfg.zparam, cfg.xparam);
end
if size(source.pos)~=size(zparam,1)
error('inconsistent number of vertices in the cortical mesh', cfg.zparam, cfg.xparam);
end
if ~isfield(source, 'tri')
error('source.tri missing, this function requires a triangulated cortical sheet as source model');
end
if isempty(xlim)
xlim(1) = min(xparam);
xlim(2) = max(xparam);
end
xbeg = nearest(xparam, xlim(1));
xend = nearest(xparam, xlim(2));
% update the configuration
cfg.xlim = xparam([xbeg xend]);
% make a subselection of the data
xparam = xparam(xbeg:xend);
zparam = zparam(:,xbeg:xend);
clear xbeg xend
if isempty(zlim)
zlim(1) = min(zparam(:));
zlim(2) = max(zparam(:));
% update the configuration
cfg.zlim = zlim;
end
h = gcf;
pos = get(gcf, 'position');
set(h, 'toolbar', 'figure');
s = uicontrol('style', 'slider');
set(s, 'position', [20 20 pos(3)-40 20]);
p = uicontrol('style', 'pushbutton');
set(p, 'position', [20 50 50 20]);
set(p, 'string', 'play')
button_slower = uicontrol('style', 'pushbutton');
set(button_slower, 'position', [75 50 20 20]);
set(button_slower, 'string', '-')
set(button_slower, 'Callback', @cb_slower);
button_faster = uicontrol('style', 'pushbutton');
set(button_faster, 'position', [100 50 20 20]);
set(button_faster, 'string', '+')
set(button_faster, 'Callback', @cb_faster);
ht = uicontrol('style', 'text');
set(ht, 'position', [125 50 pos(3)-145 20]);
set(ht, 'string', 'time = ');
set(ht, 'horizontalalignment', 'left');
text(0,0, sprintf('%s = \n', cfg.xparam));
t = timer;
set(t, 'timerfcn', {@cb_timer, h}, 'period', 0.1, 'executionmode', 'fixedSpacing');
% collect the data and the options to be used in the figure
opt.pnt = source.pos;
opt.tri = source.tri;
opt.tim = xparam;
opt.dat = zparam;
opt.speed = 1;
opt.cfg = cfg;
opt.s = s;
opt.p = p;
opt.t = t;
if ~isempty(mask) && ischar(mask)
opt.mask = double(getsubfield(source, mask));
end
ft_plot_mesh(opt, 'edgecolor', 'none', 'facecolor', [0.5 0.5 0.5]);
lighting gouraud
hs = ft_plot_mesh(opt, 'edgecolor', 'none', 'vertexcolor', 0*opt.dat(:,1), 'facealpha', 0*opt.mask(:,1));
caxis(cfg.zlim);
lighting gouraud
camlight left
camlight right
% add the handle to the mesh
opt.hs = hs;
% add the text-handle to the mesh
opt.ht = ht;
guidata(h, opt);
% from now it is safe to hand over the control to the callback function
set(s, 'Callback', @cb_slider);
% from now it is safe to hand over the control to the callback function
set(p, 'Callback', @cb_playbutton);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% deal with the output
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% get the output cfg
cfg = ft_checkconfig(cfg, 'trackconfig', 'off', 'checksize', 'yes');
% add the version details of this function call to the configuration
cfg.version.name = mfilename('fullpath'); % this is helpful for debugging
cfg.version.id = '$Id: ft_sourcemovie.m 3710 2011-06-16 14:04:19Z eelspa $'; % this will be auto-updated by the revision control system
% add information about the Matlab version used to the configuration
cfg.callinfo.matlab = version();
% add information about the function call to the configuration
cfg.callinfo.proctime = toc(ftFuncTimer);
cfg.callinfo.calltime = ftFuncClock;
cfg.callinfo.user = getusername(); % this is helpful for debugging
if isfield(source, 'cfg')
% remember the configuration details of the input data
cfg.previous = source.cfg;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_slider(h, eventdata)
opt = guidata(h);
val = get(opt.s, 'value');
val = round(val*(size(opt.dat,2)-1))+1;
val = min(val, size(opt.dat,2));
val = max(val, 1);
%text(0, 0, sprintf('%s = %f\n', opt.cfg.xparam, opt.tim(val)));
set(opt.ht, 'string', sprintf('%s = %f\n', opt.cfg.xparam, opt.tim(val)));
set(opt.hs, 'FaceVertexCData', opt.dat(:,val));
if isfield(opt, 'mask')
set(opt.hs, 'FaceVertexAlphaData', opt.mask(:,val));
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_playbutton(h, eventdata)
if ~ishandle(h)
return
end
opt = guidata(h);
switch get(h, 'string')
case 'play'
set(h, 'string', 'stop');
start(opt.t);
case 'stop'
set(h, 'string', 'play');
stop(opt.t);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_timer(obj, info, h)
if ~ishandle(h)
return
end
opt = guidata(h);
delta = opt.speed/size(opt.dat,2);
val = get(opt.s, 'value');
val = val + delta;
if val>1
val = val-1;
end
set(opt.s, 'value', val);
cb_slider(h);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_faster(h, eventdata)
if ~ishandle(h)
return
end
opt = guidata(h);
opt.speed = opt.speed*sqrt(2);
guidata(h, opt);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_slower(h, eventdata)
if ~ishandle(h)
return
end
opt = guidata(h);
opt.speed = opt.speed/sqrt(2);
opt.speed = max(opt.speed, 1); % should not be smaller than 1
guidata(h, opt);
|
github
|
philippboehmsturm/antx-master
|
ft_sourcestatistics.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_sourcestatistics.m
| 21,411 |
utf_8
|
aad51cd6bbd790904f065535f4c33a11
|
function [stat] = ft_sourcestatistics(cfg, varargin)
% FT_SOURCESTATISTICS computes the probability for a given null-hypothesis using
% a parametric statistical test or using a non-parametric randomization test.
%
% Use as
% [stat] = ft_sourcestatistics(cfg, source1, source2, ...)
% where the input data is the result from FT_SOURCEANALYSIS, FT_SOURCEDESCRIPTIVES
% or FT_SOURCEGRANDAVERAGE. The source structures should be spatially alligned
% to each other and should have the same positions for the source grid.
%
% The configuration should contain the following option for data selection
% cfg.parameter = string, describing the functional data to be processed, e.g. 'pow', 'nai' or 'coh'
%
% Furthermore, the configuration should contain:
% cfg.method = different methods for calculating the probability of the null-hypothesis,
% 'montecarlo' uses a non-parametric randomization test to get a Monte-Carlo estimate of the probability,
% 'analytic' uses a parametric test that results in analytic probability,
% 'stats' (soon deprecated) uses a parametric test from the Matlab statistics toolbox,
% 'parametric' uses the Matlab statistics toolbox (very similar to 'stats'),
% 'randomization' uses randomization of the data prior to source reconstruction,
% 'randcluster' uses randomization of the data prior to source reconstruction
% in combination with spatial clusters.
%
% You can restrict the statistical analysis to regions of interest (ROIs)
% or to the average value inside ROIs using the following options:
% cfg.atlas = filename of the atlas
% cfg.roi = string or cell of strings, region(s) of interest from anatomical atlas
% cfg.avgoverroi = 'yes' or 'no' (default = 'no')
% cfg.hemisphere = 'left', 'right', 'both', 'combined', specifying this is
% required when averaging over regions
% cfg.inputcoord = 'mni' or 'tal', the coordinate system in which your source
% reconstruction is expressed
%
% The other cfg options depend on the method that you select. You
% should read the help of the respective subfunction STATISTICS_XXX
% for the corresponding configuration options and for a detailed
% explanation of each method.
%
% See also FT_SOURCEANALYSIS, FT_SOURCEDESCRIPTIVES, FT_SOURCEGRANDAVERAGE
% Copyright (C) 2005-2008, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_sourcestatistics.m 3732 2011-06-29 07:49:26Z jorhor $
ft_defaults
% record start time and total processing time
ftFuncTimer = tic();
ftFuncClock = clock();
% this wrapper should be compatible with the already existing statistical
% functions that only work for source input data
if ~isfield(cfg, 'implementation'), cfg.implementation = 'old'; end
if strcmp(cfg.implementation, 'old'),
%--------------------------------
% use the original implementation
% check if the input data is valid for this function
for i=1:length(varargin)
if isfield(cfg, 'roi') && ~isempty(cfg.roi)
varargin{i} = ft_checkdata(varargin{i}, 'datatype', 'source', 'feedback', 'no', 'inside', 'index');
else
varargin{i} = ft_checkdata(varargin{i}, 'datatype', {'source', 'volume'}, 'feedback', 'no', 'inside', 'index');
end
end
if strcmp(cfg.method, 'parametric')
% use the source-specific statistical subfunction
stat = sourcestatistics_parametric(cfg, varargin{:});
elseif strcmp(cfg.method, 'randomization')
% use the source-specific statistical subfunction
stat = sourcestatistics_randomization(cfg, varargin{:});
elseif strcmp(cfg.method, 'randcluster')
% use the source-specific statistical subfunction
stat = sourcestatistics_randcluster(cfg, varargin{:});
else
[stat, cfg] = statistics_wrapper(cfg, varargin{:});
end
% add version information to the configuration
cfg.version.name = mfilename('fullpath');
cfg.version.id = '$Id: ft_sourcestatistics.m 3732 2011-06-29 07:49:26Z jorhor $';
% add information about the Matlab version used to the configuration
cfg.callinfo.matlab = version();
% add information about the function call to the configuration
cfg.callinfo.proctime = toc(ftFuncTimer);
cfg.callinfo.calltime = ftFuncClock;
cfg.callinfo.user = getusername();
% remember the configuration of the input data
cfg.previous = [];
for i=1:length(varargin)
if isfield(varargin{i}, 'cfg')
cfg.previous{i} = varargin{i}.cfg;
else
cfg.previous{i} = [];
end
end
% remember the exact configuration details
stat.cfg = cfg;
elseif strcmp(cfg.implementation, 'new')
%---------------------------
% use the new implementation
issource = ft_datatype(varargin{1}, 'source');
isvolume = ft_datatype(varargin{1}, 'volume');
% check if the input data is valid for this function
for i=1:length(varargin)
if isfield(cfg, 'roi') && ~isempty(cfg.roi)
% FIXME implement roi-based statistics for the new implementation
% (code is copied over from the old implementation but not yet tested
error('roi based sourcestatistics is not yet implemented for the new implementation');
varargin{i} = ft_checkdata(varargin{i}, 'datatype', 'source', 'feedback', 'no', 'inside', 'index');
else
varargin{i} = ft_checkdata(varargin{i}, 'datatype', {'source', 'volume'}, 'feedback', 'no', 'inside', 'index', 'sourcerepresentation', 'new');
if strcmp(cfg.parameter, 'pow') && ~isfield(varargin{i}, 'pow'),
varargin{i} = ft_checkdata(varargin{i}, 'sourcerepresentation', 'new', 'haspow', 'yes');
end
end
end
if any(strcmp(cfg.method, {'parametric' 'randomization' 'randcluster'}))
% FIXME only supported for old-style source representation
for i = 1:numel(varargin)
varargin{i} = ft_checkdata(varargin{i}, 'sourcerepresentation', 'old');
end
if exist(['statistics_',cfg.method]),
statmethod = str2func(['statistics_' cfg.method]);
else
error(sprintf('could not find the corresponding function for cfg.method="%s"\n', cfg.method));
end
stat = statmethod(cfg, varargin{:});
else
% convert representation of input data to new style
for i = 1:numel(varargin)
varargin{i} = ft_checkdata(varargin{i}, 'sourcerepresentation', 'new');
end
% check the input configuration
cfg = ft_checkconfig(cfg, 'renamed', {'approach', 'method'});
cfg = ft_checkconfig(cfg, 'required', {'method', 'parameter'});
cfg = ft_checkconfig(cfg, 'forbidden', {'transform'});
% set the defaults
if ~isfield(cfg, 'channel'), cfg.channel = 'all'; end
if ~isfield(cfg, 'latency'), cfg.latency = 'all'; end
if ~isfield(cfg, 'frequency'), cfg.frequency = 'all'; end
if ~isfield(cfg, 'roi'), cfg.roi = []; end
if ~isfield(cfg, 'avgoverchan'), cfg.avgoverchan = 'no'; end
if ~isfield(cfg, 'avgovertime'), cfg.avgovertime = 'no'; end
if ~isfield(cfg, 'avgoverfreq'), cfg.avgoverfreq = 'no'; end
if ~isfield(cfg, 'avgoverroi'), cfg.avgoverroi = 'no'; end
% test that all source inputs have the same dimensions and are spatially aligned
for i=2:length(varargin)
if isfield(varargin{1}, 'dim') && (numel(varargin{i}.dim)~=length(varargin{1}.dim) || ~all(varargin{i}.dim==varargin{1}.dim))
error('dimensions of the source reconstructions do not match, use VOLUMENORMALISE first');
end
if isfield(varargin{1}, 'pos') && (numel(varargin{i}.pos(:))~=numel(varargin{1}.pos(:)) || ~all(varargin{i}.pos(:)==varargin{1}.pos(:)))
error('grid locations of the source reconstructions do not match, use VOLUMENORMALISE first');
end
end
Nsource = length(varargin);
Nvoxel = length(varargin{1}.inside) + length(varargin{1}.outside);
%FIXME ft_selectdata should be used for the subselection
%FIXME ft_selectdata has to be adjusted to work with new style source data
%if isfield(varargin{1}, 'freq') && ~strcmp(cfg.frequency, 'all'),
% for i=1:length(varargin)
% varargin{i} = ft_selectdata(varargin{i}, 'foilim', cfg.frequency, ...
% 'avgoverfreq', cfg.avgoverfreq);
% end
%end
% this part contains the functionality of the old statistics_wrapper
% with source data in the input
if ~isempty(cfg.roi)
if ischar(cfg.roi)
cfg.roi = {cfg.roi};
end
% the source representation should specify the position of each voxel in MNI coordinates
x = varargin{1}.pos(:,1); % this is from left (negative) to right (positive)
% determine the mask to restrict the subsequent analysis
% process each of the ROIs, and optionally also left and/or right seperately
roimask = {};
roilabel = {};
for i=1:length(cfg.roi)
tmpcfg.roi = cfg.roi{i};
tmpcfg.inputcoord = cfg.inputcoord;
tmpcfg.atlas = cfg.atlas;
tmp = ft_volumelookup(tmpcfg, varargin{1});
if strcmp(cfg.avgoverroi, 'no') && ~isfield(cfg, 'hemisphere')
% no reason to deal with seperated left/right hemispheres
cfg.hemisphere = 'combined';
end
if strcmp(cfg.hemisphere, 'left')
tmp(x>=0) = 0; % exclude the right hemisphere
roimask{end+1} = tmp;
roilabel{end+1} = ['Left ' cfg.roi{i}];
elseif strcmp(cfg.hemisphere, 'right')
tmp(x<=0) = 0; % exclude the right hemisphere
roimask{end+1} = tmp;
roilabel{end+1} = ['Right ' cfg.roi{i}];
elseif strcmp(cfg.hemisphere, 'both')
% deal seperately with the voxels on the left and right side of the brain
tmpL = tmp; tmpL(x>=0) = 0; % exclude the right hemisphere
tmpR = tmp; tmpR(x<=0) = 0; % exclude the left hemisphere
roimask{end+1} = tmpL;
roimask{end+1} = tmpR;
roilabel{end+1} = ['Left ' cfg.roi{i}];
roilabel{end+1} = ['Right ' cfg.roi{i}];
clear tmpL tmpR
elseif strcmp(cfg.hemisphere, 'combined')
% all voxels of the ROI can be combined
roimask{end+1} = tmp;
roilabel{end+1} = cfg.roi{i};
else
error('incorrect specification of cfg.hemisphere');
end
clear tmp
end % for each roi
% note that avgoverroi=yes is implemented differently at a later stage
% avgoverroi=no is implemented using the inside/outside mask
if strcmp(cfg.avgoverroi, 'no')
for i=2:length(roimask)
% combine them all in the first mask
roimask{1} = roimask{1} | roimask{i};
end
roimask = roimask{1}; % only keep the combined mask
% the source representation should have an inside and outside vector containing indices
sel = find(~roimask);
varargin{1}.inside = setdiff(varargin{1}.inside, sel);
varargin{1}.outside = union(varargin{1}.outside, sel);
clear roimask roilabel
end % if avgoverroi=no
end % if ~isempty cfg.roi
% get the required source level data
[dat, cfg] = getfunctional(cfg, varargin{:});
% note that avgoverroi=no is implemented differently at an earlier stage
if strcmp(cfg.avgoverroi, 'yes')
tmp = zeros(length(roimask), size(dat,2));
for i=1:length(roimask)
% the data only reflects those points that are inside the brain,
% the atlas-based mask reflects points inside and outside the brain
roi = roimask{i}(varargin{1}.inside);
tmp(i,:) = mean(dat(roi,:), 1);
end
% replace the original data with the average over each ROI
dat = tmp;
clear tmp roi roimask
% remember the ROIs
cfg.dimord = 'roi';
end
end
%get the design from the information in the cfg and data
if ~isfield(cfg, 'design'),
cfg.design = data.design;
cfg = prepare_design(cfg);
end
if size(cfg.design, 2)~=size(dat, 2)
cfg.design = transpose(cfg.design);
end
% determine the function handle to the intermediate-level statistics function
if exist(['statistics_' cfg.method])
statmethod = str2func(['statistics_' cfg.method]);
else
error(sprintf('could not find the corresponding function for cfg.method="%s"\n', cfg.method));
end
fprintf('using "%s" for the statistical testing\n', func2str(statmethod));
% check that the design completely describes the data
if size(dat,2) ~= size(cfg.design,2)
error('the size of the design matrix does not match the number of observations in the data');
end
% determine the number of output arguments
try
% the nargout function in Matlab 6.5 and older does not work on function handles
num = nargout(statmethod);
catch
num = 1;
end
% perform the statistical test
if strcmp(func2str(statmethod),'statistics_montecarlo')
% because statistics_montecarlo (or to be precise, clusterstat)
% requires to know whether it is getting source data,
% the following (ugly) work around is necessary
if num>1
[stat, cfg] = statmethod(cfg, dat, cfg.design, 'issource', 1);
else
[stat] = statmethod(cfg, dat, cfg.design, 'issource', 1);
end
else
if num>1
[stat, cfg] = statmethod(cfg, dat, cfg.design);
else
[stat] = statmethod(cfg, dat, cfg.design);
end
end
if isstruct(stat)
% the statistical output contains multiple elements, e.g. F-value, beta-weights and probability
statfield = fieldnames(stat);
else
% only the probability was returned as a single matrix, reformat into a structure
dum = stat; stat = []; % this prevents a Matlab warning that appears from release 7.0.4 onwards
stat.prob = dum;
statfield = fieldnames(stat);
end
% add descriptive information to the output and rehape into the input format
if isempty(cfg.roi) || strcmp(cfg.avgoverroi, 'no')
% remember the definition of the volume, assume that they are identical for all input arguments
try, stat.dim = varargin{1}.dim; end
try, stat.xgrid = varargin{1}.xgrid; end
try, stat.ygrid = varargin{1}.ygrid; end
try, stat.zgrid = varargin{1}.zgrid; end
try, stat.inside = varargin{1}.inside; end
try, stat.outside = varargin{1}.outside; end
try, stat.pos = varargin{1}.pos; end
try, stat.transform = varargin{1}.transform; end
else
stat.inside = 1:length(roilabel);
stat.outside = [];
stat.label = roilabel(:);
end
% additional descriptive fields
hasfreq = strcmp(cfg.avgoverfreq, 'no') && isfield(varargin{1},'freq');
hastime = strcmp(cfg.avgovertime, 'no') && isfield(varargin{1},'time');
stat.dimord = 'pos_';
if hasfreq,
stat.dimord = [stat.dimord, 'freq_'];
stat.freq = varargin{1}.freq;
nfreq = numel(varargin{1}.freq);
else
nfreq = 1;
end
if hastime,
stat.dimord = [stat.dimord, 'time_'];
stat.time = varargin{1}.time;
ntime = numel(varargin{1}.time);
else
ntime = 1;
end
stat.dimord = stat.dimord(1:end-1);
if issource,
if hasfreq,
newdim = [size(stat.pos,1) nfreq ntime];
else
newdim = [size(stat.pos,1) ntime];
end
elseif isvolume,
if hasfreq,
newdim = [stat.dim nfreq ntime];
else
newdim = [stat.dim ntime];
end
end
for i=1:length(statfield)
tmp = getsubfield(stat, statfield{i});
tmp2 = [];
ntmp = numel(tmp);
if hasfreq,
tmpdim = [ntmp/(nfreq*ntime) nfreq ntime];
else
tmpdim = [ntmp/ntime ntime];
end
if isfield(varargin{1}, 'inside') && numel(tmp)==nfreq*ntime*length(varargin{1}.inside)
% the statistic was only computed on voxels that are inside the brain
% sort the inside and outside voxels back into their original place
if islogical(tmp)
if hasfreq,
tmp2 = logical(zeros(prod(varargin{1}.dim),nfreq,ntime));
tmp2(varargin{1}.inside, 1:nfreq, 1:ntime) = reshape(tmp, [ntmp/(nfreq*ntime) nfreq ntime]);
else
tmp2 = logical(zeros(prod(varargin{1}.dim),nfreq,ntime));
tmp2(varargin{1}.inside, 1:nfreq, 1:ntime) = reshape(tmp, [ntmp/ntime ntime]);
end
else
if hasfreq,
tmp2 = zeros(prod(varargin{1}.dim),nfreq,ntime)+nan;
tmp2(varargin{1}.inside, 1:nfreq, 1:ntime) = reshape(tmp, [ntmp/(nfreq*ntime) nfreq ntime]);
else
tmp2 = zeros(prod(varargin{1}.dim),nfreq,ntime)+nan;
tmp2(varargin{1}.inside, 1:nfreq, 1:ntime) = reshape(tmp, [ntmp/ntime ntime]);
end
end
end
if numel(tmp2)==prod(newdim)
% reshape the statistical volumes into the original format
stat = setsubfield(stat, statfield{i}, reshape(tmp2, newdim));
end
end
% add version information to the configuration
cfg.version.name = mfilename('fullpath');
cfg.version.id = '$Id: ft_sourcestatistics.m 3732 2011-06-29 07:49:26Z jorhor $';
% add information about the Matlab version used to the configuration
cfg.callinfo.matlab = version();
% add information about the function call to the configuration
cfg.callinfo.proctime = toc(ftFuncTimer);
cfg.callinfo.calltime = ftFuncClock;
cfg.callinfo.user = getusername();
% remember the configuration of the input data
cfg.previous = [];
for i=1:length(varargin)
if isfield(varargin{i}, 'cfg')
cfg.previous{i} = varargin{i}.cfg;
else
cfg.previous{i} = [];
end
end
% remember the exact configuration details
stat.cfg = cfg;
else
error('cfg.implementation can be only old or new');
end
%-----------------------------------------------------
%subfunction to extract functional data from the input
%and convert it into a 2D representation
function [dat, cfg] = getfunctional(cfg, varargin)
%FIXME think of how this generalizes to volumetric data (boolean inside etc)
Nsource = numel(varargin);
Nvox = size(varargin{1}.pos, 1);
inside = varargin{1}.inside;
Ninside = numel(inside);
dimord = varargin{1}.([cfg.parameter,'dimord']);
dimtok = tokenize(dimord, '_');
%check whether the requested parameter is represented as cell-array
x1 = strfind(dimord, '{');
x2 = strfind(dimord, '}');
if ~isempty(x1) && ~isempty(x2)
cellparam = 1;
cellsiz = size(varargin{1}.(cfg.parameter));
%this only explicitly keeps the first singleton dimension
%the last to be removed
cellsiz(find(cellsiz(2:end)==1)+1) = [];
cellsiz(cellsiz==Nvox) = Ninside;
else
cellparam = 0;
end
%check whether there are single observations/subjects in the data
rptdim = ~cellfun(@isempty, strfind(dimtok, 'rpt')) | ~cellfun(@isempty, strfind(dimtok, 'subj'));
hasrpt = sum(rptdim);
if hasrpt && Nsource>1,
error('only a single input with multiple observations or multiple inputs with a single observation are supported');
end
if hasrpt,
if cellparam,
tmpsiz = [cellsiz size(varargin{1}.(cfg.parameter){inside(1)})];
tmp = zeros(tmpsiz);
%FIXME what about volumetric data?
for k = 1:Ninside
tmp(k,:,:,:,:,:) = varargin{1}.(cfg.parameter){inside(k)};
end
%tmp = cell2mat(varargin{1}.(cfg.parameter)(inside,:,:,:,:));
else
if find(rptdim)==1,
tmp = varargin{1}.(cfg.parameter)(:,inside,:,:,:);
else
tmp = varargin{1}.(cfg.parameter)(inside,:,:,:,:);
end
end
if numel(rptdim)==1,
rptdim = [rptdim 0];
end
%put the repetition dimension to the last dimension
tmp = permute(tmp, [find(rptdim==0) find(rptdim==1)]);
%reshape the data to 2D
siz = size(tmp);
dat = reshape(tmp, [prod(siz(1:end-1)) siz(end)]);
else
for k = 1:Nsource
%check for cell-array representation in the input data
%FIXME this assumes positions to be in the first dimension always
%FIXME what about volumetric dadta
if cellparam
tmp = cell2mat(varargin{k}.(cfg.parameter)(inside,:,:,:,:));
else
tmp = varargin{k}.(cfg.parameter)(inside,:,:,:,:);
end
%allocate memory
if k==1, dat = zeros(numel(tmp), Nsource); end
%reshape the data
siz = size(tmp);
dat(:,k) = tmp(:);
end
end
cfg.dim = varargin{1}.dim;
cfg.inside = varargin{1}.inside; %FIXME take the intersection between all inputs
cfg.dimord = 'voxel';
cfg.origdim = [cfg.dim siz(2:end-1)];
|
github
|
philippboehmsturm/antx-master
|
ft_sourcedescriptives.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_sourcedescriptives.m
| 47,954 |
utf_8
|
f734bb25dae653941d53735ba4b2598e
|
function [source] = ft_sourcedescriptives(cfg, source)
% FT_SOURCEDESCRIPTIVES computes descriptive parameters of the source
% analysis results.
%
% Use as:
% [source] = ft_sourcedescriptives(cfg, source)
%
% where cfg is a structure with the configuration details and source is the
% result from a beamformer source estimation. The configuration can contain
% cfg.cohmethod = 'regular', 'lambda1', 'canonical'
% cfg.powmethod = 'regular', 'lambda1', 'trace', 'none'
% cfg.supmethod = string
% cfg.projectmom = 'yes' or 'no' (default = 'no')
% cfg.eta = 'yes' or 'no' (default = 'no')
% cfg.kurtosis = 'yes' or 'no' (default = 'no')
% cfg.keeptrials = 'yes' or 'no' (default = 'no')
% cfg.resolutionmatrix = 'yes' or 'no' (default = 'no')
% cfg.feedback = 'no', 'text', 'textbar', 'gui' (default = 'text')
%
% The following option only applies to LCMV single-trial timecourses.
% cfg.fixedori = 'within_trials' or 'over_trials' (default = 'over_trials')
%
% You can apply a custom mathematical transformation such as a log-transform
% on the estimated power using
% cfg.transform = string describing the transformation (default is [])
% The nai, i.e. neural activity index (power divided by projected noise),
% is computed prior to applying the optional transformation. Subsequently,
% the transformation is applied on the power and on the projected noise
% using "feval". A useful transformation is for example 'log' or 'log10'.
%
% If repeated trials are present that have undergone some sort of
% resampling (i.e. jackknife, bootstrap, singletrial or rawtrial), the mean,
% variance and standard error of mean will be computed for all source
% parameters. This is done after applying the optional transformation
% on the power and projected noise.
%
% To facilitate data-handling and distributed computing with the peer-to-peer
% module, this function has the following options:
% cfg.inputfile = ...
% cfg.outputfile = ...
% If you specify one of these (or both) the input data will be read from a *.mat
% file on disk and/or the output data will be written to a *.mat file. These mat
% files should contain only a single variable, corresponding with the
% input/output structure.
%
% See also FT_SOURCEANALYSIS, FT_SOURCESTATISTICS
% Copyright (C) 2004-2007, Robert Oostenveld & Jan-Mathijs Schoffelen
% Copyright (C) 2010, Jan-Mathijs Schoffelen
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_sourcedescriptives.m 3710 2011-06-16 14:04:19Z eelspa $
ft_defaults
% record start time and total processing time
ftFuncTimer = tic();
ftFuncClock = clock();
cfg = ft_checkconfig(cfg, 'trackconfig', 'on');
% set the defaults
if ~isfield(cfg, 'transform'), cfg.transform = []; end
if ~isfield(cfg, 'projectmom'), cfg.projectmom = 'no'; end % if yes -> svdfft
if ~isfield(cfg, 'numcomp'), cfg.numcomp = 1; end
if ~isfield(cfg, 'powmethod'), cfg.powmethod = []; end % see below
if ~isfield(cfg, 'cohmethod'), cfg.cohmethod = []; end % see below
if ~isfield(cfg, 'feedback'), cfg.feedback = 'textbar'; end
if ~isfield(cfg, 'supmethod'), cfg.supmethod = 'none'; end
if ~isfield(cfg, 'resolutionmatrix'), cfg.resolutionmatrix = 'no'; end
if ~isfield(cfg, 'eta'), cfg.eta = 'no'; end
if ~isfield(cfg, 'fa'), cfg.fa = 'no'; end
if ~isfield(cfg, 'kurtosis'), cfg.kurtosis = 'no'; end
if ~isfield(cfg, 'keeptrials'), cfg.keeptrials = 'no'; end
if ~isfield(cfg, 'keepcsd'), cfg.keepcsd = 'no'; end
if ~isfield(cfg, 'fixedori'), cfg.fixedori = 'over_trials'; end
if ~isfield(cfg, 'inputfile'), cfg.inputfile = []; end
if ~isfield(cfg, 'outputfile'), cfg.outputfile = []; end
% only works for minimumnormestimate
if ~isfield(cfg, 'demean'), cfg.demean = 'yes'; end
if ~isfield(cfg, 'baselinewindow'), cfg.baselinewindow = [-inf 0]; end
if ~isfield(cfg, 'zscore'), cfg.zscore = 'yes'; end
zscore = strcmp(cfg.zscore, 'yes');
demean = strcmp(cfg.demean, 'yes');
hasdata = (nargin>1);
if ~isempty(cfg.inputfile)
% the input data should be read from file
if hasdata
error('cfg.inputfile should not be used in conjunction with giving input data to this function');
else
data = loadvar(cfg.inputfile, 'source');
end
end
% check if the input data is valid for this function
source = ft_checkdata(source, 'datatype', 'source', 'feedback', 'yes');
% this is required for backward compatibility with the old sourceanalysis
if isfield(source, 'method') && strcmp(source.method, 'randomized')
source.method = 'randomization';
elseif isfield(source, 'method') && strcmp(source.method, 'permuted')
source.method = 'permutation';
elseif isfield(source, 'method') && strcmp(source.method, 'jacknife')
source.method = 'jackknife';
end
% determine the type of data, this is only relevant for a few specific types
ispccdata = isfield(source, 'avg') && isfield(source.avg, 'csdlabel');
islcmvavg = isfield(source, 'avg') && isfield(source, 'time') && isfield(source.avg, 'mom') && size(source.avg.pow, 2)==1;
islcmvtrl = isfield(source, 'trial') && isfield(source, 'time') && isfield(source.trial, 'mom');
ismneavg = isfield(source, 'avg') && isfield(source, 'time') && isfield(source.avg, 'mom') && size(source.avg.pow, 2)==numel(source.time);
% check the consistency of the defaults
if strcmp(cfg.projectmom, 'yes')
if isempty(cfg.powmethod)
cfg.powmethod = 'regular'; % set the default
elseif ~strcmp(cfg.powmethod, 'regular')
error('unsupported powmethod in combination with projectmom');
end
if isempty(cfg.cohmethod)
cfg.cohmethod = 'regular';% set the default
elseif ~strcmp(cfg.cohmethod, 'regular')
error('unsupported cohmethod in combination with projectmom');
end
else
if isempty(cfg.powmethod)
cfg.powmethod = 'lambda1'; % set the default
end
if isempty(cfg.cohmethod)
cfg.cohmethod = 'lambda1'; % set the default
end
end
% this is required for backward compatibility with an old version of sourcedescriptives
if isfield(cfg, 'singletrial'), cfg.keeptrials = cfg.singletrial; end
% do a validity check on the input data and specified options
if strcmp(cfg.resolutionmatrix, 'yes')
if ~isfield(source.avg, 'filter')
error('The computation of the resolution matrix requires keepfilter=''yes'' in sourceanalysis.');
elseif ~isfield(source, 'leadfield')
error('The computation of the resolution matrix requires keepleadfield=''yes'' in sourceanalysis.');
end
end
if strcmp(cfg.eta, 'yes') && strcmp(cfg.cohmethod, 'svdfft'),
error('eta cannot be computed in combination with the application of svdfft');
end
if strcmp(cfg.keeptrials, 'yes') && ~strcmp(cfg.supmethod, 'none'),
error('you cannot keep trials when you want to partialize something');
end
% set some flags for convenience
isnoise = isfield(source, 'avg') && isfield(source.avg, 'noisecsd');
keeptrials = strcmp(cfg.keeptrials, 'yes');
projectmom = strcmp(cfg.projectmom, 'yes');
% determine the subfunction used for computing power
switch cfg.powmethod
case 'regular'
powmethodfun = @powmethod_regular;
case 'lambda1'
powmethodfun = @powmethod_lambda1;
case 'trace'
powmethodfun = @powmethod_trace;
case 'none'
powmethodfun = [];
otherwise
error('unsupported powmethod');
end
if ispccdata
% the source reconstruction was computed using the pcc beamformer
Ndipole = length(source.inside) + length(source.outside);
dipsel = match_str(source.avg.csdlabel, 'scandip');
refchansel = match_str(source.avg.csdlabel, 'refchan');
refdipsel = match_str(source.avg.csdlabel, 'refdip');
supchansel = match_str(source.avg.csdlabel, 'supchan');
supdipsel = match_str(source.avg.csdlabel, 'supdip');
% cannot handle reference channels and reference dipoles simultaneously
if length(refchansel)>0 && length(refdipsel)>0
error('cannot simultaneously handle reference channels and reference dipole');
end
% these are only used to count the number of reference/suppression dipoles and channels
refsel = [refdipsel refchansel];
supsel = [supdipsel supchansel];
if projectmom
source.avg.ori = cell(1, Ndipole);
ft_progress('init', cfg.feedback, 'projecting dipole moment');
for diplop=1:length(source.inside)
ft_progress(diplop/length(source.inside), 'projecting dipole moment %d/%d\n', diplop, length(source.inside));
i = source.inside(diplop);
mom = source.avg.mom{i}(dipsel, :);
ref = source.avg.mom{i}(refdipsel, :);
sup = source.avg.mom{i}(supdipsel, :);
refchan = source.avg.mom{i}(refchansel, :);
supchan = source.avg.mom{i}(supchansel, :);
% compute the projection of the scanning dipole along the direction of the dominant amplitude
if length(dipsel)>1, [mom, rmom] = svdfft(mom, cfg.numcomp, source.cumtapcnt); else rmom = []; end
source.avg.ori{source.inside(diplop)} = rmom;
% compute the projection of the reference dipole along the direction of the dominant amplitude
if length(refdipsel)>1, [ref, rref] = svdfft(ref, 1, source.cumtapcnt); else rref = []; end
% compute the projection of the supression dipole along the direction of the dominant amplitude
if length(supdipsel)>1, [sup, rsup] = svdfft(sup, 1, source.cumtapcnt); else rsup = []; end
% compute voxel-level fourier-matrix
source.avg.mom{i} = cat(1, mom, ref, sup, refchan, supchan);
% create rotation-matrix
rotmat = zeros(0, length(source.avg.csdlabel));
if ~isempty(rmom),
rotmat = [rotmat; rmom zeros(1,length([refsel(:);supsel(:)]))];
end
if ~isempty(rref),
rotmat = [rotmat; zeros(1, length([dipsel])), rref, zeros(1,length([refchansel(:);supsel(:)]))];
end
if ~isempty(rsup),
rotmat = [rotmat; zeros(1, length([dipsel(:);refdipsel(:)])), rsup, zeros(1,length([refchansel(:);supchansel(:)]))];
end
for j=1:length(supchansel)
rotmat(end+1,:) = 0;
rotmat(end,length([dipsel(:);refdipsel(:);supdipsel(:)])+j) = 1;
end
for j=1:length(refchansel)
rotmat(end+1,:) = 0;
rotmat(end,length([dipsel(:);refdipsel(:);supdipsel(:);supchansel(:)])+j) = 1;
end
% compute voxel-level csd-matrix
source.avg.csd{i} = rotmat * source.avg.csd{i} * rotmat';
% compute voxel-level noisecsd-matrix
if isfield(source.avg, 'noisecsd'), source.avg.noisecsd{i} = rotmat * source.avg.noisecsd{i} * rotmat'; end
% compute rotated filter
if isfield(source.avg, 'filter'), source.avg.filter{i} = rotmat * source.avg.filter{i}; end
% compute rotated leadfield
% FIXME in the presence of a refdip and/or supdip, this does not work; leadfield is Nx3
if isfield(source, 'leadfield'),
%FIXME this is a proposed dirty fix
n1 = size(source.leadfield{i},2);
%n2 = size(rotmat,2) - n1;
n2 = size(rotmat,2) - n1 +1; %added 1 JM
source.leadfield{i} = source.leadfield{i} * rotmat(1:n2, 1:n1)';
end
end %for diplop
ft_progress('close');
% remember what the interpretation is of all CSD output components
scandiplabel = repmat({'scandip'}, 1, cfg.numcomp); % only one dipole orientation remains
refdiplabel = repmat({'refdip'}, 1, length(refdipsel)>0); % for svdfft at max. only one dipole orientation remains
supdiplabel = repmat({'supdip'}, 1, length(supdipsel)>0); % for svdfft at max. only one dipole orientation remains
refchanlabel = repmat({'refchan'}, 1, length(refchansel));
supchanlabel = repmat({'supchan'}, 1, length(supchansel));
% concatenate all the labels
source.avg.csdlabel = cat(2, scandiplabel, refdiplabel, supdiplabel, refchanlabel, supchanlabel);
% update the indices
dipsel = match_str(source.avg.csdlabel, 'scandip');
refchansel = match_str(source.avg.csdlabel, 'refchan');
refdipsel = match_str(source.avg.csdlabel, 'refdip');
supchansel = match_str(source.avg.csdlabel, 'supchan');
supdipsel = match_str(source.avg.csdlabel, 'supdip');
refsel = [refdipsel refchansel];
supsel = [supdipsel supchansel];
end % if projectmom
if keeptrials
cumtapcnt = source.cumtapcnt(:);
sumtapcnt = cumsum([0;cumtapcnt]);
Ntrial = length(cumtapcnt);
ft_progress('init', cfg.feedback, 'computing singletrial voxel-level cross-spectral densities');
for triallop = 1:Ntrial
source.trial(triallop).csd = cell(Ndipole, 1); % allocate memory for this trial
source.trial(triallop).mom = cell(Ndipole, 1); % allocate memory for this trial
ft_progress(triallop/Ntrial, 'computing singletrial voxel-level cross-spectral densities %d%d\n', triallop, Ntrial);
for diplop=1:length(source.inside)
i = source.inside(diplop);
dat = source.avg.mom{i};
tmpmom = dat(:, sumtapcnt(triallop)+1:sumtapcnt(triallop+1));
tmpcsd = [tmpmom * tmpmom'] ./cumtapcnt(triallop);
source.trial(triallop).mom{i} = tmpmom;
source.trial(triallop).csd{i} = tmpcsd;
end %for diplop
end % for triallop
ft_progress('close');
% remove the average, continue with separate trials
source = rmfield(source, 'avg');
else
fprintf('using average voxel-level cross-spectral densities\n');
end % if keeptrials
hasrefdip = ~isempty(refdipsel);
hasrefchan = ~isempty(refchansel);
hassupdip = ~isempty(supdipsel);
hassupchan = ~isempty(supchansel);
if keeptrials
% do the processing of the CSD matrices for each trial
if ~strcmp(cfg.supmethod, 'none')
error('suppression is only supported for average CSD');
end
dipselcell = mat2cell(repmat(dipsel(:)', [Ndipole 1]), ones(Ndipole,1), length(dipsel));
if hasrefdip, refdipselcell = mat2cell(repmat(refdipsel(:)', [Ndipole 1]), ones(Ndipole,1), length(refdipsel)); end
if hasrefchan, refchanselcell = mat2cell(repmat(refchansel(:)', [Ndipole 1]), ones(Ndipole,1), length(refchansel)); end
if hassupdip, supdipselcell = mat2cell(repmat(supdipsel(:)', [Ndipole 1]), ones(Ndipole,1), length(supdipsel)); end
if hassupchan, supchanselcell = mat2cell(repmat(supchansel(:)', [Ndipole 1]), ones(Ndipole,1), length(supchansel)); end
ft_progress('init', cfg.feedback, 'computing singletrial voxel-level power');
for triallop = 1:Ntrial
%initialize the variables
source.trial(triallop).pow = zeros(Ndipole, 1);
if hasrefdip, source.trial(triallop).refdippow = zeros(Ndipole, 1); end
if hasrefchan, source.trial(triallop).refchanpow = zeros(Ndipole, 1); end
if hassupdip, source.trial(triallop).supdippow = zeros(Ndipole, 1); end
if hassupchan, source.trial(triallop).supchanpow = zeros(Ndipole, 1); end
ft_progress(triallop/Ntrial, 'computing singletrial voxel-level power %d%d\n', triallop, Ntrial);
source.trial(triallop).pow(source.inside) = cellfun(powmethodfun, source.trial(triallop).csd(source.inside), dipselcell(source.inside));
if hasrefdip, source.trial(triallop).refdippow(source.inside) = cellfun(powmethodfun,source.trial(triallop).csd(source.inside), refdipselcell(source.inside)); end
if hassupdip, source.trial(triallop).supdippow(source.inside) = cellfun(powmethodfun,source.trial(triallop).csd(source.inside), supdipselcell(source.inside)); end
if hasrefchan, source.trial(triallop).refchanpow(source.inside) = cellfun(powmethodfun,source.trial(triallop).csd(source.inside), refchanselcell(source.inside)); end
if hassupchan, source.trial(triallop).supchanpow(source.inside) = cellfun(powmethodfun,source.trial(triallop).csd(source.inside), supchanselcell(source.inside)); end
%FIXME kan volgens mij niet
if isnoise && isfield(source.trial(triallop), 'noisecsd'),
% compute the power of the noise projected on each source component
source.trial(triallop).noise = cellfun(powmethodfun,source.trial(triallop).csd, dipselcell);
if hasrefdip, source.trial(triallop).refdipnoise = cellfun(powmethodfun,source.trial(triallop).noisecsd, refdipselcell); end
if hassupdip, source.trial(triallop).supdipnoise = cellfun(powmethodfun,source.trial(triallop).noisecsd, supdipselcell); end
if hasrefchan, source.trial(triallop).refchannoise = cellfun(powmethodfun,source.trial(triallop).noisecsd, refchanselcell); end
if hassupchan, source.trial(triallop).supchannoise = cellfun(powmethodfun,source.trial(triallop).noisecsd, supchanselcell); end
end % if isnoise
end % for triallop
ft_progress('close');
if strcmp(cfg.keepcsd, 'no')
source.trial = rmfield(source.trial, 'csd');
end
else
% do the processing of the average CSD matrix
for diplop = 1:length(source.inside)
i = source.inside(diplop);
switch cfg.supmethod
case 'chan_dip'
supindx = [supdipsel supchansel];
if diplop==1, refsel = refsel - length(supdipsel); end%adjust index only once
case 'chan'
supindx = [supchansel];
case 'dip'
supindx = [supdipsel];
if diplop==1, refsel = refsel - length(supdipsel); end
case 'none'
% do nothing
supindx = [];
end
tmpcsd = source.avg.csd{i};
scnindx = setdiff(1:size(tmpcsd,1), supindx);
tmpcsd = tmpcsd(scnindx, scnindx) - [tmpcsd(scnindx, supindx)*pinv(tmpcsd(supindx, supindx))*tmpcsd(supindx, scnindx)];
source.avg.csd{i} = tmpcsd;
end % for diplop
source.avg.csdlabel = source.avg.csdlabel(scnindx);
if isnoise && ~strcmp(cfg.supmethod, 'none')
source.avg = rmfield(source.avg, 'noisecsd');
end
% initialize the variables
source.avg.pow = nan*zeros(Ndipole, 1);
if ~isempty(refdipsel), source.avg.refdippow = nan*zeros(Ndipole, 1); end
if ~isempty(refchansel), source.avg.refchanpow = nan*zeros(Ndipole, 1); end
if ~isempty(supdipsel), source.avg.supdippow = nan*zeros(Ndipole, 1); end
if ~isempty(supchansel), source.avg.supchanpow = nan*zeros(Ndipole, 1); end
if isnoise
source.avg.noise = nan*zeros(Ndipole, 1);
if ~isempty(refdipsel), source.avg.refdipnoise = nan*zeros(Ndipole, 1); end
if ~isempty(refchansel), source.avg.refchannoise = nan*zeros(Ndipole, 1); end
if ~isempty(supdipsel), source.avg.supdipnoise = nan*zeros(Ndipole, 1); end
if ~isempty(supchansel), source.avg.supchannoise = nan*zeros(Ndipole, 1); end
end % if isnoise
if ~isempty(refsel), source.avg.coh = nan*zeros(Ndipole, 1); end
if strcmp(cfg.eta, 'yes'),
source.avg.eta = nan*zeros(Ndipole, 1);
source.avg.ori = cell(1, Ndipole);
end
if strcmp(cfg.eta, 'yes') && ~isempty(refsel),
source.avg.etacsd = nan*zeros(Ndipole, 1);
source.avg.ucsd = cell(1, Ndipole);
end
if strcmp(cfg.fa, 'yes'),
source.avg.fa = nan*zeros(Ndipole, 1);
end
for diplop = 1:length(source.inside)
i = source.inside(diplop);
% compute the power of each source component
if strcmp(cfg.projectmom, 'yes') && cfg.numcomp>1,
source.avg.pow(i) = powmethodfun(source.avg.csd{i}(dipsel,dipsel), 1);
else
source.avg.pow(i) = powmethodfun(source.avg.csd{i}(dipsel,dipsel));
end
if ~isempty(refdipsel), source.avg.refdippow(i) = powmethodfun(source.avg.csd{i}(refdipsel,refdipsel)); end
if ~isempty(supdipsel), source.avg.supdippow(i) = powmethodfun(source.avg.csd{i}(supdipsel,supdipsel)); end
if ~isempty(refchansel), source.avg.refchanpow(i) = powmethodfun(source.avg.csd{i}(refchansel,refchansel)); end
if ~isempty(supchansel), source.avg.supchanpow(i) = powmethodfun(source.avg.csd{i}(supchansel,supchansel)); end
if isnoise
% compute the power of the noise projected on each source component
if strcmp(cfg.projectmom, 'yes') && cfg.numcomp>1,
source.avg.noise(i) = powmethodfun(source.avg.noisecsd{i}(dipsel,dipsel), 1);
else
source.avg.noise(i) = powmethodfun(source.avg.noisecsd{i}(dipsel,dipsel));
end
if ~isempty(refdipsel), source.avg.refdipnoise(i) = powmethodfun(source.avg.noisecsd{i}(refdipsel,refdipsel)); end
if ~isempty(supdipsel), source.avg.supdipnoise(i) = powmethodfun(source.avg.noisecsd{i}(supdipsel,supdipsel)); end
if ~isempty(refchansel), source.avg.refchannoise(i) = powmethodfun(source.avg.noisecsd{i}(refchansel,refchansel)); end
if ~isempty(supchansel), source.avg.supchannoise(i) = powmethodfun(source.avg.noisecsd{i}(supchansel,supchansel)); end
end % if isnoise
if ~isempty(refsel)
% compute coherence
csd = source.avg.csd{i};
switch cfg.cohmethod
case 'regular'
% assume that all dipoles have been projected along the direction of maximum power
Pd = abs(csd(dipsel, dipsel));
Pr = abs(csd(refsel, refsel));
Cdr = csd(dipsel, refsel);
source.avg.coh(i) = (Cdr.^2) ./ (Pd*Pr);
case 'lambda1'
%compute coherence on Joachim Gross' way
Pd = lambda1(csd(dipsel, dipsel));
Pr = lambda1(csd(refsel, refsel));
Cdr = lambda1(csd(dipsel, refsel));
source.avg.coh(i) = abs(Cdr).^2 ./ (Pd*Pr);
case 'canonical'
[ccoh, c2, v1, v2] = cancorr(csd, dipsel, refsel);
[cmax, indmax] = max(ccoh);
source.avg.coh(i) = ccoh(indmax);
otherwise
error('unsupported cohmethod');
end % cohmethod
end
% compute eta
if strcmp(cfg.eta, 'yes')
[source.avg.eta(i), source.avg.ori{i}] = csd2eta(source.avg.csd{i}(dipsel,dipsel));
if ~isempty(refsel),
%FIXME this only makes sense when only a reference signal OR a dipole is selected
[source.avg.etacsd(i), source.avg.ucsd{i}] = csd2eta(source.avg.csd{i}(dipsel,refsel));
end
end
%compute fa
if strcmp(cfg.fa, 'yes')
source.avg.fa(i) = csd2fa(source.avg.csd{i}(dipsel,dipsel));
end
end % for diplop
if strcmp(cfg.keepcsd, 'no')
source.avg = rmfield(source.avg, 'csd');
end
if strcmp(cfg.keepcsd, 'no') && isnoise
source.avg = rmfield(source.avg, 'noisecsd');
end
end
elseif ismneavg
%the source reconstruction was computed using the minimumnormestimate and contains an average timecourse
if demean
begsmp = nearest(source.time, cfg.baselinewindow(1));
endsmp = nearest(source.time, cfg.baselinewindow(2));
ft_progress('init', cfg.feedback, 'baseline correcting dipole moments');
for diplop=1:length(source.inside)
ft_progress(diplop/length(source.inside), 'baseline correcting dipole moments %d/%d\n', diplop, length(source.inside));
mom = source.avg.mom{source.inside(diplop)};
mom = ft_preproc_baselinecorrect(mom, begsmp, endsmp);
source.avg.mom{source.inside(diplop)} = mom;
end
ft_progress('close');
end
if projectmom
ft_progress('init', cfg.feedback, 'projecting dipole moment');
for diplop=1:length(source.inside)
ft_progress(diplop/length(source.inside), 'projecting dipole moment %d/%d\n', diplop, length(source.inside));
mom = source.avg.mom{source.inside(diplop)};
[mom, rmom] = svdfft(mom, 1);
source.avg.mom{source.inside(diplop)} = mom;
source.avg.ori{source.inside(diplop)} = rmom;
end
ft_progress('close');
end
if zscore
begsmp = nearest(source.time, cfg.baselinewindow(1));
endsmp = nearest(source.time, cfg.baselinewindow(2));
% zscore using baselinewindow for power
ft_progress('init', cfg.feedback, 'computing power');
source.avg.absmom = source.avg.pow;
for diplop=1:length(source.inside)
ft_progress(diplop/length(source.inside), 'computing power %d/%d\n', diplop, length(source.inside));
mom = source.avg.mom{source.inside(diplop)};
mmom = mean(mom(begsmp:endsmp));
smom = std(mom(begsmp:endsmp));
pow = sum(((mom-mmom)./smom).^2,1);
source.avg.pow(source.inside(diplop),:) = pow;
source.avg.absmom(source.inside(diplop),:) = sum((mom-mmom)./smom,1);
end
ft_progress('close');
else
% just square for power
ft_progress('init', cfg.feedback, 'computing power');
source.avg.absmom = source.avg.pow;
for diplop=1:length(source.inside)
ft_progress(diplop/length(source.inside), 'computing power %d/%d\n', diplop, length(source.inside));
mom = source.avg.mom{source.inside(diplop)};
pow = sum(mom.^2,1);
source.avg.pow(source.inside(diplop),:) = pow;
source.avg.absmom(source.inside(diplop),:) = sum(mom,1);
end
ft_progress('close');
end
if strcmp(cfg.kurtosis, 'yes')
fprintf('computing kurtosis based on dipole timecourse\n');
source.avg.k2 = nan*zeros(size(source.pos,1),1);
for diplop=1:length(source.inside)
mom = source.avg.mom{source.inside(diplop)};
if length(mom)~=prod(size(mom))
error('kurtosis can only be computed for projected dipole moment');
end
source.avg.k2(source.inside(diplop)) = kurtosis(mom);
end
end
elseif islcmvavg
% the source reconstruction was computed using the lcmv beamformer and contains an average timecourse
if projectmom
ft_progress('init', cfg.feedback, 'projecting dipole moment');
for diplop=1:length(source.inside)
ft_progress(diplop/length(source.inside), 'projecting dipole moment %d/%d\n', diplop, length(source.inside));
mom = source.avg.mom{source.inside(diplop)};
[mom, rmom] = svdfft(mom, 1);
source.avg.mom{source.inside(diplop)} = mom;
source.avg.ori{source.inside(diplop)} = rmom;
end
ft_progress('close');
end
if ~strcmp(cfg.powmethod, 'none')
fprintf('recomputing power based on dipole timecourse\n')
source.avg.pow = nan*zeros(size(source.pos,1),1);
for diplop=1:length(source.inside)
mom = source.avg.mom{source.inside(diplop)};
cov = mom * mom';
source.avg.pow(source.inside(diplop)) = powmethodfun(cov);
end
end
if strcmp(cfg.kurtosis, 'yes')
fprintf('computing kurtosis based on dipole timecourse\n');
source.avg.k2 = nan*zeros(size(source.pos,1),1);
for diplop=1:length(source.inside)
mom = source.avg.mom{source.inside(diplop)};
if length(mom)~=prod(size(mom))
error('kurtosis can only be computed for projected dipole moment');
end
source.avg.k2(source.inside(diplop)) = kurtosis(mom);
end
end
elseif islcmvtrl
% the source reconstruction was computed using the lcmv beamformer and contains a single-trial timecourse
ntrial = length(source.trial);
if projectmom && strcmp(cfg.fixedori, 'within_trials')
% the dipole orientation is re-determined for each trial
ft_progress('init', cfg.feedback, 'projecting dipole moment');
for trllop=1:ntrial
ft_progress(trllop/ntrial, 'projecting dipole moment %d/%d\n', trllop, ntrial);
for diplop=1:length(source.inside)
mom = source.trial(trllop).mom{source.inside(diplop)};
[mom, rmom] = svdfft(mom, 1);
source.trial(trllop).mom{source.inside(diplop)} = mom;
source.trial(trllop).ori{source.inside(diplop)} = rmom; % remember the orientation
end
end
ft_progress('close');
elseif projectmom && strcmp(cfg.fixedori, 'over_trials')
ft_progress('init', cfg.feedback, 'projecting dipole moment');
% compute average covariance over all trials
for trllop=1:ntrial
for diplop=1:length(source.inside)
mom = source.trial(trllop).mom{source.inside(diplop)};
if trllop==1
cov{diplop} = mom*mom'./size(mom,2);
else
cov{diplop} = mom*mom'./size(mom,2) + cov{diplop};
end
end
end
% compute source orientation over all trials
for diplop=1:length(source.inside)
[dum, ori{diplop}] = svdfft(cov{diplop}, 1);
end
% project the data in each trial
for trllop=1:ntrial
ft_progress(trllop/ntrial, 'projecting dipole moment %d/%d\n', trllop, ntrial);
for diplop=1:length(source.inside)
mom = source.trial(trllop).mom{source.inside(diplop)};
mom = ori{diplop}*mom;
source.trial(trllop).mom{source.inside(diplop)} = mom;
source.trial(trllop).ori{source.inside(diplop)} = ori{diplop};
end
end
ft_progress('close');
end
if ~strcmp(cfg.powmethod, 'none')
fprintf('recomputing power based on dipole timecourse\n')
for trllop=1:ntrial
for diplop=1:length(source.inside)
mom = source.trial(trllop).mom{source.inside(diplop)};
cov = mom * mom';
source.trial(trllop).pow(source.inside(diplop)) = powmethodfun(cov);
end
end
end
if strcmp(cfg.kurtosis, 'yes')
fprintf('computing kurtosis based on dipole timecourse\n');
for trllop=1:ntrial
source.trial(trllop).k2 = nan*zeros(size(source.pos,1),1);
for diplop=1:length(source.inside)
mom = source.trial(trllop).mom{source.inside(diplop)};
if length(mom)~=prod(size(mom))
error('kurtosis can only be computed for projected dipole moment');
end
source.trial(trllop).k2(source.inside(diplop)) = kurtosis(mom);
end
end
end
end % dealing with pcc or lcmv input
if isfield(source, 'avg') && isfield(source.avg, 'pow') && isfield(source.avg, 'noise')
% compute the neural activity index for the average
source.avg.nai = source.avg.pow(:) ./ source.avg.noise(:);
end
if isfield(source, 'trial') && isfield(source.trial, 'pow') && isfield(source.trial, 'noise')
% compute the neural activity index for the trials
ntrials = length(source.trial);
for trlop=1:ntrials
source.trial(trlop).nai = source.trial(trlop).pow ./ source.trial(trlop).noise;
end
end
if strcmp(source.method, 'randomization') || strcmp(source.method, 'permutation')
% compute the neural activity index for the two randomized conditions
source.avgA.nai = source.avgA.pow ./ source.avgA.noise;
source.avgB.nai = source.avgB.pow ./ source.avgB.noise;
for trlop=1:length(source.trialA)
source.trialA(trlop).nai = source.trialA(trlop).pow ./ source.trialA(trlop).noise;
end
for trlop=1:length(source.trialB)
source.trialB(trlop).nai = source.trialB(trlop).pow ./ source.trialB(trlop).noise;
end
end
if ~isempty(cfg.transform)
fprintf('applying %s transformation on the power and projected noise\n', cfg.transform);
% apply the specified transformation on the power
if isfield(source, 'avg' ) && isfield(source.avg , 'pow'), source.avg .pow = feval(cfg.transform, source.avg .pow); end
if isfield(source, 'avgA' ) && isfield(source.avgA , 'pow'), source.avgA.pow = feval(cfg.transform, source.avgA.pow); end
if isfield(source, 'avgB' ) && isfield(source.avgB , 'pow'), source.avgB.pow = feval(cfg.transform, source.avgB.pow); end
if isfield(source, 'trial' ) && isfield(source.trial , 'pow'), for i=1:length(source.trial ), source.trial (i).pow = feval(cfg.transform, source.trial (i).pow); end; end
if isfield(source, 'trialA') && isfield(source.trialA, 'pow'), for i=1:length(source.trialA), source.trialA(i).pow = feval(cfg.transform, source.trialA(i).pow); end; end
if isfield(source, 'trialB') && isfield(source.trialB, 'pow'), for i=1:length(source.trialB), source.trialB(i).pow = feval(cfg.transform, source.trialB(i).pow); end; end
% apply the specified transformation on the projected noise
if isfield(source, 'avg' ) && isfield(source.avg , 'noise'), source.avg .noise = feval(cfg.transform, source.avg .noise); end
if isfield(source, 'avgA' ) && isfield(source.avgA , 'noise'), source.avgA.noise = feval(cfg.transform, source.avgA.noise); end
if isfield(source, 'avgB' ) && isfield(source.avgB , 'noise'), source.avgB.noise = feval(cfg.transform, source.avgB.noise); end
if isfield(source, 'trial' ) && isfield(source.trial , 'noise'), for i=1:length(source.trial ), source.trial (i).noise = feval(cfg.transform, source.trial (i).noise); end; end
if isfield(source, 'trialA') && isfield(source.trialA, 'noise'), for i=1:length(source.trialA), source.trialA(i).noise = feval(cfg.transform, source.trialA(i).noise); end; end
if isfield(source, 'trialB') && isfield(source.trialB, 'noise'), for i=1:length(source.trialB), source.trialB(i).noise = feval(cfg.transform, source.trialB(i).noise); end; end
end
if strcmp(source.method, 'pseudovalue')
% compute the pseudovalues for the beamformer output
avg = source.trial(1); % the first is the complete average
Ntrials = length(source.trial)-1; % the remaining are the leave-one-out averages
pseudoval = [];
if isfield(source.trial, 'pow')
allavg = getfield(avg, 'pow');
for i=1:Ntrials
thisavg = getfield(source.trial(i+1), 'pow');
thisval = Ntrials*allavg - (Ntrials-1)*thisavg;
pseudoval(i).pow = thisval;
end
end
if isfield(source.trial, 'coh')
allavg = getfield(avg, 'coh');
for i=1:Ntrials
thisavg = getfield(source.trial(i+1), 'coh');
thisval = Ntrials*allavg - (Ntrials-1)*thisavg;
pseudoval(i).coh = thisval;
end
end
if isfield(source.trial, 'nai')
allavg = getfield(avg, 'nai');
for i=1:Ntrials
thisavg = getfield(source.trial(i+1), 'nai');
thisval = Ntrials*allavg - (Ntrials-1)*thisavg;
pseudoval(i).nai = thisval;
end
end
if isfield(source.trial, 'noise')
allavg = getfield(avg, 'noise');
for i=1:Ntrials
thisavg = getfield(source.trial(i+1), 'noise');
thisval = Ntrials*allavg - (Ntrials-1)*thisavg;
pseudoval(i).noise = thisval;
end
end
% store the pseudovalues instead of the original values
source.trial = pseudoval;
end
if strcmp(source.method, 'jackknife') || strcmp(source.method, 'bootstrap') || strcmp(source.method, 'pseudovalue') || strcmp(source.method, 'singletrial') || strcmp(source.method, 'rawtrial')
% compute descriptive statistics (mean, var, sem) for multiple trial data
% compute these for as many source parameters as possible
% for convenience copy the trials out of the source structure
dip = source.trial;
% determine the (original) number of trials in the data
if strcmp(source.method, 'bootstrap') %VERANDERD ER ZAT GEEN .RESAMPLE IN SOURCE
Ntrials = size(source.trial,2);% WAS size(source.resample, 2);
else
Ntrials = length(source.trial);
end
fprintf('original data contained %d trials\n', Ntrials);
% allocate memory for all elements in the dipole structure
sumdip = [];
if isfield(dip(1), 'var'), sumdip.var = zeros(size(dip(1).var )); sumdip.var(source.outside)=nan; end
if isfield(dip(1), 'pow'), sumdip.pow = zeros(size(dip(1).pow )); sumdip.pow(source.outside)=nan; end
if isfield(dip(1), 'coh'), sumdip.coh = zeros(size(dip(1).coh )); sumdip.coh(source.outside)=nan; end
if isfield(dip(1), 'rv'), sumdip.rv = zeros(size(dip(1).rv )); sumdip.rv(source.outside)=nan; end
if isfield(dip(1), 'noise'), sumdip.noise = zeros(size(dip(1).noise)); sumdip.noise(source.outside)=nan; end
if isfield(dip(1), 'nai'), sumdip.nai = zeros(size(dip(1).nai )); sumdip.nai(source.outside)=nan; end
sqrdip = [];
if isfield(dip(1), 'var'), sqrdip.var = zeros(size(dip(1).var )); sqrdip.var(source.outside)=nan; end
if isfield(dip(1), 'pow'), sqrdip.pow = zeros(size(dip(1).pow )); sqrdip.pow(source.outside)=nan; end
if isfield(dip(1), 'coh'), sqrdip.coh = zeros(size(dip(1).coh )); sqrdip.coh(source.outside)=nan; end
if isfield(dip(1), 'rv'), sqrdip.rv = zeros(size(dip(1).rv )); sqrdip.rv(source.outside)=nan; end
if isfield(dip(1), 'noise'), sqrdip.noise = zeros(size(dip(1).noise)); sqrdip.noise(source.outside)=nan; end
if isfield(dip(1), 'nai'), sqrdip.nai = zeros(size(dip(1).nai )); sqrdip.nai(source.outside)=nan; end
if isfield(dip(1), 'mom')
sumdip.mom = cell(size(dip(1).mom));
sqrdip.mom = cell(size(dip(1).mom));
for i=1:length(dip(1).mom)
sumdip.mom{i} = nan*zeros(size(dip(1).mom{i}));
sqrdip.mom{i} = nan*zeros(size(dip(1).mom{i}));
end
end
if isfield(dip(1), 'csd')
sumdip.csd = cell(size(dip(1).csd));
sqrdip.csd = cell(size(dip(1).csd));
for i=1:length(dip(1).csd)
sumdip.csd{i} = nan*zeros(size(dip(1).csd{i}));
sqrdip.csd{i} = nan*zeros(size(dip(1).csd{i}));
end
end
for trial=1:length(dip)
% compute the sum of all values
if isfield(dip(trial), 'var'), sumdip.var = sumdip.var + dip(trial).var; end
if isfield(dip(trial), 'pow'), sumdip.pow = sumdip.pow + dip(trial).pow; end
if isfield(dip(trial), 'coh'), sumdip.coh = sumdip.coh + dip(trial).coh; end
if isfield(dip(trial), 'rv'), sumdip.rv = sumdip.rv + dip(trial).rv; end
if isfield(dip(trial), 'noise'), sumdip.noise = sumdip.noise + dip(trial).noise; end
if isfield(dip(trial), 'nai'), sumdip.nai = sumdip.nai + dip(trial).nai; end
% compute the sum of squared values
if isfield(dip(trial), 'var'), sqrdip.var = sqrdip.var + (dip(trial).var ).^2; end
if isfield(dip(trial), 'pow'), sqrdip.pow = sqrdip.pow + (dip(trial).pow ).^2; end
if isfield(dip(trial), 'coh'), sqrdip.coh = sqrdip.coh + (dip(trial).coh ).^2; end
if isfield(dip(trial), 'rv'), sqrdip.rv = sqrdip.rv + (dip(trial).rv ).^2; end
if isfield(dip(trial), 'noise'), sqrdip.noise = sqrdip.noise + (dip(trial).noise).^2; end
if isfield(dip(trial), 'nai'), sqrdip.nai = sqrdip.nai + (dip(trial).nai ).^2; end
% do the same for the cell array with mom
if isfield(dip(trial), 'mom')
for i=1:length(dip(1).mom)
sumdip.mom{i} = sumdip.mom{i} + dip(trial).mom{i};
sqrdip.mom{i} = sqrdip.mom{i} + (dip(trial).mom{i}).^2;
end
end
% do the same for the cell array with csd
if isfield(dip(trial), 'csd')
for i=1:length(dip(1).csd)
sumdip.csd{i} = sumdip.csd{i} + dip(trial).csd{i};
sqrdip.csd{i} = sqrdip.csd{i} + (dip(trial).csd{i}).^2;
end
end
end
% compute the mean over all repetitions
if isfield(sumdip, 'var'), dipmean.var = sumdip.var / length(dip); end
if isfield(sumdip, 'pow'), dipmean.pow = sumdip.pow / length(dip); end
if isfield(sumdip, 'coh'), dipmean.coh = sumdip.coh / length(dip); end
if isfield(sumdip, 'rv'), dipmean.rv = sumdip.rv / length(dip); end
if isfield(sumdip, 'noise'), dipmean.noise = sumdip.noise / length(dip); end
if isfield(sumdip, 'nai'), dipmean.nai = sumdip.nai / length(dip); end
% for the cell array with mom, this is done further below
% for the cell array with csd, this is done further below
% the estimates for variance and SEM are biased if we are working with the jackknife/bootstrap
% determine the proper variance scaling that corrects for this bias
% note that Ntrials is not always the same as the length of dip, especially in case of the bootstrap
if strcmp(source.method, 'singletrial')
bias = 1;
elseif strcmp(source.method, 'rawtrial')
bias = 1;
elseif strcmp(source.method, 'jackknife')
% Effron gives SEM estimate for the jackknife method in equation 11.5 (paragraph 11.2)
% to get the variance instead of SEM, we also have to multiply with the number of trials
bias = (Ntrials - 1)^2;
elseif strcmp(source.method, 'bootstrap')
% Effron gives SEM estimate for the bootstrap method in algorithm 6.1 (equation 6.6)
% to get the variance instead of SEM, we also have to multiply with the number of trials
bias = Ntrials;
elseif strcmp(source.method, 'pseudovalue')
% note that I have not put any thought in this aspect yet
warning('don''t know how to compute bias for pseudovalue resampling');
bias = 1;
end
% compute the variance over all repetitions
if isfield(sumdip, 'var'), dipvar.var = bias*(sqrdip.var - (sumdip.var .^2)/length(dip))/(length(dip)-1); end
if isfield(sumdip, 'pow'), dipvar.pow = bias*(sqrdip.pow - (sumdip.pow .^2)/length(dip))/(length(dip)-1); end
if isfield(sumdip, 'coh'), dipvar.coh = bias*(sqrdip.coh - (sumdip.coh .^2)/length(dip))/(length(dip)-1); end
if isfield(sumdip, 'rv' ), dipvar.rv = bias*(sqrdip.rv - (sumdip.rv .^2)/length(dip))/(length(dip)-1); end
if isfield(sumdip, 'noise' ), dipvar.noise = bias*(sqrdip.noise - (sumdip.noise .^2)/length(dip))/(length(dip)-1); end
if isfield(sumdip, 'nai' ), dipvar.nai = bias*(sqrdip.nai - (sumdip.nai .^2)/length(dip))/(length(dip)-1); end
% compute the SEM over all repetitions
if isfield(sumdip, 'var'), dipsem.var = (dipvar.var /Ntrials).^0.5; end
if isfield(sumdip, 'pow'), dipsem.pow = (dipvar.pow /Ntrials).^0.5; end
if isfield(sumdip, 'coh'), dipsem.coh = (dipvar.coh /Ntrials).^0.5; end
if isfield(sumdip, 'rv' ), dipsem.rv = (dipvar.rv /Ntrials).^0.5; end
if isfield(sumdip, 'noise' ), dipsem.noise = (dipvar.noise /Ntrials).^0.5; end
if isfield(sumdip, 'nai' ), dipsem.nai = (dipvar.nai /Ntrials).^0.5; end
% compute the mean and SEM over all repetitions for the cell array with mom
if isfield(dip(trial), 'mom')
for i=1:length(dip(1).mom)
dipmean.mom{i} = sumdip.mom{i}/length(dip);
dipvar.mom{i} = bias*(sqrdip.mom{i} - (sumdip.mom{i}.^2)/length(dip))/(length(dip)-1);
dipsem.mom{i} = (dipvar.mom{i}/Ntrials).^0.5;
end
end
% compute the mean and SEM over all repetitions for the cell array with csd
if isfield(dip(trial), 'csd')
for i=1:length(dip(1).csd)
dipmean.csd{i} = sumdip.csd{i}/length(dip);
dipvar.csd{i} = bias*(sqrdip.csd{i} - (sumdip.csd{i}.^2)/length(dip))/(length(dip)-1);
dipsem.csd{i} = (dipvar.csd{i}/Ntrials).^0.5;
end
end
if strcmp(source.method, 'pseudovalue')
% keep the trials, since they have been converted to pseudovalues
% and hence the trials contain the interesting data
elseif keeptrials
% keep the trials upon request
else
% remove the original trials
source = rmfield(source, 'trial');
% assign the descriptive statistics to the output source structure
source.avg = dipmean;
source.var = dipvar;
source.sem = dipsem;
end
end
if strcmp(cfg.resolutionmatrix, 'yes')
% this is only implemented for pcc and no refdips/chans at the moment
Nchan = size(source.leadfield{source.inside(1)}, 1);
Ninside = length(source.inside);
allfilter = zeros(Ninside,Nchan);
allleadfield = zeros(Nchan,Ninside);
dipsel = match_str(source.avg.csdlabel, 'scandip');
ft_progress('init', cfg.feedback, 'computing resolution matrix');
for diplop=1:length(source.inside)
ft_progress(diplop/length(source.inside), 'computing resolution matrix %d/%d\n', diplop, length(source.inside));
i = source.inside(diplop);
% concatenate all filters
allfilter(diplop,:) = source.avg.filter{i}(dipsel,:);
% concatenate all leadfields
allleadfield(:,diplop) = source.leadfield{i};
end
ft_progress('close');
% multiply the filters and leadfields to obtain the resolution matrix
% see equation 1 and 2 in De Peralta-Menendez RG, Gonzalez-Andino SL: A critical analysis of linear inverse solutions to the neuroelectromagnetic inverse problem. IEEE Transactions on Biomedical Engineering 45: 440-448, 1998.
source.resolution = nan*zeros(Ndipole, Ndipole);
source.resolution(source.inside, source.inside) = allfilter*allleadfield;
end
% accessing this field here is needed for the configuration tracking
% by accessing it once, it will not be removed from the output cfg
cfg.outputfile;
% get the output cfg
cfg = ft_checkconfig(cfg, 'trackconfig', 'off', 'checksize', 'yes');
% add version information to the configuration
cfg.version.name = mfilename('fullpath');
cfg.version.id = '$Id: ft_sourcedescriptives.m 3710 2011-06-16 14:04:19Z eelspa $';
% add information about the Matlab version used to the configuration
cfg.callinfo.matlab = version();
% add information about the function call to the configuration
cfg.callinfo.proctime = toc(ftFuncTimer);
cfg.callinfo.calltime = ftFuncClock;
cfg.callinfo.user = getusername();
% remember the configuration details of the input data
try, cfg.previous = source.cfg; end
% remember the exact configuration details in the output
source.cfg = cfg;
% the output data should be saved to a MATLAB file
if ~isempty(cfg.outputfile)
savevar(cfg.outputfile, 'source', source); % use the variable name "data" in the output file
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function to compute eta from a csd-matrix
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [eta, u] = csd2eta(csd)
[u,s,v] = svd(real(csd));
eta = s(2,2)./s(1,1);
u = u'; %orientation is defined in the rows
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function to compute fa from a csd-matrix
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [fa] = csd2fa(csd)
s = svd(real(csd));
ns = rank(real(csd));
s = s(1:ns);
ms = mean(s);
fa = sqrt( (ns./(ns-1)) .* (sum((s-ms).^2))./(sum(s.^2)) );
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function to compute power
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function p = powmethod_lambda1(x, ind);
if nargin==1,
ind = 1:size(x,1);
end
s = svd(x(ind,ind));
p = s(1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function to compute power
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function p = powmethod_trace(x, ind);
if nargin==1,
ind = 1:size(x,1);
end
p = trace(x(ind,ind));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function to compute power
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function p = powmethod_regular(x, ind);
if nargin==1,
ind = 1:size(x,1);
end
p = abs(x(ind,ind));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function to obtain the largest singular value or trace of the
% source CSD matrices resulting from DICS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function s = lambda1(x);
s = svd(x);
s = s(1);
|
github
|
philippboehmsturm/antx-master
|
ft_componentbrowser_old.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_componentbrowser_old.m
| 8,188 |
utf_8
|
42dd5e64a1f8b29bbc4398a22c2aa440
|
function [varargout] = ft_componentbrowser_old(cfg, comp)
% FT_COMPONENTBROWSER plots topography and activations of ICA components
% This function is deprecated, use FT_DATABROWSER with cfg.viewmode='template' instead.
%
% Use as
% ft_componentbrowser_old(cfg, comp)
% where comp is a FieldTrip structure obtained from FT_COMPONENTANALYSIS.
%
% The configuration has the following parameters:
% cfg.comp = a vector with the components to plot (ex. 1:10) (optional)
% cfg.trial = choose which trial to plot first (optional, only one trial)
% cfg.layout = because the output of componentanalysis does not contain
% information on the layout, you need to specify in a variety of ways:
% - you can provide a pre-computed layout structure (see prepare_layout)
% - you can give the name of an ascii layout file with extension *.lay
% - you can give the name of an electrode file
% - you can give an electrode definition, i.e. "elec" structure
% - you can give a gradiometer definition, i.e. "grad" structure
%
% See also FT_COMPONENTANALYSIS
% Copyright (C) 2009, Giovanni Piantoni
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_componentbrowser_old.m 3862 2011-07-14 13:41:01Z jorhor $
warning('FT_COMPONENTBROWSER is deprecated, please use FT_DATABROWSER with cfg.viewmode = ''component'' instead.')
ft_defaults
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Prepare the data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% check that the data comes from componentanalysis
comp = ft_checkdata(comp, 'datatype', 'comp');
% set the defaults:
if ~isfield(cfg, 'comp'), cfg.comp = 1:10; end
if ~isfield(cfg, 'trial'), cfg.trial = 1; end
if numel(cfg.trial) > 1,
warning('componentbrowser:cfg_onetrial', 'only one trial can be plotted at the time');
cfg.trial = cfg.trial(1);
end
% Read or create the layout that will be used for plotting:
[cfg.layout] = ft_prepare_layout(cfg, comp);
% Identify the channels to plot
[labels, cfg.chanidx.lay, cfg.chanidx.comp] = intersect(cfg.layout.label, comp.topolabel); % in case channels are missing
if isempty(cfg.chanidx.lay)
error('componentbrowser:labelmismatch', 'The channel labels in the data do not match the labels of the layout');
end
% fixed variables
cfg.shift = 1.2; % distance between topoplots
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Create figure and assign userdata
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% create figure and axes
cfg.h = figure('uni','pix', 'name', 'componentbrowser', 'vis', 'off', 'numbertitle', 'off');
cfg.axis = axes;
hold on
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Buttons and Callbacks
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% scroll components
uicontrol(cfg.h,'uni','pix','pos',[105 5 25 18],'str','-',...
'call',{@plottopography, comp});
cfg.ncomp = uicontrol(cfg.h,'sty','text','uni','pix','pos',[130 5 150 18],...
'str',['comp n.' num2str(cfg.comp(1)) '-' num2str(cfg.comp(end))]);
uicontrol(cfg.h,'uni','pix','pos',[280 5 25 18],'str','+',...
'call',{@plottopography, comp});
% scroll trials
uicontrol(cfg.h,'uni','pix','pos',[330 5 25 18],'str','<<',...
'call',{@plotactivation, comp});
uicontrol(cfg.h,'uni','pix','pos',[355 5 25 18],'str', '<',...
'call',{@plotactivation, comp});
cfg.ntrl = uicontrol(cfg.h,'sty','text','uni','pix','pos',[380 5 70 18],...
'str',['trial n.' num2str(cfg.trial)]);
uicontrol(cfg.h,'uni','pix','pos',[450 5 25 18],'str', '>',...
'call',{@plotactivation, comp});
uicontrol(cfg.h,'uni','pix','pos',[475 5 25 18],'str','>>',...
'call',{@plotactivation, comp});
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% First callback and final adjustments
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% first call of the two plotting functions
plottopography([], cfg, comp)
plotactivation([], cfg, comp)
% final adjustments
set(cfg.h, 'vis', 'on')
axis equal
axis off
hold off
% the (optional) output is the handle
if nargout == 1;
varargout{1} = cfg.h;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% PLOTTOPOGRAPHY
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function plottopography(h, cfg, comp)
% now plottopography is not associated with a callback, but it might in
% the future
if isempty(h) % when called in isolation
set(cfg.h, 'user', cfg)
else
cfg = get(get(h, 'par'), 'user');
% which button has been pressed
if intersect(h, findobj(cfg.h, 'str', '+'))
cfg.comp = cfg.comp + numel(cfg.comp);
if cfg.comp(end) > size(comp.label,1)
cfg.comp = cfg.comp - (cfg.comp(end) - size(comp.label,1));
end
elseif intersect(h, findobj(cfg.h, 'str', '-'))
cfg.comp = cfg.comp - numel(cfg.comp);
if cfg.comp(1) < 1
cfg.comp = cfg.comp - cfg.comp(1) + 1;
end
end
end
set(cfg.ncomp, 'str', ['comp n.' num2str(cfg.comp(1)) '-' num2str(cfg.comp(end))])
drawnow
delete(findobj(cfg.h, 'tag', 'comptopo'))
cnt = 0;
for k = cfg.comp
cnt = cnt + 1;
% write number of the component on the left
h_text(cnt) = ft_plot_text(-2.5, -cnt*cfg.shift, ['n. ' num2str(cfg.comp(cnt))]);
% plot only topography (*and* layout)
ft_plot_topo(cfg.layout.pos(cfg.chanidx.lay,1), cfg.layout.pos(cfg.chanidx.lay,2), ...
comp.topo(cfg.chanidx.comp, k)./max(abs(comp.topo(cfg.chanidx.comp, k))), ... % for proper scaling
'hpos', -1, 'vpos', -cnt*cfg.shift, 'mask', cfg.layout.mask, ...
'interplim','mask', 'outline',cfg.layout.outline);
end
h_topo = findobj(cfg.h, 'type', 'surface');
set(h_text, 'tag', 'comptopo')
set(h_topo, 'tag', 'comptopo')
% in the colorbar, green should be zero
set(cfg.axis, 'clim', [-1 1])
plotactivation([], cfg, comp)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% PLOTACTIVATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function plotactivation(h, cfg, comp)
% plotactivation can be called in isolation or by buttondownfcn
% cfg is stored in 'user' of the main figure
if isempty(h) % when called in isolation
set(cfg.h, 'user', cfg)
else
cfg = get(get(h, 'par'), 'user');
% which button has been pressed
if intersect(h, findobj(cfg.h, 'str', '>>'))
cfg.trial = cfg.trial + 10;
if cfg.trial > size(comp.trial,2)
cfg.trial = size(comp.trial,2);
end
elseif intersect(h, findobj(cfg.h, 'str', '>'))
cfg.trial = cfg.trial + 1;
if cfg.trial > size(comp.trial,2)
cfg.trial = size(comp.trial,2);
end
elseif intersect(h, findobj(cfg.h, 'str', '<'))
cfg.trial = cfg.trial - 1;
if cfg.trial < 1
cfg.trial = 1;
end
elseif intersect(h, findobj(cfg.h, 'str', '<<'))
cfg.trial = cfg.trial - 10;
if cfg.trial < 1
cfg.trial = 1;
end
end
end
set(cfg.ntrl,'str',['trial n. ' num2str(cfg.trial)])
drawnow
delete(findobj(cfg.h,'tag', 'activations'));
hold on
cnt = 0;
for k = cfg.comp
cnt = cnt + 1;
% plot the activations
h_act(cnt) = ft_plot_vector(comp.trial{cfg.trial}(k,:), 'hpos', 6 , 'vpos', -cnt*cfg.shift, 'width', 12, 'height', 1, 'box', true);
end
h_inv = plot(6+12+1, -cnt*cfg.shift, '.'); %
set(h_inv, 'vis', 'off')
set(h_act, 'tag', 'activations')
set(cfg.h, 'user', cfg)
hold off
|
github
|
philippboehmsturm/antx-master
|
ft_freqanalysis_mvar.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_freqanalysis_mvar.m
| 4,454 |
utf_8
|
fa9d69e0cc7817d01bd2e89dccc5cfe6
|
function [freq] = ft_freqanalysis_mvar(cfg, data)
% FT_FREQANALYSIS_MVAR performs frequency analysis on
% mvar data.
%
% Use as
% [freq] = ft_freqanalysis(cfg, data)
% Copyright (C) 2009, Jan-Mathijs Schoffelen
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_freqanalysis_mvar.m 3538 2011-05-13 06:48:41Z jansch $
if ~isfield(cfg, 'channel'), cfg.channel = 'all'; end
if ~isfield(cfg, 'channelcmb'), cfg.channelcmb = {'all' 'all'}; end
if ~isfield(cfg, 'foi'), cfg.foi = 'all'; end
if ~isfield(cfg, 'keeptrials'), cfg.keeptrials = 'no'; end
if ~isfield(cfg, 'jackknife'), cfg.jackknife = 'no'; end
if ~isfield(cfg, 'keeptapers'), cfg.keeptapers = 'yes'; end
if ~isfield(cfg, 'feedback'), cfg.feedback = 'none'; end
if strcmp(cfg.foi, 'all'),
cfg.foi = (0:1:data.fsampleorig/2);
end
cfg.channel = ft_channelselection(cfg.channel, data.label);
%cfg.channelcmb = channelcombination(cfg.channelcmb, data.label);
%keeprpt = strcmp(cfg.keeptrials, 'yes');
%keeptap = strcmp(cfg.keeptapers, 'yes');
%dojack = strcmp(cfg.jackknife, 'yes');
%dozscore = strcmp(cfg.zscore, 'yes');
%if ~keeptap, error('not keeping tapers is not possible yet'); end
%if dojack && keeprpt, error('you cannot simultaneously keep trials and do jackknifing'); end
nfoi = length(cfg.foi);
if isfield(data, 'time')
ntoi = numel(data.time);
else
ntoi = 1;
end
nlag = size(data.coeffs,3); %change in due course
chanindx = match_str(data.label, cfg.channel);
nchan = length(chanindx);
label = data.label(chanindx);
%---allocate memory
h = complex(zeros(nchan, nchan, nfoi, ntoi), zeros(nchan, nchan, nfoi, ntoi));
a = complex(zeros(nchan, nchan, nfoi, ntoi), zeros(nchan, nchan, nfoi, ntoi));
crsspctrm = complex(zeros(nchan, nchan, nfoi, ntoi), zeros(nchan, nchan, nfoi, ntoi));
%FIXME build in repetitions
%---loop over the tois
ft_progress('init', cfg.feedback, 'computing MAR-model based TFR');
for j = 1:ntoi
ft_progress(j/ntoi, 'processing timewindow %d from %d\n', j, ntoi);
%---compute transfer function
ar = reshape(data.coeffs(:,:,:,j), [nchan nchan*nlag]);
[h(:,:,:,j), a(:,:,:,j)] = ar2h(ar, cfg.foi, data.fsampleorig);
%---compute cross-spectra
nc = data.noisecov(:,:,j);
for k = 1:nfoi
tmph = h(:,:,k,j);
crsspctrm(:,:,k,j) = tmph*nc*tmph';
end
end
ft_progress('close');
%---create output-structure
freq = [];
freq.label = label;
freq.freq = cfg.foi;
%freq.cumtapcnt= ones(ntrl, 1)*ntap;
if ntoi>1
freq.time = data.time;
freq.dimord = 'chan_chan_freq_time';
else
freq.dimord = 'chan_chan_freq';
end
freq.transfer = h;
%freq.itransfer = a;
freq.noisecov = data.noisecov;
freq.crsspctrm = crsspctrm;
freq.dof = data.dof;
try
cfg.previous = data.cfg;
end
freq.cfg = cfg;
%---SUBFUNCTION to compute transfer-function from ar-parameters
function [h, zar] = ar2h(ar, foi, fsample)
nchan = size(ar,1);
ncmb = nchan*nchan;
nfoi = length(foi);
%---z-transform frequency axis
zfoi = exp(-2.*pi.*1i.*(foi./fsample));
%---reorganize the ar-parameters
ar = reshape(ar, [ncmb size(ar,2)./nchan]);
ar = fliplr([reshape(eye(nchan), [ncmb 1]) -ar]);
zar = complex(zeros(ncmb, nfoi), zeros(ncmb, nfoi));
for k = 1:ncmb
zar(k,:) = polyval(ar(k,:),zfoi);
end
zar = reshape(zar, [nchan nchan nfoi]);
h = zeros(size(zar));
for k = 1:nfoi
h(:,:,k) = inv(zar(:,:,k));
end
h = sqrt(2).*h; %account for the negative frequencies, normalization necessary for
%comparison with non-parametric (fft based) results in fieldtrip
%FIXME probably the normalization for the zero Hz bin is incorrect
zar = zar./sqrt(2);
|
github
|
philippboehmsturm/antx-master
|
ft_interactiverealign.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_interactiverealign.m
| 15,069 |
utf_8
|
aee4683cbadc909e326c438c1bbf57fc
|
function cfg = ft_interactiverealign(cfg)
% FT_INTERACTIVEREALIGN interactively rotates, scales and translates
% electrode positions to template electrode positions or towards
% the head surface.
%
% Use as
% [cfg] = ft_interactiverealign(cfg)
%
% Required configuration options:
% cfg.individual.vol
% cfg.individual.elec
% cfg.individual.grad
% cfg.individual.headshape
% cfg.individual.headshapestyle = 'vertex' (default), 'surface' or 'both'
% cfg.individual.volstyle = 'edge' (default), 'surface' or 'both'
%
% cfg.template.vol
% cfg.template.elec
% cfg.template.grad
% cfg.template.headshape
% cfg.template.headshapestyle = 'surface' (default), 'vertex' or 'both'
% cfg.individual.volstyle = 'surface' (default), 'edge' or 'both'
%
% See also FT_VOLUMEREALIGN, FT_ELECTRODEREALIGN, FT_READ_SENS, FT_READ_VOL, FT_READ_HEADSHAPE
% Copyright (C) 2008, Vladimir Litvak
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_interactiverealign.m 3710 2011-06-16 14:04:19Z eelspa $
ft_defaults
% record start time and total processing time
ftFuncTimer = tic();
ftFuncClock = clock();
% check if the input cfg is valid for this function
cfg = ft_checkconfig(cfg, 'trackconfig', 'on');
cfg = ft_checkconfig(cfg, 'required', {'individual', 'template'});
if ~isfield(cfg.individual, 'vol'), cfg.individual.vol = []; end
if ~isfield(cfg.individual, 'elec'), cfg.individual.elec = []; end
if ~isfield(cfg.individual, 'grad'), cfg.individual.grad = []; end
if ~isfield(cfg.individual, 'headshape'), cfg.individual.headshape = []; end
if ~isfield(cfg.individual, 'headshapestyle'), cfg.individual.headshapestyle = 'vertex'; end
if ~isfield(cfg.individual, 'volstyle'), cfg.individual.volstyle = 'edge'; end
if ~isfield(cfg.template, 'vol'), cfg.template.vol = []; end
if ~isfield(cfg.template, 'elec'), cfg.template.elec = []; end
if ~isfield(cfg.template, 'grad'), cfg.template.grad = []; end
if ~isfield(cfg.template, 'headshape'), cfg.template.headshape = []; end
if ~isfield(cfg.template, 'headshapestyle'), cfg.template.headshapestyle = 'surface'; end
if ~isfield(cfg.template, 'volstyle'), cfg.template.volstyle = 'surface'; end
template = cfg.template;
individual = cfg.individual;
if ~isempty(template.headshape)
if ~isfield(template.headshape, 'tri') || isempty(template.headshape.tri)
template.headshape.tri = projecttri(template.headshape.pnt);
end
end
if ~isempty(individual.headshape) && isfield(individual.headshape, 'pnt') && ...
~isempty(individual.headshape.pnt)
if ~isfield(individual.headshape, 'tri') || isempty(individual.headshape.tri)
individual.headshape.tri = projecttri(individual.headshape.pnt);
end
end
% open a figure
fig = figure;
% add the data to the figure
set(fig, 'CloseRequestFcn', @cb_close);
setappdata(fig, 'individual', individual);
setappdata(fig, 'template', template);
setappdata(fig, 'transform', eye(4));
% add the GUI elements
cb_creategui(gca);
cb_redraw(gca);
rotate3d on
waitfor(fig);
% get the data from the figure that was left behind as global variable
% FIXME pass this as appdata
global norm
tmp = norm;
clear global norm
norm = tmp;
clear tmp
% get the output cfg
cfg = ft_checkconfig(cfg, 'trackconfig', 'off', 'checksize', 'yes');
% add version information to the configuration
cfg.version.name = mfilename('fullpath');
cfg.version.id = '$Id: ft_interactiverealign.m 3710 2011-06-16 14:04:19Z eelspa $';
% add information about the Matlab version used to the configuration
cfg.callinfo.matlab = version();
% add information about the function call to the configuration
cfg.callinfo.proctime = toc(ftFuncTimer);
cfg.callinfo.calltime = ftFuncClock;
cfg.callinfo.user = getusername();
% remember the transform
cfg.m = norm.m;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% some simple SUBFUNCTIONs that facilitate 3D plotting
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function h = my_plot3(xyz, varargin)
h = plot3(xyz(:,1), xyz(:,2), xyz(:,3), varargin{:});
function h = my_text3(xyz, varargin)
h = text(xyz(:,1), xyz(:,2), xyz(:,3), varargin{:});
function my_line3(xyzB, xyzE, varargin)
for i=1:size(xyzB,1)
line([xyzB(i,1) xyzE(i,1)], [xyzB(i,2) xyzE(i,2)], [xyzB(i,3) xyzE(i,3)], varargin{:})
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION to layout a moderately complex graphical user interface
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function h = layoutgui(fig, geometry, position, style, string, value, tag, callback);
horipos = geometry(1); % lower left corner of the GUI part in the figure
vertpos = geometry(2); % lower left corner of the GUI part in the figure
width = geometry(3); % width of the GUI part in the figure
height = geometry(4); % height of the GUI part in the figure
horidist = 0.05;
vertdist = 0.05;
options = {'units', 'normalized', 'HorizontalAlignment', 'center'}; % 'VerticalAlignment', 'middle'
Nrow = size(position,1);
h = cell(Nrow,1);
for i=1:Nrow
if isempty(position{i})
continue;
end
position{i} = position{i} ./ sum(position{i});
Ncol = size(position{i},2);
ybeg = (Nrow-i )/Nrow + vertdist/2;
yend = (Nrow-i+1)/Nrow - vertdist/2;
for j=1:Ncol
xbeg = sum(position{i}(1:(j-1))) + horidist/2;
xend = sum(position{i}(1:(j ))) - horidist/2;
pos(1) = xbeg*width + horipos;
pos(2) = ybeg*height + vertpos;
pos(3) = (xend-xbeg)*width;
pos(4) = (yend-ybeg)*height;
h{i}{j} = uicontrol(fig, ...
options{:}, ...
'position', pos, ...
'style', style{i}{j}, ...
'string', string{i}{j}, ...
'tag', tag{i}{j}, ...
'value', value{i}{j}, ...
'callback', callback{i}{j} ...
);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_creategui(hObject, eventdata, handles);
% define the position of each GUI element
position = {
[2 1 1 1]
[2 1 1 1]
[2 1 1 1]
[1]
[1]
[1]
[1]
[1 1]
};
% define the style of each GUI element
style = {
{'text' 'edit' 'edit' 'edit'}
{'text' 'edit' 'edit' 'edit'}
{'text' 'edit' 'edit' 'edit'}
{'pushbutton'}
{'pushbutton'}
{'toggle'}
{'toggle'}
{'text' 'edit'}
};
% define the descriptive string of each GUI element
string = {
{'rotate' 0 0 0}
{'translate' 0 0 0}
{'scale' 1 1 1}
{'redisplay'}
{'apply'}
{'toggle grid'}
{'toggle axes'}
{'alpha' 0.7}
};
% define the value of each GUI element
value = {
{[] [] [] []}
{[] [] [] []}
{[] [] [] []}
{[]}
{[]}
{0}
{0}
{[] []}
};
% define a tag for each GUI element
tag = {
{'' 'rx' 'ry' 'rz'}
{'' 'tx' 'ty' 'tz'}
{'' 'sx' 'sy' 'sz'}
{''}
{''}
{'toggle grid'}
{'toggle axes'}
{'' 'alpha'}
};
% define the callback function of each GUI element
callback = {
{[] @cb_redraw @cb_redraw @cb_redraw}
{[] @cb_redraw @cb_redraw @cb_redraw}
{[] @cb_redraw @cb_redraw @cb_redraw}
{@cb_redraw}
{@cb_apply}
{@cb_redraw}
{@cb_redraw}
{[] @cb_redraw}
};
fig = get(hObject, 'parent');
layoutgui(fig, [0.7 0.05 0.25 0.50], position, style, string, value, tag, callback);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_redraw(hObject, eventdata, handles)
fig = get(hObject, 'parent');
individual = getappdata(fig, 'individual');
template = getappdata(fig, 'template');
% get the transformation details
rx = str2num(get(findobj(fig, 'tag', 'rx'), 'string'));
ry = str2num(get(findobj(fig, 'tag', 'ry'), 'string'));
rz = str2num(get(findobj(fig, 'tag', 'rz'), 'string'));
tx = str2num(get(findobj(fig, 'tag', 'tx'), 'string'));
ty = str2num(get(findobj(fig, 'tag', 'ty'), 'string'));
tz = str2num(get(findobj(fig, 'tag', 'tz'), 'string'));
sx = str2num(get(findobj(fig, 'tag', 'sx'), 'string'));
sy = str2num(get(findobj(fig, 'tag', 'sy'), 'string'));
sz = str2num(get(findobj(fig, 'tag', 'sz'), 'string'));
R = rotate ([rx ry rz]);
T = translate([tx ty tz]);
S = scale ([sx sy sz]);
H = S * T * R;
axis vis3d; cla
xlabel('x')
ylabel('y')
zlabel('z')
hold on
% the "individual" struct is a local copy, so it is safe to change it here
if ~isempty(individual.vol)
individual.vol = ft_transform_vol(H, individual.vol);
end
if ~isempty(individual.elec)
individual.elec = ft_transform_sens(H, individual.elec);
end
if ~isempty(individual.grad)
individual.grad = ft_transform_sens(H, individual.grad);
end
if ~isempty(individual.headshape)
individual.headshape = ft_transform_headshape(H, individual.headshape);
end
if ~isempty(template.elec)
hs = triplot(template.elec.pnt, [], [], 'nodes');
set(hs, 'MarkerSize', 10);
set(hs, 'Color', 'b');
if isfield(template.elec, 'line')
hs = triplot(template.elec.pnt, template.elec.line, [], 'edges');
try, set(hs, 'MarkerEdgeColor', 'b'); end
end
end
if ~isempty(individual.elec)
hs = triplot(individual.elec.pnt, [], [], 'nodes');
set(hs, 'MarkerSize', 10);
set(hs, 'Color', 'r');
if isfield(individual.elec, 'line')
hs = triplot(individual.elec.pnt, elec.line, [], 'edges');
try, set(hs, 'MarkerEdgeColor', 'r'); end
end
end
if ~isempty(template.grad)
hs = triplot(template.grad.pnt, [], [], 'nodes');
set(hs, 'MarkerSize', 10);
set(hs, 'Color', 'b');
% FIXME also plot lines?
end
if ~isempty(individual.grad)
hs = triplot(individual.grad.pnt, [], [], 'nodes');
set(hs, 'MarkerSize', 10);
set(hs, 'Color', 'r');
% FIXME also plot lines?
end
if ~isempty(template.vol)
% FIXME this only works for boundary element models
for i = 1:numel(template.vol.bnd)
if strcmp(template.volstyle, 'edge') || ...
strcmp(template.volstyle, 'both')
hs = triplot(template.vol.bnd(i).pnt, template.vol.bnd(i).tri, [], 'edges');
try, set(hs, 'EdgeColor', 'b'); end
end
if strcmp(template.volstyle, 'surface') || ...
strcmp(template.volstyle, 'both')
hs = triplot(template.vol.bnd(i).pnt, template.vol.bnd(i).tri, [], 'faces_blue');
end
end
end
if ~isempty(individual.vol)
% FIXME this only works for boundary element models
for i = 1:numel(individual.vol.bnd)
if strcmp(individual.volstyle, 'edge') || ...
strcmp(individual.volstyle, 'both')
hs = triplot(individual.vol.bnd(i).pnt, individual.vol.bnd(i).tri, [], 'edges');
try, set(hs, 'EdgeColor', 'r'); end
end
if strcmp(individual.volstyle, 'surface') || ...
strcmp(individual.volstyle, 'both')
hs = triplot(individual.vol.bnd(i).pnt, individual.vol.bnd(i).tri, [], 'faces_red');
end
end
end
if ~isempty(template.headshape)
if isfield(template.headshape, 'pnt') && ~isempty(template.headshape.pnt)
if strcmp(template.headshapestyle, 'surface') || ...
strcmp(template.headshapestyle, 'both')
triplot(template.headshape.pnt, template.headshape.tri, [], 'faces_blue');
alpha(str2num(get(findobj(fig, 'tag', 'alpha'), 'string')));
end
if strcmp(template.headshapestyle, 'vertex') || ...
strcmp(template.headshapestyle, 'both')
hs = triplot(template.headshape.pnt, [], [], 'nodes');
set(hs, 'Color', 'b');
end
end
if isfield(template.headshape, 'fid') && ~isempty(template.headshape.fid.pnt)
triplot(template.headshape.fid.pnt, [], [], 'nodes_blue');
end
end
if ~isempty(individual.headshape)
if isfield(individual.headshape, 'pnt') && ~isempty(individual.headshape.pnt)
if strcmp(individual.headshapestyle, 'surface') || ...
strcmp(individual.headshapestyle, 'both')
triplot(individual.headshape.pnt, individual.headshape.tri, [], 'faces_red');
alpha(str2num(get(findobj(fig, 'tag', 'alpha'), 'string')));
end
if strcmp(individual.headshapestyle, 'vertex') || ...
strcmp(individual.headshapestyle, 'both')
hs = triplot(individual.headshape.pnt, [], [], 'nodes');
set(hs, 'Color', 'r');
end
end
if isfield(individual.headshape, 'fid') && ~isempty(individual.headshape.fid.pnt)
triplot(individual.headshape.fid.pnt, [], [], 'nodes_red');
end
end
if get(findobj(fig, 'tag', 'toggle axes'), 'value')
axis on
else
axis off
end
if get(findobj(fig, 'tag', 'toggle grid'), 'value')
grid on
else
grid off
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_apply(hObject, eventdata, handles);
fig = get(hObject, 'parent');
transform = getappdata(fig, 'transform');
% get the transformation details
rx = str2num(get(findobj(fig, 'tag', 'rx'), 'string'));
ry = str2num(get(findobj(fig, 'tag', 'ry'), 'string'));
rz = str2num(get(findobj(fig, 'tag', 'rz'), 'string'));
tx = str2num(get(findobj(fig, 'tag', 'tx'), 'string'));
ty = str2num(get(findobj(fig, 'tag', 'ty'), 'string'));
tz = str2num(get(findobj(fig, 'tag', 'tz'), 'string'));
sx = str2num(get(findobj(fig, 'tag', 'sx'), 'string'));
sy = str2num(get(findobj(fig, 'tag', 'sy'), 'string'));
sz = str2num(get(findobj(fig, 'tag', 'sz'), 'string'));
R = rotate ([rx ry rz]);
T = translate([tx ty tz]);
S = scale ([sx sy sz]);
H = S * T * R;
transform = H * transform;
set(findobj(fig, 'tag', 'rx'), 'string', 0);
set(findobj(fig, 'tag', 'ry'), 'string', 0);
set(findobj(fig, 'tag', 'rz'), 'string', 0);
set(findobj(fig, 'tag', 'tx'), 'string', 0);
set(findobj(fig, 'tag', 'ty'), 'string', 0);
set(findobj(fig, 'tag', 'tz'), 'string', 0);
set(findobj(fig, 'tag', 'sx'), 'string', 1);
set(findobj(fig, 'tag', 'sy'), 'string', 1);
set(findobj(fig, 'tag', 'sz'), 'string', 1);
setappdata(fig, 'transform', transform);
cb_redraw(hObject);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_close(hObject, eventdata, handles);
% make the current transformation permanent and subsequently allow deleting the figure
cb_apply(gca);
% get the updated electrode from the figure
fig = hObject;
% hmmm, this is ugly
global norm
norm.m = getappdata(fig, 'transform');
set(fig, 'CloseRequestFcn', @delete);
delete(fig);
|
github
|
philippboehmsturm/antx-master
|
ft_topoplotER.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_topoplotER.m
| 41,447 |
utf_8
|
2ed7fe6daff435d1ed7ef28c7c343eb9
|
function [cfg] = ft_topoplotER(cfg, varargin)
% FT_TOPOPLOTER plots the topographic distribution of 2-Dimensional ft_datatypes as
% event-related fields (ERF), potentials (ERP), the powerspectrum or coherence spectum
% that was computed using the FT_TIMELOCKANALYSIS, FT_TIMELOCKGRANDAVERAGE, FT_FREQANALYSIS or
% FT_FREQDESCRIPTIVES functions, as a 2-D circular view (looking down at the top of the head).
%
% Use as:
% ft_topoplotER(cfg, data)
%
% cfg.xparam = first dimension in data in which a selection is made
% 'time' or 'freq' (default depends on data.dimord)
% cfg.zparam = field that contains the data to be plotted as color
% 'avg', 'powspctrm' or 'cohspctrm' (default depends on data.dimord)
% cfg.xlim = 'maxmin' or [xmin xmax] (default = 'maxmin')
% cfg.zlim = 'maxmin', 'maxabs' or [zmin zmax] (default = 'maxmin')
% cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), see FT_CHANNELSELECTION for details
% cfg.refchannel = name of reference channel for visualising connectivity, can be 'gui'
% cfg.baseline = 'yes','no' or [time1 time2] (default = 'no'), see FT_TIMELOCKBASELINE or FT_FREQBASELINE
% cfg.baselinetype = 'absolute' or 'relative' (default = 'absolute')
% cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all')
% cfg.colormap = any sized colormap, see COLORMAP
% cfg.marker = 'on', 'labels', 'numbers', 'off'
% cfg.markersymbol = channel marker symbol (default = 'o')
% cfg.markercolor = channel marker color (default = [0 0 0] (black))
% cfg.markersize = channel marker size (default = 2)
% cfg.markerfontsize = font size of channel labels (default = 8 pt)
% cfg.highlight = 'on', 'labels', 'numbers', 'off'
% cfg.highlightchannel = Nx1 cell-array with selection of channels, or vector containing channel indices see FT_CHANNELSELECTION
% cfg.highlightsymbol = highlight marker symbol (default = 'o')
% cfg.highlightcolor = highlight marker color (default = [0 0 0] (black))
% cfg.highlightsize = highlight marker size (default = 6)
% cfg.highlightfontsize = highlight marker size (default = 8)
% cfg.hotkeys = enables hotkeys (up/down arrows) for dynamic colorbar adjustment
% cfg.colorbar = 'yes'
% 'no' (default)
% 'North' inside plot box near top
% 'South' inside bottom
% 'East' inside right
% 'West' inside left
% 'NorthOutside' outside plot box near top
% 'SouthOutside' outside bottom
% 'EastOutside' outside right
% 'WestOutside' outside left
% cfg.interplimits = limits for interpolation (default = 'head')
% 'electrodes' to furthest electrode
% 'head' to edge of head
% cfg.interpolation = 'linear','cubic','nearest','v4' (default = 'v4') see GRIDDATA
% cfg.style = plot style (default = 'both')
% 'straight' colormap only
% 'contour' contour lines only
% 'both' (default) both colormap and contour lines
% 'fill' constant color between lines
% 'blank' only the head shape
% cfg.gridscale = scaling grid size (default = 67)
% determines resolution of figure
% cfg.shading = 'flat' 'interp' (default = 'flat')
% cfg.comment = string 'no' 'auto' or 'xlim' (default = 'auto')
% 'auto': date, xparam and zparam limits are printed
% 'xlim': only xparam limits are printed
% cfg.commentpos = string or two numbers, position of comment (default 'leftbottom')
% 'lefttop' 'leftbottom' 'middletop' 'middlebottom' 'righttop' 'rightbottom'
% 'title' to place comment as title
% 'layout' to place comment as specified for COMNT in layout
% [x y] coordinates
% cfg.interactive = Interactive plot 'yes' or 'no' (default = 'no')
% In a interactive plot you can select areas and produce a new
% interactive plot when a selected area is clicked. Multiple areas
% can be selected by holding down the SHIFT key.
% cfg.layout = specification of the layout, see below
%
% The layout defines how the channels are arranged. You can specify the
% layout in a variety of ways:
% - you can provide a pre-computed layout structure (see prepare_layout)
% - you can give the name of an ascii layout file with extension *.lay
% - you can give the name of an electrode file
% - you can give an electrode definition, i.e. "elec" structure
% - you can give a gradiometer definition, i.e. "grad" structure
% If you do not specify any of these and the data structure contains an
% electrode or gradiometer structure, that will be used for creating a
% layout. If you want to have more fine-grained control over the layout
% of the subplots, you should create your own layout file.
%
% To facilitate data-handling and distributed computing with the peer-to-peer
% module, this function has the following option:
% cfg.inputfile = ...
% If you specify this option the input data will be read from a *.mat
% file on disk. This mat files should contain only a single variable named 'data',
% corresponding to the input structure. For this particular function, the input should be
% structured as a cell array.
%
% See also:
% FT_TOPOPLOTTFR, FT_TOPOPLOTIC, FT_SINGLEPLOTER, FT_MULTIPLOTER, FT_PREPARE_LAYOUT
% Undocumented local options:
% The following additional cfg parameters are used when plotting 3-dimensional
% data (i.e. when ft_topoplotTFR calls ft_topoplotER):
% cfg.yparam field to be plotted on y-axis
% cfg.ylim 'maxmin' or [ymin ymax] (default = 'maxmin')
% It is possible to use multiple highlight-selections (e.g.: multiple statistical clusters of channels)
% To do this, all the content of the highlight-options (including cfg.highlight) should be placed in a cell-array
% (even if the normal content was already in a cell-array). Specific marker settings (e.g. color, size) are defaulted when
% not present.
% Example (3 selections):
% cfg.highlight = {'labels', 'labels', 'numbers'}
% cfg.highlightchannel = {{'MZF03','MZC01','MRT54'}, [1:5], 'C*'}
% cfg.highlightsymbol = {'o',[],'+'} % the empty option will be defaulted
% cfg.highlightcolor = {'r',[0 0 1]}; % the missing option will be defaulted
% cfg.highlightsize = []; % will be set to default, as will the missing cfg.highlightfontsize
%
% Other options:
% cfg.labeloffset (offset of labels to their marker, default = 0.005)
% cfg.inputfile = one can specifiy preanalysed saved data as input
% The data should be provided in a cell array
% This function depends on FT_TIMELOCKBASELINE which has the following options:
% cfg.baseline, documented
% cfg.channel
% cfg.baselinewindow
%
% This function depends on FT_FREQBASELINE which has the following options:
% cfg.baseline, documented
% cfg.baselinetype
% Copyright (C) 2005-2006, F.C. Donders Centre
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_topoplotER.m 3734 2011-06-29 08:14:36Z jorhor $
ft_defaults
cfg = ft_checkconfig(cfg, 'trackconfig', 'on');
cfg = ft_checkconfig(cfg, 'unused', {'cohtargetchannel'});
cfg = ft_checkconfig(cfg, 'renamed', {'cohrefchannel' 'refchannel'});
% set default for inputfile
if ~isfield(cfg, 'inputfile'), cfg.inputfile = []; end
hasdata = nargin>1;
hasinputfile = ~isempty(cfg.inputfile);
Ndata = numel(varargin);
if isnumeric(varargin{end})
Ndata = Ndata - 1;
indx = varargin{end};
else
indx = 1;
end
if Ndata>1 && ~isnumeric(varargin{end})
for k=1:Ndata
if k>1
% create a new figure for the additional input arguments
figure
end
ft_topoplotER(cfg, varargin{1:Ndata}, indx);
indx = indx + 1;
end
return
end
if hasdata && hasinputfile
error('cfg.inputfile should not be used in conjunction with giving input data to this function');
end
if hasdata
data = varargin{indx};
elseif hasinputfile
if iscell(cfg.inputfile), cfg.inputfile = cfg.inputfile{1}; end
data = loadvar(cfg.inputfile, 'data');
if isfield(cfg, 'interactive') && strcmp(cfg.interactive, 'yes'),
warning('switching off interactive mode, this is not supported when loading an inputfile from disk');
end
end
% For backward compatibility with old data structures:
%data = ft_checkdata(data, 'datatype', {'timelock', 'freq', 'comp'});
% check for option-values to be renamed
cfg = ft_checkconfig(cfg, 'renamedval', {'electrodes', 'dotnum', 'numbers'});
cfg = ft_checkconfig(cfg, 'renamedval', {'zlim', 'absmax', 'maxabs'});
cfg = ft_checkconfig(cfg, 'renamedval', {'matrixside', 'feedforward', 'outflow'});
cfg = ft_checkconfig(cfg, 'renamedval', {'matrixside', 'feedback', 'inflow'});
% check for renamed options
cfg = ft_checkconfig(cfg, 'renamed', {'electrodes', 'marker'});
cfg = ft_checkconfig(cfg, 'renamed', {'emarker', 'markersymbol'});
cfg = ft_checkconfig(cfg, 'renamed', {'ecolor', 'markercolor'});
cfg = ft_checkconfig(cfg, 'renamed', {'emarkersize', 'markersize'});
cfg = ft_checkconfig(cfg, 'renamed', {'efontsize', 'markerfontsize'});
cfg = ft_checkconfig(cfg, 'renamed', {'hlmarker', 'highlightsymbol'});
cfg = ft_checkconfig(cfg, 'renamed', {'hlcolor', 'highlightcolor'});
cfg = ft_checkconfig(cfg, 'renamed', {'hlmarkersize', 'highlightsize'});
cfg = ft_checkconfig(cfg, 'renamed', {'maplimits', 'zlim'});
% old ft_checkconfig adapted partially from topoplot.m (backwards backwards compatability)
cfg = ft_checkconfig(cfg, 'renamed', {'grid_scale', 'gridscale'});
cfg = ft_checkconfig(cfg, 'renamed', {'interpolate', 'interpolation'});
cfg = ft_checkconfig(cfg, 'renamed', {'numcontour', 'contournum'});
cfg = ft_checkconfig(cfg, 'renamed', {'electrod', 'marker'});
cfg = ft_checkconfig(cfg, 'renamed', {'electcolor', 'markercolor'});
cfg = ft_checkconfig(cfg, 'renamed', {'emsize', 'markersize'});
cfg = ft_checkconfig(cfg, 'renamed', {'efsize', 'markerfontsize'});
cfg = ft_checkconfig(cfg, 'renamed', {'headlimits', 'interplimits'});
% check for forbidden options
cfg = ft_checkconfig(cfg, 'forbidden', {'hllinewidth'});
cfg = ft_checkconfig(cfg, 'forbidden', {'headcolor'});
cfg = ft_checkconfig(cfg, 'forbidden', {'hcolor'});
cfg = ft_checkconfig(cfg, 'forbidden', {'hlinewidth'});
cfg = ft_checkconfig(cfg, 'forbidden', {'contcolor'});
cfg = ft_checkconfig(cfg, 'forbidden', {'outline'});
cfg = ft_checkconfig(cfg, 'forbidden', {'highlightfacecolor'});
cfg = ft_checkconfig(cfg, 'forbidden', {'showlabels'});
cfg = ft_checkconfig(cfg, 'forbidden', {'hllinewidth'});
% Set other config defaults:
cfg.xlim = ft_getopt(cfg, 'xlim', 'maxmin');
cfg.ylim = ft_getopt(cfg, 'ylim', 'maxmin');
cfg.zlim = ft_getopt(cfg, 'zlim', 'maxmin');
cfg.style = ft_getopt(cfg, 'style', 'both');
cfg.gridscale = ft_getopt(cfg, 'gridscale', 67);
cfg.interplimits = ft_getopt(cfg, 'interplimits', 'head');
cfg.interpolation = ft_getopt(cfg, 'interpolation', 'v4');
cfg.contournum = ft_getopt(cfg, 'contournum', 6);
cfg.colorbar = ft_getopt(cfg, 'colorbar', 'no');
cfg.shading = ft_getopt(cfg, 'shading', 'flat');
cfg.comment = ft_getopt(cfg, 'comment', 'auto');
cfg.commentpos = ft_getopt(cfg, 'commentpos', 'leftbottom');
cfg.fontsize = ft_getopt(cfg, 'fontsize', 8);
cfg.baseline = ft_getopt(cfg, 'baseline', 'no'); %to avoid warning in timelock/freqbaseline
cfg.trials = ft_getopt(cfg, 'trials', 'all');
cfg.interactive = ft_getopt(cfg, 'interactive', 'no');
cfg.hotkeys = ft_getopt(cfg, 'hotkeys', 'no');
cfg.renderer = ft_getopt(cfg, 'renderer', []); % matlab sets the default
cfg.marker = ft_getopt(cfg, 'marker', 'on');
cfg.markersymbol = ft_getopt(cfg, 'markersymbol', 'o');
cfg.markercolor = ft_getopt(cfg, 'markercolor', [0 0 0]);
cfg.markersize = ft_getopt(cfg, 'markersize', 2);
cfg.markerfontsize = ft_getopt(cfg, 'markerfontsize', 8);
cfg.highlight = ft_getopt(cfg, 'highlight', 'off');
cfg.highlightchannel = ft_getopt(cfg, 'highlightchannel', 'all');
cfg.highlightsymbol = ft_getopt(cfg, 'highlightsymbol', '*');
cfg.highlightcolor = ft_getopt(cfg, 'highlightcolor', [0 0 0]);
cfg.highlightsize = ft_getopt(cfg, 'highlightsize', 6);
cfg.highlightfontsize = ft_getopt(cfg, 'highlightfontsize', 8);
cfg.labeloffset = ft_getopt(cfg, 'labeloffset', 0.005);
cfg.maskparameter = ft_getopt(cfg, 'maskparameter', []);
cfg.component = ft_getopt(cfg, 'component', []);
cfg.matrixside = ft_getopt(cfg, 'matrixside', 'outflow');
cfg.channel = ft_getopt(cfg, 'channel', 'all');
% compatibility for previous highlighting option
if isnumeric(cfg.highlight)
cfg.highlightchannel = cfg.highlight;
cfg.highlight = 'on';
warning('cfg.highlight is now used for specifing highlighting-mode, use cfg.highlightchannel instead of cfg.highlight for specifiying channels')
elseif iscell(cfg.highlight)
if ~iscell(cfg.highlightchannel)
cfg.highlightchannel = cell(1,length(cfg.highlight));
end
for icell = 1:length(cfg.highlight)
if isnumeric(cfg.highlight{icell})
cfg.highlightchannel{icell} = cfg.highlight{icell};
cfg.highlight{icell} = 'on';
warning('cfg.highlight is now used for specifing highlighting-mode, use cfg.highlightchannel instead of cfg.highlight for specifiying channels')
end
end
end
% Converting all higlight options to cell-arrays if they're not cell-arrays,
% to make defaulting, checking for backwards compatability and error
% checking easier
if ~iscell(cfg.highlight), cfg.highlight = {cfg.highlight}; end
if ~iscell(cfg.highlightchannel), cfg.highlightchannel = {cfg.highlightchannel}; end
if ischar(cfg.highlightchannel{1}), cfg.highlightchannel = {cfg.highlightchannel}; end % {'all'} is valid input to channelselection, {1:5} isn't
if ~iscell(cfg.highlightsymbol), cfg.highlightsymbol = {cfg.highlightsymbol}; end
if ~iscell(cfg.highlightcolor), cfg.highlightcolor = {cfg.highlightcolor}; end
if ~iscell(cfg.highlightsize), cfg.highlightsize = {cfg.highlightsize}; end
if ~iscell(cfg.highlightfontsize), cfg.highlightfontsize = {cfg.highlightfontsize}; end
% then make sure all cell-arrays for options have length ncellhigh and default the last element if not present
ncellhigh = length(cfg.highlight);
if length(cfg.highlightsymbol) < ncellhigh, cfg.highlightsymbol{ncellhigh} = 'o'; end
if length(cfg.highlightcolor) < ncellhigh, cfg.highlightcolor{ncellhigh} = [0 0 0]; end
if length(cfg.highlightsize) < ncellhigh, cfg.highlightsize{ncellhigh} = 6; end
if length(cfg.highlightfontsize) < ncellhigh, cfg.highlightfontsize{ncellhigh} = 8; end
% then default all empty cells
for icell = 1:ncellhigh
if isempty(cfg.highlightsymbol{icell}), cfg.highlightsymbol{icell} = 'o'; end
if isempty(cfg.highlightcolor{icell}), cfg.highlightcolor{icell} = [0 0 0]; end
if isempty(cfg.highlightsize{icell}), cfg.highlightsize{icell} = 6; end
if isempty(cfg.highlightfontsize{icell}), cfg.h1tighlightfontsize{icell} = 8; end
end
% for backwards compatability
if strcmp(cfg.marker,'highlights')
warning('using cfg.marker option -highlights- is no longer used, please use cfg.highlight')
cfg.marker = 'off';
end
% check colormap is proper format and set it
if isfield(cfg,'colormap')
if size(cfg.colormap,2)~=3, error('topoplot(): Colormap must be a n x 3 matrix'); end
colormap(cfg.colormap);
end;
dtype = ft_datatype(data);
% identify the interpretation of the functional data
switch dtype
case 'raw'
data = ft_checkdata(data, 'datatype', 'timelock');
dtype = ft_datatype(data);
dimord = data.dimord;
case {'timelock' 'freq' 'unknown'}
dimord = data.dimord;
case 'comp'
dimord = 'chan_comp';
otherwise
end
dimtok = tokenize(dimord, '_');
% Set x/y/zparam defaults according to datatype and dimord
switch dtype
case 'timelock'
cfg.xparam = ft_getopt(cfg, 'xparam', 'time');
cfg.yparam = ft_getopt(cfg, 'yparam', '');
cfg.zparam = ft_getopt(cfg, 'zparam', 'avg');
case 'freq'
if any(ismember(dimtok, 'time'))
cfg.xparam = ft_getopt(cfg, 'xparam', 'time');
cfg.yparam = ft_getopt(cfg, 'yparam', 'freq');
cfg.zparam = ft_getopt(cfg, 'zparam', 'powspctrm');
else
cfg.xparam = ft_getopt(cfg, 'xparam', 'freq');
cfg.yparam = ft_getopt(cfg, 'yparam', '');
cfg.zparam = ft_getopt(cfg, 'zparam', 'powspctrm');
end
case 'comp'
% Add a pseudo-axis with the component numbers:
data.comp = 1:size(data.topo,2);
% Specify the components
if ~isempty(cfg.component)
data.comp = cfg.component;
data.topo = data.topo(:,cfg.component);
end
% Rename the field with topographic label information:
data.label = data.topolabel;
cfg.xparam = ft_getopt(cfg, 'xparam', 'comp');
cfg.yparam = ft_getopt(cfg, 'yparam', '');
cfg.zparam = ft_getopt(cfg, 'zparam', 'topo');
otherwise
% if the input data is not one of the standard data types, or if
% the functional data is just one value per channel
% in this case xparam, yparam are not defined
% and the user should define the zparam
if ~isfield(data, 'label'), error('the input data should at least contain a label-field'); end
if ~isfield(cfg, 'zparam'), error('the configuration should at least contain a ''zparam'' field'); end
if ~isfield(cfg, 'xparam'),
cfg.xlim = [1 1];
cfg.xparam = '';
end
end
% user specified own fields, but no yparam (which is not asked in help)
if isfield(cfg, 'xparam') && isfield(cfg, 'zparam') && ~isfield(cfg, 'yparam')
cfg.yparam = '';
end
% check whether rpt/subj is present and remove if necessary and whether
hasrpt = any(ismember(dimtok, {'rpt' 'subj'}));
if strcmp(dtype, 'timelock') && hasrpt,
tmpcfg = [];
tmpcfg.trials = cfg.trials;
data = ft_timelockanalysis(tmpcfg, data);
dimord = data.dimord;
dimtok = tokenize(dimord, '_');
elseif strcmp(dtype, 'freq') && hasrpt,
% this also deals with fourier-spectra in the input
% or with multiple subjects in a frequency domain stat-structure
% on the fly computation of coherence spectrum is not supported
if isfield(data, 'crsspctrm'), data = rmfield(data, 'crsspctrm'); end
tmpcfg = [];
tmpcfg.trials = cfg.trials;
tmpcfg.jackknife = 'no';
if isfield(cfg, 'zparam') && ~strcmp(cfg.zparam,'powspctrm')
% freqdesctiptives will only work on the powspctrm field
% hence a temporary copy of the data is needed
tempdata.dimord = data.dimord;
tempdata.freq = data.freq;
tempdata.label = data.label;
tempdata.powspctrm = data.(cfg.zparam);
tempdata.cfg = data.cfg;
tempdata = ft_freqdescriptives(tmpcfg, tempdata);
data.(cfg.zparam) = tempdata.powspctrm;
clear tempdata
else
data = ft_freqdescriptives(tmpcfg, data);
end
dimord = data.dimord;
dimtok = tokenize(dimord, '_');
end
if isfield(cfg, 'channel') && isfield(data, 'label')
cfg.channel = ft_channelselection(cfg.channel, data.label);
elseif isfield(cfg, 'channel') && isfield(data, 'labelcmb')
cfg.channel = ft_channelselection(cfg.channel, unique(data.labelcmb(:)));
end
% perform channel selection but only allow this when cfg.interactive = 'no'
if isfield(data, 'label') && strcmp(cfg.interactive, 'no')
selchannel = ft_channelselection(cfg.channel, data.label);
elseif isfield(data, 'labelcmb') && strcmp(cfg.interactive, 'no')
selchannel = ft_channelselection(cfg.channel, unique(data.labelcmb(:)));
end
% Read or create the layout that will be used for plotting:
lay = ft_prepare_layout(cfg, data);
cfg.layout = lay;
% Create time-series of small topoplots:
if ~ischar(cfg.xlim) && length(cfg.xlim)>2
% Switch off interactive mode:
cfg.interactive = 'no';
xlims = cfg.xlim;
% Iteratively call topoplotER with different xlim values:
for i=1:length(xlims)-1
subplot(ceil(sqrt(length(xlims)-1)), ceil(sqrt(length(xlims)-1)), i);
cfg.xlim = xlims(i:i+1);
ft_topoplotER(cfg, data);
end
return
end
% Apply baseline correction:
if ~strcmp(cfg.baseline, 'no')
if strcmp(cfg.xparam, 'freq') || strcmp(cfg.yparam, 'freq')
data = ft_freqbaseline(cfg, data);
else
data = ft_timelockbaseline(cfg, data);
end
end
% Handle the bivariate case
% Check for bivariate metric with 'chan_chan' in the dimord:
selchan = strmatch('chan', dimtok);
isfull = length(selchan)>1;
% Check for bivariate metric with a labelcmb field:
haslabelcmb = isfield(data, 'labelcmb');
if (isfull || haslabelcmb) && isfield(data, cfg.zparam)
% A reference channel is required:
if ~isfield(cfg, 'refchannel')
error('no reference channel is specified');
end
% check for refchannel being part of selection
if ~strcmp(cfg.refchannel,'gui')
if (isfull && ~any(ismember(data.label, cfg.refchannel))) || ...
(haslabelcmb && ~any(ismember(data.labelcmb(:), cfg.refchannel)))
error('cfg.refchannel is a not present in the (selected) channels)')
end
end
% Interactively select the reference channel
if strcmp(cfg.refchannel, 'gui')
% Open a single figure with the channel layout, the user can click on a reference channel
h = clf;
ft_plot_lay(lay, 'box', false);
title('Select the reference channel by dragging a selection window, more than 1 channel can be selected...');
% add the channel information to the figure
info = guidata(gcf);
info.x = lay.pos(:,1);
info.y = lay.pos(:,2);
info.label = lay.label;
guidata(h, info);
%set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'callback', {@select_topoplotER, cfg, data}});
set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_topoplotER, cfg, data}, 'event', 'WindowButtonUpFcn'});
set(gcf, 'WindowButtonDownFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_topoplotER, cfg, data}, 'event', 'WindowButtonDownFcn'});
set(gcf, 'WindowButtonMotionFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_topoplotER, cfg, data}, 'event', 'WindowButtonMotionFcn'});
return
end
if ~isfull,
% Convert 2-dimensional channel matrix to a single dimension:
if isempty(cfg.matrixside)
sel1 = strmatch(cfg.refchannel, data.labelcmb(:,2), 'exact');
sel2 = strmatch(cfg.refchannel, data.labelcmb(:,1), 'exact');
elseif strcmp(cfg.matrixside, 'outflow')
sel1 = [];
sel2 = strmatch(cfg.refchannel, data.labelcmb(:,1), 'exact');
elseif strcmp(cfg.matrixside, 'inflow')
sel1 = strmatch(cfg.refchannel, data.labelcmb(:,2), 'exact');
sel2 = [];
end
fprintf('selected %d channels for %s\n', length(sel1)+length(sel2), cfg.zparam);
data.(cfg.zparam) = data.(cfg.zparam)([sel1;sel2],:,:);
data.label = [data.labelcmb(sel1,1);data.labelcmb(sel2,2)];
data.labelcmb = data.labelcmb([sel1;sel2],:);
data = rmfield(data, 'labelcmb');
else
% General case
sel = match_str(data.label, cfg.refchannel);
siz = [size(data.(cfg.zparam)) 1];
if strcmp(cfg.matrixside, 'inflow') || isempty(cfg.matrixside)
%the interpretation of 'inflow' and 'outflow' depend on
%the definition in the bivariate representation of the data
%in FieldTrip the row index 'causes' the column index channel
%data.(cfg.zparam) = reshape(mean(data.(cfg.zparam)(:,sel,:),2),[siz(1) 1 siz(3:end)]);
sel1 = 1:siz(1);
sel2 = sel;
meandir = 2;
elseif strcmp(cfg.matrixside, 'outflow')
%data.(cfg.zparam) = reshape(mean(data.(cfg.zparam)(sel,:,:),1),[siz(1) 1 siz(3:end)]);
sel1 = sel;
sel2 = 1:siz(1);
meandir = 1;
elseif strcmp(cfg.matrixside, 'ff-fd')
error('cfg.matrixside = ''ff-fd'' is not supported anymore, you have to manually subtract the two before the call to ft_topoplotER');
elseif strcmp(cfg.matrixside, 'fd-ff')
error('cfg.matrixside = ''fd-ff'' is not supported anymore, you have to manually subtract the two before the call to ft_topoplotER');
end
end
end
% Get physical min/max range of x:
if strcmp(cfg.xlim,'maxmin')
xmin = min(data.(cfg.xparam));
xmax = max(data.(cfg.xparam));
else
xmin = cfg.xlim(1);
xmax = cfg.xlim(2);
end
% Replace value with the index of the nearest bin
if ~isempty(cfg.xparam)
xmin = nearest(data.(cfg.xparam), xmin);
xmax = nearest(data.(cfg.xparam), xmax);
end
% Get physical min/max range of y:
if isfield(cfg, 'yparam') && ~isempty(cfg.yparam)
if strcmp(cfg.ylim,'maxmin')
ymin = min(data.(cfg.yparam));
ymax = max(data.(cfg.yparam));
else
ymin = cfg.ylim(1);
ymax = cfg.ylim(2);
end
% Replace value with the index of the nearest bin:
ymin = nearest(data.(cfg.yparam), ymin);
ymax = nearest(data.(cfg.yparam), ymax);
end
% Take subselection of channels, this only works
% if the interactive mode is switched off
if exist('selchannel', 'var')
sellab = match_str(data.label, selchannel);
label = data.label(sellab);
else
sellab = 1:numel(data.label);
label = data.label;
end
if isfull
sel1 = intersect(sel1, sellab);
sel2 = intersect(sel2, sellab);
end
% Make vector dat with one value for each channel
dat = data.(cfg.zparam);
if ~isempty(cfg.yparam)
if isfull
dat = dat(sel1, sel2, ymin:ymax, xmin:xmax);
dat = nanmean(nanmean(nanmean(dat, meandir), 4), 3);
elseif haslabelcmb
dat = dat(sellab, ymin:ymax, xmin:xmax);
dat = nanmean(nanmean(dat, 3), 2);
else
dat = dat(sellab, ymin:ymax, xmin:xmax);
dat = nanmean(nanmean(dat, 3), 2);
end
elseif ~isempty(cfg.component)
else
if isfull
dat = dat(sel1, sel2, xmin:xmax);
dat = nanmean(nanmean(dat, meandir), 3);
elseif haslabelcmb
dat = dat(sellab, xmin:xmax);
dat = nanmean(dat, 2);
else
dat = dat(sellab, xmin:xmax);
dat = nanmean(dat, 2);
end
end
dat = dat(:);
% Select the channels in the data that match with the layout:
[seldat, sellay] = match_str(label, cfg.layout.label);
if isempty(seldat)
error('labels in data and labels in layout do not match');
end
datavector = dat(seldat);
% Select x and y coordinates and labels of the channels in the data
chanX = cfg.layout.pos(sellay,1);
chanY = cfg.layout.pos(sellay,2);
chanLabels = cfg.layout.label(sellay);
% make datmask structure with one value for each channel
if ~isempty(cfg.maskparameter)
datmask = data.(cfg.maskparameter);
if numel(datmask) ~= length(data.label)
error('data in cfg.maskparameter should be vector with one value per channel')
end
datmask = datmask(:);
% Select the channels in the maskdata that match with the layout:
maskdatavector = datmask(sellab(seldat));
%maskdatavector = datmask(seldat);
else
maskdatavector = [];
end
% Get physical min/max range of z:
if strcmp(cfg.zlim,'maxmin')
zmin = min(datavector);
zmax = max(datavector);
elseif strcmp(cfg.zlim,'maxabs')
zmin = -max(max(abs(datavector)));
zmax = max(max(abs(datavector)));
else
zmin = cfg.zlim(1);
zmax = cfg.zlim(2);
end
% make comment
if strcmp(cfg.comment, 'auto')
comment = date;
if ~isempty(cfg.xparam)
if strcmp(cfg.xlim,'maxmin')
comment = sprintf('%0s\n%0s=[%.3g %.3g]', comment, cfg.xparam, data.(cfg.xparam)(xmin), data.(cfg.xparam)(xmax));
else
comment = sprintf('%0s\n%0s=[%.3g %.3g]', comment, cfg.xparam, cfg.xlim(1), cfg.xlim(2));
end
end
if ~isempty(cfg.yparam)
if strcmp(cfg.ylim,'maxmin')
comment = sprintf('%0s\n%0s=[%.3g %.3g]', comment, cfg.yparam, data.(cfg.yparam)(ymin), data.(cfg.yparam)(ymax));
else
comment = sprintf('%0s\n%0s=[%.3g %.3g]', comment, cfg.yparam, cfg.ylim(1), cfg.ylim(2));
end
end
if ~isempty(cfg.zparam)
comment = sprintf('%0s\n%0s=[%.3g %.3g]', comment, cfg.zparam, zmin, zmax);
end
cfg.comment = comment;
elseif strcmp(cfg.comment, 'xlim')
if strcmp(cfg.xlim,'maxmin')
comment = sprintf('%0s=[%.3g %.3g]', cfg.xparam, data.(cfg.xparam)(xmin), data.(cfg.xparam)(xmax));
else
comment = sprintf('%0s=[%.3g %.3g]', cfg.xparam, cfg.xlim(1), cfg.xlim(2));
end
cfg.comment = comment;
elseif ~ischar(cfg.comment)
error('cfg.comment must be string');
end
if isfield(cfg,'refchannel')
if iscell(cfg.refchannel)
cfg.comment = sprintf('%s\nreference=%s %s', comment, cfg.refchannel{:});
else
cfg.comment = sprintf('%s\nreference=%s %s', comment, cfg.refchannel);
end
end
% Specify the x and y coordinates of the comment
if strcmp(cfg.commentpos,'layout')
ind_comment = strmatch('COMNT', cfg.layout.label);
x_comment = cfg.layout.pos(ind_comment,1);
y_comment = cfg.layout.pos(ind_comment,2);
elseif strcmp(cfg.commentpos,'lefttop')
x_comment = -0.7;
y_comment = 0.6;
HorAlign = 'left';
VerAlign = 'top';
elseif strcmp(cfg.commentpos,'leftbottom')
x_comment = -0.6;
y_comment = -0.6;
HorAlign = 'left';
VerAlign = 'bottom';
elseif strcmp(cfg.commentpos,'middletop')
x_comment = 0;
y_comment = 0.75;
HorAlign = 'center';
VerAlign = 'top';
elseif strcmp(cfg.commentpos,'middlebottom')
x_comment = 0;
y_comment = -0.7;
HorAlign = 'center';
VerAlign = 'bottom';
elseif strcmp(cfg.commentpos,'righttop')
x_comment = 0.65;
y_comment = 0.6;
HorAlign = 'right';
VerAlign = 'top';
elseif strcmp(cfg.commentpos,'rightbottom')
x_comment = 0.6;
y_comment = -0.6;
HorAlign = 'right';
VerAlign = 'bottom';
elseif isnumeric(cfg.commentpos)
x_comment = cfg.commentpos(1);
y_comment = cfg.commentpos(2);
HorAlign = 'left';
VerAlign = 'middle';
x_comment = 0.9*((x_comment-min(x))/(max(x)-min(x))-0.5);
y_comment = 0.9*((y_comment-min(y))/(max(y)-min(y))-0.5);
end
% Draw topoplot
cla
hold on
% Set ft_plot_topo specific options
if strcmp(cfg.interplimits,'head'), interplimits = 'mask';
else interplimits = cfg.interplimits; end
if strcmp(cfg.style,'both'); style = 'surfiso'; end
if strcmp(cfg.style,'straight'); style = 'surf'; end
if strcmp(cfg.style,'contour'); style = 'iso'; end
if strcmp(cfg.style,'fill'); style = 'isofill'; end
% Draw plot
if ~strcmp(cfg.style,'blank')
ft_plot_topo(chanX,chanY,datavector,'interpmethod',cfg.interpolation,...
'interplim',interplimits,...
'gridscale',cfg.gridscale,...
'outline',cfg.layout.outline,...
'shading',cfg.shading,...
'isolines',cfg.contournum,...
'mask',cfg.layout.mask,...
'style',style,...
'datmask', maskdatavector);
elseif ~strcmp(cfg.style,'blank')
ft_plot_lay(lay,'box','no','label','no','point','no')
end
% Plotting markers for channels and/or highlighting a selection of channels
highlightchansel = []; % used for remembering selection of channels
templay.outline = lay.outline;
templay.mask = lay.mask;
% For Highlight (channel-selection)
for icell = 1:length(cfg.highlight)
if ~strcmp(cfg.highlight{icell},'off')
[dum labelindex] = match_str(ft_channelselection(cfg.highlightchannel{icell}, data.label), lay.label);
highlightchansel = [highlightchansel; match_str(data.label,ft_channelselection(cfg.highlightchannel{icell}, data.label))];
templay.pos = lay.pos(labelindex,:);
templay.width = lay.width(labelindex);
templay.height = lay.height(labelindex);
templay.label = lay.label(labelindex);
if strcmp(cfg.highlight{icell}, 'labels') || strcmp(cfg.highlight{icell}, 'numbers')
labelflg = 1;
else
labelflg = 0;
end
if strcmp(cfg.highlight{icell}, 'numbers')
for ichan = 1:length(labelindex)
templay.label{ichan} = num2str(match_str(data.label,templay.label{ichan}));
end
end
ft_plot_lay(templay,'box','no','label',labelflg,'point','yes',...
'pointsymbol',cfg.highlightsymbol{icell},...
'pointcolor',cfg.highlightcolor{icell},...
'pointsize',cfg.highlightsize{icell},...
'labelsize',cfg.highlightfontsize{icell},...
'labeloffset',cfg.labeloffset)
end
end % for icell
% For Markers (all channels)
if ~strcmp(cfg.marker,'off')
[dum labelindex] = match_str(ft_channelselection(setdiff(1:length(data.label),highlightchansel), data.label),lay.label);
templay.pos = lay.pos(labelindex,:);
templay.width = lay.width(labelindex);
templay.height = lay.height(labelindex);
templay.label = lay.label(labelindex);
if strcmp(cfg.marker, 'labels') || strcmp(cfg.marker, 'numbers')
labelflg = 1;
else
labelflg = 0;
end
if strcmp(cfg.marker, 'numbers')
for ichan = 1:length(labelindex)
templay.label{ichan} = num2str(match_str(data.label,templay.label{ichan}));
end
end
ft_plot_lay(templay,'box','no','label',labelflg,'point','yes',...
'pointsymbol',cfg.markersymbol,...
'pointcolor',cfg.markercolor,...
'pointsize',cfg.markersize,...
'labelsize',cfg.markerfontsize,...
'labeloffset',cfg.labeloffset)
end
% Write comment
if ~strcmp(cfg.comment,'no')
if strcmp(cfg.commentpos, 'title')
title(cfg.comment, 'Fontsize', cfg.fontsize);
else
ft_plot_text(x_comment,y_comment, cfg.comment, 'Fontsize', cfg.fontsize, 'HorizontalAlignment', 'left', 'VerticalAlignment', 'bottom');
end
end
% plot colorbar:
if isfield(cfg, 'colorbar')
if strcmp(cfg.colorbar, 'yes')
colorbar;
elseif ~strcmp(cfg.colorbar, 'no')
colorbar('location',cfg.colorbar);
end
end
% Set renderer if specified
if ~isempty(cfg.renderer)
set(gcf, 'renderer', cfg.renderer)
end
% The remainder of the code is meant to make the figure interactive
hold on;
% Set colour axis
caxis([zmin zmax]);
if strcmp('yes',cfg.hotkeys)
% Attach data and cfg to figure and attach a key listener to the figure
set(gcf, 'KeyPressFcn', {@key_sub, zmin, zmax})
end
% Make the figure interactive
if strcmp(cfg.interactive, 'yes')
% add the channel position information to the figure
% this section is required for ft_select_channel to do its work
info = guidata(gcf);
info.x = lay.pos(:,1);
info.y = lay.pos(:,2);
info.label = lay.label;
guidata(gcf, info);
if any(strcmp(data.dimord, {'chan_time', 'chan_freq', 'subj_chan_time', 'rpt_chan_time', 'chan_chan_freq'}))
set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_singleplotER, cfg, varargin{1:Ndata}}, 'event', 'WindowButtonUpFcn'});
set(gcf, 'WindowButtonDownFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_singleplotER, cfg, varargin{1:Ndata}}, 'event', 'WindowButtonDownFcn'});
set(gcf, 'WindowButtonMotionFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_singleplotER, cfg, varargin{1:Ndata}}, 'event', 'WindowButtonMotionFcn'});
elseif any(strcmp(data.dimord, {'chan_freq_time', 'subj_chan_freq_time', 'rpt_chan_freq_time', 'rpttap_chan_freq_time', 'chan_chan_freq_time'}))
set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_singleplotTFR, cfg, varargin{1:Ndata}}, 'event', 'WindowButtonUpFcn'});
set(gcf, 'WindowButtonDownFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_singleplotTFR, cfg, varargin{1:Ndata}}, 'event', 'WindowButtonDownFcn'});
set(gcf, 'WindowButtonMotionFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_singleplotTFR, cfg, varargin{1:Ndata}}, 'event', 'WindowButtonMotionFcn'});
else
error('unsupported dimord "%" for interactive plotting', data.dimord);
end
end
axis off;
hold off;
axis equal;
% get the output cfg
cfg = ft_checkconfig(cfg, 'trackconfig', 'off', 'checksize', 'yes');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION which is called after selecting channels in case of cfg.refchannel='gui'
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function select_topoplotER(label, cfg, varargin)
cfg.refchannel = label;
fprintf('selected cfg.refchannel = ''%s''\n', cfg.refchannel{:});
p = get(gcf, 'Position');
f = figure;
set(f, 'Position', p);
cfg.highlight = 'on';
cfg.highlightsymbol = '.';
cfg.highlightcolor = 'r';
cfg.highlightsize = 20;
cfg.highlightchannel = cfg.refchannel;
ft_topoplotER(cfg, varargin{:});
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION which is called after selecting channels in case of cfg.interactive='yes'
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function select_singleplotER(label, cfg, varargin)
if ~isempty(label)
cfg.xlim = 'maxmin';
cfg.channel = label;
fprintf('selected cfg.channel = {');
for i=1:(length(cfg.channel)-1)
fprintf('''%s'', ', cfg.channel{i});
end
fprintf('''%s''}\n', cfg.channel{end});
p = get(gcf, 'Position');
f = figure;
set(f, 'Position', p);
ft_singleplotER(cfg, varargin{:});
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION which is called after selecting channels in case of cfg.interactive='yes'
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function select_singleplotTFR(label, cfg, varargin)
if ~isempty(label)
cfg.xlim = 'maxmin';
cfg.ylim = 'maxmin';
cfg.channel = label;
fprintf('selected cfg.channel = {');
for i=1:(length(cfg.channel)-1)
fprintf('''%s'', ', cfg.channel{i});
end
fprintf('''%s''}\n', cfg.channel{end});
p = get(gcf, 'Position');
f = figure;
set(f, 'Position', p);
ft_singleplotTFR(cfg, varargin{:});
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION which handles hot keys in the current plot
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function key_sub(handle, eventdata, varargin)
incr = (max(caxis)-min(caxis)) /10;
% symmetrically scale color bar down by 10 percent
if strcmp(eventdata.Key,'uparrow')
caxis([min(caxis)-incr max(caxis)+incr]);
% symmetrically scale color bar up by 10 percent
elseif strcmp(eventdata.Key,'downarrow')
caxis([min(caxis)+incr max(caxis)-incr]);
% resort to minmax of data for colorbar
elseif strcmp(eventdata.Key,'m')
caxis([varargin{1} varargin{2}]);
end
|
github
|
philippboehmsturm/antx-master
|
ft_spike_plot_raster.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_spike_plot_raster.m
| 14,853 |
utf_8
|
6ff7ffacc8bc4b5b2e8c94560944ae5b
|
function [hdl] = ft_spike_plot_raster(cfg, spike)
% FT_SPIKE_RASTERPLOT:
% - makes a raster plot of spike-trains
% - allows for spike-density or psth plot on top
%
% The input SPIKE should be organised as:
% The SPIKE datatype, obtained from FT_SPIKESTATION_DATA2SPIKE or FT_SPIKE_MAKETRIALS
%
% The optional input TOPDATA is a structure as the output from FT_SPIKE_PSTH
% or FT_SPIKEDENSITY or FT_TIMELOCKANALYSIS. See those functions for more info.
%
% Configurations options (CFG):
%
% Configuration options related to selection of spike channel and trials and latencies
%
% cfg.spikechannel = see FT_CHANNELSELECTION for details
% cfg.latency = [begin end]` in seconds, 'maxperiod' (default), 'minperiod',
% 'prestim' (all t<=0), or 'poststim' (all t>=0).
% cfg.linewidth = number indicating the width of the lines (default = 1);
% cfg.cmapneurons = 'auto' (default), or nUnits-by-3 matrix, or cell array with
% color strings (e.g., {'k' 'r' 'b'}). If 'auto', we are using a
% private colormap that has good visibility on white background.
% cfg.spikelength = number >0 and <=1 indicating the length of the spike. If
% cfg.spikelength = 1, then no space will be left between
% subsequent rows representing trials (row-unit is 1).
%
% Configuration options related to additionally plotting the TOPDATA
%
% cfg.topdata = output structure from FT_SPIKE_PSTH
% or FT_SPIKEDENSITY or FT_TIMELOCKANALYSIS. See those functions for more
% info.
% cfg.topplotsize = number ranging from 0 to 1, indicating the proportion of the
% rasterplot that the top plot will take (e.g., with 0.7 the top
% plot will be 70% of the rasterplot in size). Default = 0.5.
% cfg.topplotfunc = 'bar' (default) or 'line'.
%
% Outputs:
% HDL.TOP = handle of the plot of the TOPDATA (psth or sdf)
% HDL.RASTER = handle for each individual spike.
% HDL.AX = axes handles: AX(1) the rasterplot and AX(2) the topplot.
% HDL.CFG
% Martin Vinck (C) 2010 F.C. Donders Centre for Neuroimaging, University of Amsterdam
if nargin<2, error('MATLAB:ft_spike_plot_raster:nargin','>=2 input arguments required'), end
% check the configuration inputs and enter the defaults
defaults.spikechannel = {'all'};
defaults.trials = {'all'};
defaults.latency = {'maxperiod'};
defaults.linewidth = {1};
defaults.cmapneurons = {'auto'}; % auto based on the number of cells
defaults.spikelength = {0.9};
defaults.topdata = {[]};
defaults.topplotsize = {0.5}; % meaning: top plot takes 50%
defaults.topplotfunc = {'bar' 'line'}; % auto means: we check if sdf or psth REMOVE
cfg = ft_spike_sub_defaultcfg(cfg,defaults);
% check which features should be present in the rasterplot and psth
doTopData = ~isempty(cfg.topdata);
if doTopData
topData = cfg.topdata;
% make sure TOPDATA is struct with right fields, and warn if VAR or DOF are missing
if ~isstruct(topData) || ~all(isfield(topData,{'avg' 'time' 'label'}))
error('MATLAB:ft_spike_plot_raster:topData:wrongFormatStruct',...
'TOPDATA needs to be (timelock or psth) struct with fields avg, time and label');
end
end
% check if input is of correct format
hasAllFields = all(isfield(spike, {'time', 'trial', 'trialtime', 'label'}));
if ~hasAllFields, error('MATLAB:spikestation:plot_raster:wrongStructInput',...
'input ETS should be struct with .time, .trial, .trialtime, .label fields')
end
% check whether all are of right format
correctInp = iscell(spike.time) & iscell(spike.trial) & iscell(spike.label) & size(spike.trialtime,2)==2;
if ~correctInp, error('MATLAB:spikestation:plot_raster:wrongStructInput',...
'.time, .trial and .label should be cell arrays, .trialtime should be nTrials-by-2 matrix')
end
% get the spikechannels
cfg.channel = ft_channelselection(cfg.spikechannel, spike.label);
spikesel = match_str(spike.label, cfg.channel);
nUnits = length(spikesel); % number of spike channels
if nUnits==0, error('MATLAB:ft_spike_plot_raster:cfg:spikechannel:noSpikeChanSelected',...
'No spikechannel selected by means of cfg.spikechannel');
end
% get the number of trials or change DATA according to cfg.trials
nTrialsOrig = size(spike.trialtime,1);
if strcmp(cfg.trials,'all')
cfg.trials = 1:nTrialsOrig;
elseif islogical(cfg.trials)
cfg.trials = find(cfg.trials);
elseif ~isrealvec(cfg.trials);
error('MATLAB:ft_spike_plot_raster:cfg:trials:wrongInput',...
'cfg.trials should be logical or numerical selection or string "all"');
end
cfg.trials = sort(cfg.trials(:));
if max(cfg.trials)>nTrialsOrig, error('MATLAB:ft_spike_plot_raster:cfg:trials:maxExceeded',...
'maximum trial number in cfg.trials should not exceed length of DATA.trial')
end
if isempty(cfg.trials),
errors('MATLAB:ft_spike_plot_raster:cfg:trials','No trials were selected in cfg.trials');
end
nTrials = length(cfg.trials);
% determine the duration of each trial
begTrialLatency = spike.trialtime(cfg.trials,1);
endTrialLatency = spike.trialtime(cfg.trials,2);
% select the latencies
if strcmp(cfg.latency,'minperiod')
cfg.latency = [max(begTrialLatency) min(endTrialLatency)];
elseif strcmp(cfg.latency,'maxperiod')
cfg.latency = [min(begTrialLatency) max(endTrialLatency)];
elseif strcmp(cfg.latency,'prestim')
cfg.latency = [min(begTrialLatency) 0];
elseif strcmp(cfg.latency,'poststim')
cfg.latency = [0 max(endTrialLatency)];
elseif ~isrealvec(cfg.latency)||length(cfg.latency)~=2
error('MATLAB:fieldtrip:spikerate:cfg:latency',...
'cfg.latency should be "max", "min", "prestim", "poststim" or 1-by-2 numerical vector');
end
if cfg.latency(1)>cfg.latency(2),
error('MATLAB:ft_spike_plot_raster:cfg:latency:wrongOrder',...
'cfg.latency should be a vector in ascending order, i.e., cfg.latency(2)>cfg.latency(1)');
end
% check whether the time window fits with the data
if (cfg.latency(1) < min(begTrialLatency)), cfg.latency(1) = min(begTrialLatency);
warning('MATLAB:ft_spike_plot_raster:cfg:latency:correctBeg',...
'Correcting begin latency of averaging window');
end
if (cfg.latency(2) > max(endTrialLatency)), cfg.latency(2) = max(endTrialLatency);
warning('MATLAB:ft_spike_plot_raster:cfg:latency:correctEnd',...
'Correcting begin latency of averaging window');
end
trialDur = cfg.latency(2) - cfg.latency(1);
% delete trials that are not in our window
overlaps = endTrialLatency>=cfg.latency(1) & begTrialLatency<=cfg.latency(2);
trialSel = overlaps(:);
cfg.trials = cfg.trials(trialSel); %update the trial selection
if isempty(cfg.trials),
warning('MATLAB:ft_spike_plot_raster:cfg:trials','No trials were selected');
end
nTrials = length(cfg.trials);
% create the data that should be plotted
[unitX,unitY] = deal(cell(1,nUnits));
% find the spiketimes per neuron and make one vector of them with y value per element
for iUnit = 1:nUnits
unitIndx = spikesel(iUnit);
latencySel = spike.time{unitIndx}>=cfg.latency(1) & spike.time{unitIndx} <= cfg.latency(2);
isInTrials = ismember(spike.trial{unitIndx},cfg.trials);
unitX{iUnit} = spike.time{unitIndx}(isInTrials(:) & latencySel(:));
unitY{iUnit} = spike.trial{unitIndx}(isInTrials(:) & latencySel(:));
end
if ~isscalar(cfg.spikelength) || cfg.spikelength<=0 || cfg.spikelength>1
error('MATLAB:ft_spike_plot_raster:cfg:spikelength:unknownOption',...
'cfg.spikelength should be a single number >0 and <=1. 1 row (1 trial) = 1');
end
if ~isscalar(cfg.topplotsize) || cfg.topplotsize<=0 || cfg.topplotsize>1
error('MATLAB:ft_spike_plot_raster:cfg:topplotsize:unknownOption',...
'cfg.topplotsize should be a single number >0 and <=1. 0.7 = 70%');
end
% start plotting the rasterplot
for iUnit = 1:nUnits
% create the x and y value to be plotted
x = [unitX{iUnit}(:)'; unitX{iUnit}(:)']; % create x duplicates, spike times
y = unitY{iUnit}(:); % these are the trial values
y = [y' - cfg.spikelength/2; y' + cfg.spikelength/2];
% process the color information for the different units
if strcmp(cfg.cmapneurons, 'auto'), cfg.cmapneurons = colormap_cgbprb(nUnits); end
if isrealmat(cfg.cmapneurons) && all(size(cfg.cmapneurons) ./ [nUnits 3])
color = cfg.cmapneurons(iUnit,:);
elseif iscell(cfg.cmapneurons) && length(cfg.cmapneurons)==nUnits
color = cfg.cmapneurons{iUnit};
else
error('MATLAB:ft_spike_plot_raster:cfg:cmapneurons:unknownOption',...
'cfg.cmapneurons should be nUnits-by-3 matrix or 1-by-nUnits cell or "auto"');
end
% create axes for the rasterplot, all go to the same position, so do this for unit 1
if iUnit==1
ax(1) = newplot;
posOrig = get(ax(1), 'Position'); % original position for a standard plot
pos = posOrig;
if doTopData % if topdata, we leave space on top
posRaster = [pos(1:3) pos(4)*(1-cfg.topplotsize)]; % and decrease the size of width and height
else
posRaster = pos;
end
set(ax(1), 'ActivePositionProperty', 'position', 'Position', posRaster)
end
% make the raster plot and hold on for the next plots
rasterHdl = plot(x, y,'linewidth', cfg.linewidth,'Color', color);
set(ax(1),'NextPlot', 'add')
set(ax(1),'Box', 'off')
end
% create the labels for the first axes
xlabel('time (sec)')
ylabel('Trial Number')
axis ij
% plot the top data
if doTopData
% match on the basis of labels, and specify this in the documentary
unitIndx = find(ismember(topData.label,spike.label(spikesel)));
if sum(unitIndx)<nUnits, error('MATLAB:ft_spike_plot_raster:topData:missingLabel',...
'topData.label should contain all label of selected units');
end
% select timepoints and get the data to be plotted
binSel = topData.time>=cfg.latency(1) & topData.time<=cfg.latency(2);
y = topData.avg(unitIndx,binSel);
% create the position for the topplot and axes with this position
posTopPlot = [0 pos(4)*(1-cfg.topplotsize) 0 0] + pos.*[1 1 1 cfg.topplotsize];
ax(2) = axes('Units', get(ax(1), 'Units'), 'Position', posTopPlot,...
'Parent', get(ax(1), 'Parent'));
% make the bar or the line plot
if strcmp(cfg.topplotfunc,'bar')
avgHdl = feval(cfg.topplotfunc,topData.time(binSel),y', 'Stack');
for iUnit = 1:nUnits
set(avgHdl(iUnit),'FaceColor',cfg.cmapneurons(iUnit,:),'EdgeColor', cfg.cmapneurons(iUnit,:));
end
if strcmp(cfg.topplotfunc,'bar'),set(avgHdl,'BarWidth', 1); end
else
x = topData.time(binSel);
x = repmat(x(:),1,nUnits); % it puts multiple neurons here? check>
avgHdl = feval(cfg.topplotfunc,x,y');
for iUnit = 1:nUnits
set(avgHdl(iUnit),'Color',cfg.cmapneurons(iUnit,:));
end
end
% modify the axes
set(ax(2),'YAxisLocation', 'right') % swap y axis location
set(ax(2),'XTickLabel', {}) % remove ticks and labels for x axis
set(ax(2),'XTick', [])
set(ax(2), 'Box', 'off') % turn the box off
% change the axis settings
try
ylabel(topData.cfg.outputunit)
catch
ylabel('Firing Rate')
end
end
% set the limits for the axis
set(ax,'XLim', [cfg.latency])
set(ax(1), 'YLim', [0.5 nTrialsOrig+0.5]); % number of trials
set(ax,'TickDir','out') % put the tickmarks outside
% collect the handles
hdl.raster = rasterHdl;
if doTopData, hdl.top = avgHdl; end
hdl.ax = ax;
% now link the axes, constrain zooming and keep ticks intact
limX = [cfg.latency];
limY = get(ax,'YLim');
if ~iscell(limY), limY = {limY}; end
% constrain the zooming and zoom psth together with the jpsth, remove ticklabels jpsth
set(zoom,'ActionPostCallback',{@mypostcallback,ax,limX,limY});
set(pan,'ActionPostCallback',{@mypostcallback,ax,limX,limY});
hdl.cfg = cfg;
function [] = mypostcallback(fig,evd,ax,lim,ylim)
currentAxes = evd.Axes;
indx = find(currentAxes==ax);
% keep the y axis within boundaries
origLim = ylim{indx};
ylim = get(ax(indx), 'YLim');
if origLim(1)>ylim(1), ylim(1) = origLim(1); end
if origLim(2)<ylim(2), ylim(2) = origLim(2); end
set(ax(indx), 'YLim', ylim)
% keep the x axis within boundaries and reset for both
xlim = get(ax(indx), 'XLim');
if lim(1)>xlim(1), xlim(1) = lim(1); end
if lim(2)<xlim(2), xlim(2) = lim(2); end
set(ax,'XLim', xlim)
function [X,Y] = polygon(x,mn,sm,multiplier)
if nargin < 4
multiplier = 1;
end
X = [x x(end:-1:1) x(1)];
up = mn + multiplier*sm;
down = mn - multiplier*sm;
Y = [down up(end:-1:1) down(1)];
function [colorspace] = colormap_cgbprb(N)
% COLORMAP_SEPARATION returns a color map with well separated colors that does not include
% white, yellow or orange since these are not well visible in white plots.
%
% Inputs: N is the number of colors desired
% Outputs: COLORSPACE is an N-by-3 colorspace.
% Chosen colors are green, cyan, blue, purple, red and black
% Script was adapted from varycolors.m from FEX
% Copyright (c) 2009, Martin Vinck
if nargin<1
error('specify the number of colors that you want')
end
% create a well visible color space
% green cyan blue purple red black
colors = [[0 1 0]; [0 1 1] ; [0 0 1] ; [1 0 1]; [1 0 0]; [0 0 0]];
order = [1 5 3 2 4 6]; % our preference order when plotting different lines
rm{2} = [2:5];
rm{3} = [2 4 5];
rm{4} = [2 4];
rm{5} = [4];
if N==1
colorspace = colors(end,:);
elseif N>1&&N<6
colors(rm{N},:) = [];
colorspace = colors;
else
n = floor(N/5)*ones(1,5);
rest = mod(N,5);
order = [1 5 3 2 4];
% if we have some rest, add them starting oppositly
n(order(1:rest)) = n(order(1:rest)) + 1;
colorspace = [];
for iColor = 1:5
corStart = colors(iColor,:);
corEnd = colors(iColor+1,:);
dim = corStart~=corEnd;
subColors = corStart(ones(n(iColor)+1,1),:);
if iColor>1
subColors(:,dim) = linspace(corStart(dim),corEnd(dim),n(iColor)+1);
subColors(1,:) = [];
else
subColors(1:end-1,dim) = linspace(corStart(dim),corEnd(dim),n(iColor));
subColors(end,:) = [];
end
colorspace = [colorspace;subColors];
end
end
|
github
|
philippboehmsturm/antx-master
|
ft_electroderealign.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_electroderealign.m
| 28,009 |
utf_8
|
3f54c6cc419ca2ba2fa35dd3892ae692
|
function [norm] = ft_electroderealign(cfg)
% FT_ELECTRODEREALIGN rotates and translates electrode positions to
% template electrode positions or towards the head surface. It can
% either perform a rigid body transformation, in which only the
% coordinate system is changed, or it can apply additional deformations
% to the input electrodes.
%
% Use as
% [elec] = ft_electroderealign(cfg)
%
% Different methods for aligning the input electrodes to the subjects head
% are implemented, which are described in detail below:
%
% TEMPLATE - You can apply a spatial transformation/deformation that
% automatically minimizes the distance between the electrodes and the
% template or standard electrode set. The warping methods use a non-linear
% search to minimize the error between the input electrodes and
% corresponding template electrodes or between the input electrodes and a
% head surface.
%
% FIDUCIAL - You can apply a rigid body realignment based on three fiducial
% locations. Realigning using the fiducials only ensures that the fiducials
% (typically nose, left and right ear) are along the same axes in the input
% eectrode set as in the template electrode set.
%
% INTERACTIVE - You can display the skin surface together with the
% electrode position, and manually (using the graphical user interface)
% adjust the rotation, translation and scaling parameters, so that the
% electrodes correspond with the skin.
%
% MANUAL - You can display the skin surface and manually determine the
% electrode positions by clicking on the skin surface.
%
% The configuration can contain the following options
% cfg.method = string representing the method for aligning or placing the electrodes
% 'template' realign the electrodes to a template electrode set
% 'fiducial' realign using the NAS, LPA and RPA fiducials
% 'interactive' realign manually using a graphical user interface
% 'manual' manual positioning of the electrodes by clicking in a graphical user interface
% cfg.warp = string describing the spatial transformation for the template method
% 'rigidbody' apply a rigid-body warp (default)
% 'globalrescale' apply a rigid-body warp with global rescaling
% 'traditional' apply a rigid-body warp with individual axes rescaling
% 'nonlin1' apply a 1st order non-linear warp
% 'nonlin2' apply a 2nd order non-linear warp
% 'nonlin3' apply a 3rd order non-linear warp
% 'nonlin4' apply a 4th order non-linear warp
% 'nonlin5' apply a 5th order non-linear warp
% cfg.channel = Nx1 cell-array with selection of channels (default = 'all'),
% see FT_CHANNELSELECTION for details
% cfg.fiducial = cell-array with the name of three fiducials used for
% realigning (default = {'nasion', 'lpa', 'rpa'})
% cfg.casesensitive = 'yes' or 'no', determines whether string comparisons
% between electrode labels are case sensitive (default = 'yes')
% cfg.feedback = 'yes' or 'no' (default = 'no')
%
% The electrode set that will be realigned is specified as
% cfg.elecfile = string with filename, or alternatively
% cfg.elec = structure with electrode definition
%
% If you want to align the electrodes to a single template electrode set
% or to multiple electrode sets (which will be averaged), you should
% specify the template electrode sets as
% cfg.template = single electrode set that serves as standard
% or
% cfg.template{1..N} = list of electrode sets that are averaged into the standard
% The template electrode sets can be specified either as electrode
% structures (i.e. when they are already read in memory) or as electrode
% files.
%
% If you only want to realign using the fiducials, the template has to contain
% the three fiducials, e.g.
% cfg.template.pnt(1,:) = [110 0 0] % location of the nose
% cfg.template.pnt(2,:) = [0 90 0] % left ear
% cfg.template.pnt(3,:) = [0 -90 0] % right ear
% cfg.template.label = {'nasion', 'lpa', 'rpa'}
%
% If you want to align existing electrodes to the head surface or position
% new electrodes on the head surface, you should specify the head surface as
% cfg.headshape = a filename containing headshape, a structure containing a
% single triangulated boundary, or a Nx3 matrix with surface
% points
%
% See also FT_READ_SENS, FT_VOLUMEREALIGN
% Copyright (C) 2005-2011, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_electroderealign.m 3710 2011-06-16 14:04:19Z eelspa $
ft_defaults
% record start time and total processing time
ftFuncTimer = tic();
ftFuncClock = clock();
%text output
disp('Close the figure to output new sensor positions');
% this is used for feedback of the lower-level functions
global fb
% set the defaults
if ~isfield(cfg, 'channel'), cfg.channel = 'all'; end
if ~isfield(cfg, 'feedback'), cfg.feedback = 'no'; end
if ~isfield(cfg, 'casesensitive'), cfg.casesensitive = 'yes'; end
if ~isfield(cfg, 'headshape'), cfg.headshape = []; end % for triangulated head surface, without labels
if ~isfield(cfg, 'template'), cfg.template = []; end % for electrodes or fiducials, always with labels
if ~isfield(cfg, 'warp'), cfg.warp = 'rigidbody'; end
if ~isfield(cfg, 'label'), cfg.label = 'off'; end % show labels
cfg = ft_checkconfig(cfg, 'renamedval', {'method', 'realignfiducials', 'fiducial'});
cfg = ft_checkconfig(cfg, 'renamedval', {'method', 'realignfiducial', 'fiducial'});
cfg = ft_checkconfig(cfg, 'forbidden', 'outline');
cfg = ft_checkconfig(cfg, 'renamedval',{'warp', 'homogenous', 'rigidbody'});
if isfield(cfg, 'headshape') && isa(cfg.headshape, 'config')
% convert the nested config-object back into a normal structure
cfg.headshape = struct(cfg.headshape);
end
if strcmp(cfg.feedback, 'yes')
% use the global fb field to tell the warping toolbox to print feedback
fb = 1;
else
fb = 0;
end
% get the electrode definition that should be warped
if isfield(cfg, 'elec')
elec = cfg.elec;
elseif isfield(cfg, 'elecfile')
elec = ft_read_sens(cfg.elecfile);
else
% start with an empty set of electrodes (usefull for manual positioning)
elec = [];
elec.pnt = zeros(0,3);
elec.label = cell(0,1);
elec.unit = 'mm';
end
elec = ft_convert_units(elec); % ensure that the units are specified
usetemplate = isfield(cfg, 'template') && ~isempty(cfg.template);
useheadshape = isfield(cfg, 'headshape') && ~isempty(cfg.headshape);
if usetemplate
% get the template electrode definitions
if ~iscell(cfg.template)
cfg.template = {cfg.template};
end
Ntemplate = length(cfg.template);
for i=1:Ntemplate
if isstruct(cfg.template{i})
template(i) = cfg.template{i};
else
template(i) = ft_read_sens(cfg.template{i});
end
end
clear tmp
for i=1:Ntemplate
tmp(i) = ft_convert_units(template(i), elec.unit); % ensure that the units are consistent with the electrodes
end
template = tmp;
end
if useheadshape
% get the surface describing the head shape
if isstruct(cfg.headshape) && isfield(cfg.headshape, 'pnt')
% use the headshape surface specified in the configuration
headshape = cfg.headshape;
elseif isnumeric(cfg.headshape) && size(cfg.headshape,2)==3
% use the headshape points specified in the configuration
headshape.pnt = cfg.headshape;
elseif ischar(cfg.headshape)
% read the headshape from file
headshape = ft_read_headshape(cfg.headshape);
else
error('cfg.headshape is not specified correctly')
end
if ~isfield(headshape, 'tri')
% generate a closed triangulation from the surface points
headshape.pnt = unique(headshape.pnt, 'rows');
headshape.tri = projecttri(headshape.pnt);
end
headshape = ft_convert_units(headshape, elec.unit); % ensure that the units are consistent with the electrodes
end
% remember the original electrode locations and labels
orig = elec;
% convert all labels to lower case for string comparisons
% this has to be done AFTER keeping the original labels and positions
if strcmp(cfg.casesensitive, 'no')
for i=1:length(elec.label)
elec.label{i} = lower(elec.label{i});
end
for j=1:length(template)
for i=1:length(template(j).label)
template(j).label{i} = lower(template(j).label{i});
end
end
end
if strcmp(cfg.feedback, 'yes')
% create an empty figure, continued below...
figure
axis equal
axis vis3d
hold on
xlabel('x')
ylabel('y')
zlabel('z')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if strcmp(cfg.method, 'template') && usetemplate
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% determine electrode selection and overlapping subset for warping
cfg.channel = ft_channelselection(cfg.channel, elec.label);
for i=1:Ntemplate
cfg.channel = ft_channelselection(cfg.channel, template(i).label);
end
% make subselection of electrodes
[cfgsel, datsel] = match_str(cfg.channel, elec.label);
elec.label = elec.label(datsel);
elec.pnt = elec.pnt(datsel,:);
for i=1:Ntemplate
[cfgsel, datsel] = match_str(cfg.channel, template(i).label);
template(i).label = template(i).label(datsel);
template(i).pnt = template(i).pnt(datsel,:);
end
% compute the average of the template electrode positions
all = [];
for i=1:Ntemplate
all = cat(3, all, template(i).pnt);
end
avg = mean(all,3);
stderr = std(all, [], 3);
fprintf('warping electrodes to template... '); % the newline comes later
[norm.pnt, norm.m] = warp_optim(elec.pnt, avg, cfg.warp);
norm.label = elec.label;
dpre = mean(sqrt(sum((avg - elec.pnt).^2, 2)));
dpost = mean(sqrt(sum((avg - norm.pnt).^2, 2)));
fprintf('mean distance prior to warping %f, after warping %f\n', dpre, dpost);
if strcmp(cfg.feedback, 'yes')
% plot all electrodes before warping
my_plot3(elec.pnt, 'r.');
my_plot3(elec.pnt(1,:), 'r*');
my_plot3(elec.pnt(2,:), 'r*');
my_plot3(elec.pnt(3,:), 'r*');
my_text3(elec.pnt(1,:), elec.label{1}, 'color', 'r');
my_text3(elec.pnt(2,:), elec.label{2}, 'color', 'r');
my_text3(elec.pnt(3,:), elec.label{3}, 'color', 'r');
% plot all electrodes after warping
my_plot3(norm.pnt, 'm.');
my_plot3(norm.pnt(1,:), 'm*');
my_plot3(norm.pnt(2,:), 'm*');
my_plot3(norm.pnt(3,:), 'm*');
my_text3(norm.pnt(1,:), norm.label{1}, 'color', 'm');
my_text3(norm.pnt(2,:), norm.label{2}, 'color', 'm');
my_text3(norm.pnt(3,:), norm.label{3}, 'color', 'm');
% plot the template electrode locations
my_plot3(avg, 'b.');
my_plot3(avg(1,:), 'b*');
my_plot3(avg(2,:), 'b*');
my_plot3(avg(3,:), 'b*');
my_text3(avg(1,:), norm.label{1}, 'color', 'b');
my_text3(avg(2,:), norm.label{2}, 'color', 'b');
my_text3(avg(3,:), norm.label{3}, 'color', 'b');
% plot lines connecting the input/warped electrode locations with the template locations
my_line3(elec.pnt, avg, 'color', 'r');
my_line3(norm.pnt, avg, 'color', 'm');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif strcmp(cfg.method, 'template') && useheadshape
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% determine electrode selection and overlapping subset for warping
cfg.channel = ft_channelselection(cfg.channel, elec.label);
% make subselection of electrodes
[cfgsel, datsel] = match_str(cfg.channel, elec.label);
elec.label = elec.label(datsel);
elec.pnt = elec.pnt(datsel,:);
fprintf('warping electrodes to head shape... '); % the newline comes later
[norm.pnt, norm.m] = warp_optim(elec.pnt, headshape, cfg.warp);
norm.label = elec.label;
dpre = warp_error([], elec.pnt, headshape, cfg.warp);
dpost = warp_error(norm.m, elec.pnt, headshape, cfg.warp);
fprintf('mean distance prior to warping %f, after warping %f\n', dpre, dpost);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif strcmp(cfg.method, 'fiducial')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% try to determine the fiducials automatically if not specified
if ~isfield(cfg, 'fiducial')
option1 = {'nasion' 'left' 'right'};
option2 = {'nasion' 'lpa' 'rpa'};
option3 = {'nz' 'lpa' 'rpa'};
if length(match_str(elec.label, option1))==3
cfg.fiducial = option1;
elseif length(match_str(elec.label, option2))==3
cfg.fiducial = option2;
elseif length(match_str(elec.label, option3))==3
cfg.fiducial = option3;
else
error('could not determine three fiducials, please specify cfg.fiducial')
end
end
fprintf('using fiducials {''%s'', ''%s'', ''%s''}\n', cfg.fiducial{1}, cfg.fiducial{2}, cfg.fiducial{3});
% determine electrode selection
cfg.channel = ft_channelselection(cfg.channel, elec.label);
[cfgsel, datsel] = match_str(cfg.channel, elec.label);
elec.label = elec.label(datsel);
elec.pnt = elec.pnt(datsel,:);
if length(cfg.fiducial)~=3
error('you must specify three fiducials');
end
% do case-insensitive search for fiducial locations
nas_indx = match_str(lower(elec.label), lower(cfg.fiducial{1}));
lpa_indx = match_str(lower(elec.label), lower(cfg.fiducial{2}));
rpa_indx = match_str(lower(elec.label), lower(cfg.fiducial{3}));
if length(nas_indx)~=1 || length(lpa_indx)~=1 || length(rpa_indx)~=1
error('not all fiducials were found in the electrode set');
end
elec_nas = elec.pnt(nas_indx,:);
elec_lpa = elec.pnt(lpa_indx,:);
elec_rpa = elec.pnt(rpa_indx,:);
% FIXME change the flow in the remainder
% if one or more template electrode sets are specified, then align to the average of those
% if no template is specified, then align so that the fiducials are along the axis
% find the matching fiducials in the template and average them
templ_nas = [];
templ_lpa = [];
templ_rpa = [];
for i=1:Ntemplate
nas_indx = match_str(lower(template(i).label), lower(cfg.fiducial{1}));
lpa_indx = match_str(lower(template(i).label), lower(cfg.fiducial{2}));
rpa_indx = match_str(lower(template(i).label), lower(cfg.fiducial{3}));
if length(nas_indx)~=1 || length(lpa_indx)~=1 || length(rpa_indx)~=1
error(sprintf('not all fiducials were found in template %d', i));
end
templ_nas(end+1,:) = template(i).pnt(nas_indx,:);
templ_lpa(end+1,:) = template(i).pnt(lpa_indx,:);
templ_rpa(end+1,:) = template(i).pnt(rpa_indx,:);
end
templ_nas = mean(templ_nas,1);
templ_lpa = mean(templ_lpa,1);
templ_rpa = mean(templ_rpa,1);
% realign both to a common coordinate system
elec2common = headcoordinates(elec_nas, elec_lpa, elec_rpa);
templ2common = headcoordinates(templ_nas, templ_lpa, templ_rpa);
% compute the combined transform and realign the electrodes to the template
norm = [];
norm.m = elec2common * inv(templ2common);
norm.pnt = warp_apply(norm.m, elec.pnt, 'homogeneous');
norm.label = elec.label;
nas_indx = match_str(lower(elec.label), lower(cfg.fiducial{1}));
lpa_indx = match_str(lower(elec.label), lower(cfg.fiducial{2}));
rpa_indx = match_str(lower(elec.label), lower(cfg.fiducial{3}));
dpre = mean(sqrt(sum((elec.pnt([nas_indx lpa_indx rpa_indx],:) - [templ_nas; templ_lpa; templ_rpa]).^2, 2)));
nas_indx = match_str(lower(norm.label), lower(cfg.fiducial{1}));
lpa_indx = match_str(lower(norm.label), lower(cfg.fiducial{2}));
rpa_indx = match_str(lower(norm.label), lower(cfg.fiducial{3}));
dpost = mean(sqrt(sum((norm.pnt([nas_indx lpa_indx rpa_indx],:) - [templ_nas; templ_lpa; templ_rpa]).^2, 2)));
fprintf('mean distance between fiducials prior to realignment %f, after realignment %f\n', dpre, dpost);
if strcmp(cfg.feedback, 'yes')
% plot the first three electrodes before transformation
my_plot3(elec.pnt(1,:), 'r*');
my_plot3(elec.pnt(2,:), 'r*');
my_plot3(elec.pnt(3,:), 'r*');
my_text3(elec.pnt(1,:), elec.label{1}, 'color', 'r');
my_text3(elec.pnt(2,:), elec.label{2}, 'color', 'r');
my_text3(elec.pnt(3,:), elec.label{3}, 'color', 'r');
% plot the template fiducials
my_plot3(templ_nas, 'b*');
my_plot3(templ_lpa, 'b*');
my_plot3(templ_rpa, 'b*');
my_text3(templ_nas, ' nas', 'color', 'b');
my_text3(templ_lpa, ' lpa', 'color', 'b');
my_text3(templ_rpa, ' rpa', 'color', 'b');
% plot all electrodes after transformation
my_plot3(norm.pnt, 'm.');
my_plot3(norm.pnt(1,:), 'm*');
my_plot3(norm.pnt(2,:), 'm*');
my_plot3(norm.pnt(3,:), 'm*');
my_text3(norm.pnt(1,:), norm.label{1}, 'color', 'm');
my_text3(norm.pnt(2,:), norm.label{2}, 'color', 'm');
my_text3(norm.pnt(3,:), norm.label{3}, 'color', 'm');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif strcmp(cfg.method, 'interactive')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% open a figure
fig = figure;
% add the data to the figure
set(fig, 'CloseRequestFcn', @cb_close);
setappdata(fig, 'elec', elec);
setappdata(fig, 'transform', eye(4));
if useheadshape
setappdata(fig, 'headshape', headshape);
end
if usetemplate
% FIXME interactive realigning to template electrodes is not yet supported
% this requires a consistent handling of channel selection etc.
setappdata(fig, 'template', template);
end
% add the GUI elements
cb_creategui(gca);
cb_redraw(gca);
rotate3d on
waitfor(fig);
% get the data from the figure that was left behind as global variable
global norm
tmp = norm;
clear global norm
norm = tmp;
clear tmp
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif strcmp(cfg.method, 'manual')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% open a figure
fig = figure;
rotate3d on
ft_plot_mesh(headshape, 'edgecolor', 'k')
xyz = ft_select_point3d(headshape, 'multiple', true);
orig.pnt = xyz;
for i=1:size(orig.pnt,1)
orig.label{i,1} = 'unknown';
end
else
error('unknown method');
end
% apply the spatial transformation to all electrodes, and replace the
% electrode labels by their case-sensitive original values
switch cfg.method
case 'template'
norm.pnt = warp_apply(norm.m, orig.pnt, cfg.warp);
case {'fiducial' 'interactive'}
norm.pnt = warp_apply(norm.m, orig.pnt);
case 'manual'
% the positions are already assigned in correspondence with the mesh
norm = orig;
otherwise
error('unknown method');
end
if isfield(orig, 'label')
norm.label = orig.label;
end
% add version information to the configuration
cfg.version.name = mfilename('fullpath');
cfg.version.id = '$Id: ft_electroderealign.m 3710 2011-06-16 14:04:19Z eelspa $';
% add information about the Matlab version used to the configuration
cfg.callinfo.matlab = version();
% add information about the function call to the configuration
cfg.callinfo.proctime = toc(ftFuncTimer);
cfg.callinfo.calltime = ftFuncClock;
cfg.callinfo.user = getusername();
% remember the exact configuration details in the output
norm.cfg = cfg;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% some simple SUBFUNCTIONs that facilitate 3D plotting
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function h = my_plot3(xyz, varargin)
h = plot3(xyz(:,1), xyz(:,2), xyz(:,3), varargin{:});
function h = my_text3(xyz, varargin)
h = text(xyz(:,1), xyz(:,2), xyz(:,3), varargin{:});
function my_line3(xyzB, xyzE, varargin)
for i=1:size(xyzB,1)
line([xyzB(i,1) xyzE(i,1)], [xyzB(i,2) xyzE(i,2)], [xyzB(i,3) xyzE(i,3)], varargin{:})
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION to layout a moderately complex graphical user interface
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function h = layoutgui(fig, geometry, position, style, string, value, tag, callback);
horipos = geometry(1); % lower left corner of the GUI part in the figure
vertpos = geometry(2); % lower left corner of the GUI part in the figure
width = geometry(3); % width of the GUI part in the figure
height = geometry(4); % height of the GUI part in the figure
horidist = 0.05;
vertdist = 0.05;
options = {'units', 'normalized', 'HorizontalAlignment', 'center'}; % 'VerticalAlignment', 'middle'
Nrow = size(position,1);
h = cell(Nrow,1);
for i=1:Nrow
if isempty(position{i})
continue;
end
position{i} = position{i} ./ sum(position{i});
Ncol = size(position{i},2);
ybeg = (Nrow-i )/Nrow + vertdist/2;
yend = (Nrow-i+1)/Nrow - vertdist/2;
for j=1:Ncol
xbeg = sum(position{i}(1:(j-1))) + horidist/2;
xend = sum(position{i}(1:(j ))) - horidist/2;
pos(1) = xbeg*width + horipos;
pos(2) = ybeg*height + vertpos;
pos(3) = (xend-xbeg)*width;
pos(4) = (yend-ybeg)*height;
h{i}{j} = uicontrol(fig, ...
options{:}, ...
'position', pos, ...
'style', style{i}{j}, ...
'string', string{i}{j}, ...
'tag', tag{i}{j}, ...
'value', value{i}{j}, ...
'callback', callback{i}{j} ...
);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_creategui(hObject, eventdata, handles);
% define the position of each GUI element
position = {
[2 1 1 1]
[2 1 1 1]
[2 1 1 1]
[1]
[1]
[1]
[1]
[1 1]
};
% define the style of each GUI element
style = {
{'text' 'edit' 'edit' 'edit'}
{'text' 'edit' 'edit' 'edit'}
{'text' 'edit' 'edit' 'edit'}
{'pushbutton'}
{'pushbutton'}
{'toggle'}
{'toggle'}
{'text' 'edit'}
};
% define the descriptive string of each GUI element
string = {
{'rotate' 0 0 0}
{'translate' 0 0 0}
{'scale' 1 1 1}
{'redisplay'}
{'apply'}
{'toggle labels'}
{'toggle axes'}
{'alpha' 0.7}
};
% define the value of each GUI element
value = {
{[] [] [] []}
{[] [] [] []}
{[] [] [] []}
{[]}
{[]}
{0}
{0}
{[] []}
};
% define a tag for each GUI element
tag = {
{'' 'rx' 'ry' 'rz'}
{'' 'tx' 'ty' 'tz'}
{'' 'sx' 'sy' 'sz'}
{''}
{''}
{'toggle labels'}
{'toggle axes'}
{'' 'alpha'}
};
% define the callback function of each GUI element
callback = {
{[] @cb_redraw @cb_redraw @cb_redraw}
{[] @cb_redraw @cb_redraw @cb_redraw}
{[] @cb_redraw @cb_redraw @cb_redraw}
{@cb_redraw}
{@cb_apply}
{@cb_redraw}
{@cb_redraw}
{[] @cb_redraw}
};
fig = get(hObject, 'parent');
layoutgui(fig, [0.7 0.05 0.25 0.50], position, style, string, value, tag, callback);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_redraw(hObject, eventdata, handles);
fig = get(hObject, 'parent');
headshape = getappdata(fig, 'headshape');
bnd.pnt = headshape.pnt; %ft_plot_mesh wants headshape in bnd fields
bnd.tri = headshape.tri;
elec = getappdata(fig, 'elec');
template = getappdata(fig, 'template');
% get the transformation details
rx = str2num(get(findobj(fig, 'tag', 'rx'), 'string'));
ry = str2num(get(findobj(fig, 'tag', 'ry'), 'string'));
rz = str2num(get(findobj(fig, 'tag', 'rz'), 'string'));
tx = str2num(get(findobj(fig, 'tag', 'tx'), 'string'));
ty = str2num(get(findobj(fig, 'tag', 'ty'), 'string'));
tz = str2num(get(findobj(fig, 'tag', 'tz'), 'string'));
sx = str2num(get(findobj(fig, 'tag', 'sx'), 'string'));
sy = str2num(get(findobj(fig, 'tag', 'sy'), 'string'));
sz = str2num(get(findobj(fig, 'tag', 'sz'), 'string'));
R = rotate ([rx ry rz]);
T = translate([tx ty tz]);
S = scale ([sx sy sz]);
H = S * T * R;
elec = ft_transform_sens(H, elec);
axis vis3d; cla
xlabel('x')
ylabel('y')
zlabel('z')
if ~isempty(template)
if size(template.pnt, 2)==2
hs = plot(template.pnt(:,1), template.pnt(:,2), 'b.', 'MarkerSize', 20);
else
hs = plot3(template.pnt(:,1), template.pnt(:,2), template.pnt(:,3), 'b.', 'MarkerSize', 20);
end
end
if ~isempty(headshape)
% plot the faces of the 2D or 3D triangulation
skin = [255 213 119]/255;
brain = [202 100 100]/255;
cortex = [255 213 119]/255;
ft_plot_mesh(bnd,'facecolor', skin,'EdgeColor','none','facealpha',0.7);
lighting gouraud
material shiny
camlight
end
if isfield(elec, 'fid') && ~isempty(elec.fid.pnt)
ft_plot_sens(elec.fid,'style', 'r*');
end
if get(findobj(fig, 'tag', 'toggle axes'), 'value')
axis on
grid on
else
axis off
grid on
end
if get(findobj(fig, 'tag', 'toggle labels'), 'value')
cfg.label = 'on';
else
cfg.label = 'off';
end
hold on
ft_plot_sens(elec,'label',cfg.label);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_apply(hObject, eventdata, handles);
fig = get(hObject, 'parent');
elec = getappdata(fig, 'elec');
transform = getappdata(fig, 'transform');
% get the transformation details
rx = str2num(get(findobj(fig, 'tag', 'rx'), 'string'));
ry = str2num(get(findobj(fig, 'tag', 'ry'), 'string'));
rz = str2num(get(findobj(fig, 'tag', 'rz'), 'string'));
tx = str2num(get(findobj(fig, 'tag', 'tx'), 'string'));
ty = str2num(get(findobj(fig, 'tag', 'ty'), 'string'));
tz = str2num(get(findobj(fig, 'tag', 'tz'), 'string'));
sx = str2num(get(findobj(fig, 'tag', 'sx'), 'string'));
sy = str2num(get(findobj(fig, 'tag', 'sy'), 'string'));
sz = str2num(get(findobj(fig, 'tag', 'sz'), 'string'));
R = rotate ([rx ry rz]);
T = translate([tx ty tz]);
S = scale ([sx sy sz]);
H = S * T * R;
elec = ft_transform_headshape(H, elec);
transform = H * transform;
set(findobj(fig, 'tag', 'rx'), 'string', 0);
set(findobj(fig, 'tag', 'ry'), 'string', 0);
set(findobj(fig, 'tag', 'rz'), 'string', 0);
set(findobj(fig, 'tag', 'tx'), 'string', 0);
set(findobj(fig, 'tag', 'ty'), 'string', 0);
set(findobj(fig, 'tag', 'tz'), 'string', 0);
set(findobj(fig, 'tag', 'sx'), 'string', 1);
set(findobj(fig, 'tag', 'sy'), 'string', 1);
set(findobj(fig, 'tag', 'sz'), 'string', 1);
setappdata(fig, 'elec', elec);
setappdata(fig, 'transform', transform);
cb_redraw(hObject);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_close(hObject, eventdata, handles);
% make the current transformation permanent and subsequently allow deleting the figure
cb_apply(gca);
% get the updated electrode from the figure
fig = hObject;
% hmmm, this is ugly
global norm
norm = getappdata(fig, 'elec');
norm.m = getappdata(fig, 'transform');
set(fig, 'CloseRequestFcn', @delete);
delete(fig);
|
github
|
philippboehmsturm/antx-master
|
ft_singleplotTFR.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_singleplotTFR.m
| 19,869 |
utf_8
|
a7375cdecd992f1c7ac3a85269e85753
|
function [cfg] = ft_singleplotTFR(cfg, data)
% ft_singleplotTFR plots the time-frequency representations of power of a
% single channel or the average over multiple channels.
%
% Use as:
% ft_singleplotTFR(cfg,data)
%
% The data can be a time-frequency representation of power that was
% computed using the FT_FREQANALYSIS function.
%
% The configuration can have the following parameters:
% cfg.xparam = field to be plotted on x-axis, e.g. 'time' (default depends on data.dimord)
% cfg.yparam = field to be plotted on y-axis, e.g. 'freq' (default depends on data.dimord)
% cfg.zparam = field to be plotted on z-axis, e.g. 'powspcrtrm' (default depends on data.dimord)
% cfg.maskparameter = field in the data to be used for masking of data
% (not possible for mean over multiple channels, or when input contains multiple subjects
% or trials)
% cfg.maskstyle = style used to mask nans, 'opacity' or 'saturation' (default = 'opacity')
% use 'saturation' when saving to vector-format (like *.eps) to avoid all sorts of image-problems
% cfg.maskalpha = alpha value used for masking areas dictated by cfg.maskparameter (0 - 1, default = 1)
% cfg.xlim = 'maxmin' or [xmin xmax] (default = 'maxmin')
% cfg.ylim = 'maxmin' or [ymin ymax] (default = 'maxmin')
% cfg.zlim = 'maxmin','maxabs' or [zmin zmax] (default = 'maxmin')
% cfg.baseline = 'yes','no' or [time1 time2] (default = 'no'), see FT_FREQBASELINE
% cfg.baselinetype = 'absolute' or 'relative' (default = 'absolute')
% cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all')
% cfg.channel = Nx1 cell-array with selection of channels (default = 'all'),
% see FT_CHANNELSELECTION for details
% cfg.refchannel = name of reference channel for visualising connectivity, can be 'gui'
% cfg.fontsize = font size of title (default = 8)
% cfg.hotkeys = enables hotkeys (up/down arrows) for dynamic colorbar adjustment
% cfg.colormap = any sized colormap, see COLORMAP
% cfg.colorbar = 'yes', 'no' (default = 'yes')
% cfg.interactive = Interactive plot 'yes' or 'no' (default = 'no')
% In a interactive plot you can select areas and produce a new
% interactive plot when a selected area is clicked. Multiple areas
% can be selected by holding down the SHIFT key.
% cfg.renderer = 'painters', 'zbuffer',' opengl' or 'none' (default = [])
% cfg.masknans = 'yes' or 'no' (default = 'yes')
%
% See also:
% FT_SINGLEPLOTER, FT_MULTIPLOTER, FT_MULTIPLOTTFR, FT_TOPOPLOTER, FT_TOPOPLOTTFR
% This function depends on FT_FREQBASELINE which has the following options:
% cfg.baseline, documented
% cfg.baselinetype, documented
% Copyright (C) 2005-2006, F.C. Donders Centre
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_singleplotTFR.m 3733 2011-06-29 08:02:30Z jorhor $
ft_defaults
cfg = ft_checkconfig(cfg, 'trackconfig', 'on');
cfg = ft_checkconfig(cfg, 'unused', {'cohtargetchannel'});
cfg = ft_checkconfig(cfg, 'renamedval', {'zlim', 'absmax', 'maxabs'});
cfg = ft_checkconfig(cfg, 'renamedval', {'matrixside', 'feedforward', 'outflow'});
cfg = ft_checkconfig(cfg, 'renamedval', {'matrixside', 'feedback', 'inflow'});
cfg = ft_checkconfig(cfg, 'renamed', {'channelindex', 'channel'});
cfg = ft_checkconfig(cfg, 'renamed', {'channelname', 'channel'});
cfg = ft_checkconfig(cfg, 'renamed', {'cohrefchannel', 'refchannel'});
% Set the defaults:
cfg.baseline = ft_getopt(cfg, 'baseline', 'no');
cfg.baselinetype = ft_getopt(cfg, 'baselinetype', 'absolute');
cfg.trials = ft_getopt(cfg, 'trials', 'all');
cfg.xlim = ft_getopt(cfg, 'xlim', 'maxmin');
cfg.ylim = ft_getopt(cfg, 'ylim', 'maxmin');
cfg.zlim = ft_getopt(cfg, 'zlim', 'maxmin');
cfg.fontsize = ft_getopt(cfg, 'fontsize', 8);
cfg.colorbar = ft_getopt(cfg, 'colorbar', 'yes');
cfg.interactive = ft_getopt(cfg, 'interactive', 'no');
cfg.hotkeys = ft_getopt(cfg, 'hotkeys', 'no');
cfg.renderer = ft_getopt(cfg, 'renderer', []);
cfg.maskalpha = ft_getopt(cfg, 'maskalpha', 1);
cfg.maskparameter = ft_getopt(cfg, 'maskparameter',[]);
cfg.maskstyle = ft_getopt(cfg, 'maskstyle', 'opacity');
cfg.channel = ft_getopt(cfg, 'channel', 'all');
cfg.masknans = ft_getopt(cfg, 'masknans', 'yes');
cfg.matrixside = ft_getopt(cfg, 'matrixside', 'outflow');
% for backward compatibility with old data structures
data = ft_checkdata(data, 'datatype', 'freq');
dimord = data.dimord;
dimtok = tokenize(dimord, '_');
% Set x/y/zparam defaults
if ~any(ismember(dimtok, 'time'))
error('input data needs a time dimension');
else
if ~isfield(cfg, 'xparam'), cfg.xparam='time'; end
if ~isfield(cfg, 'yparam'), cfg.yparam='freq'; end
if ~isfield(cfg, 'zparam'), cfg.zparam='powspctrm'; end
end
if isfield(cfg, 'channel') && isfield(data, 'label')
cfg.channel = ft_channelselection(cfg.channel, data.label);
elseif isfield(cfg, 'channel') && isfield(data, 'labelcmb')
cfg.channel = ft_channelselection(cfg.channel, unique(data.labelcmb(:)));
end
if isempty(cfg.channel)
error('no channels selected');
end
% check whether rpt/subj is present and remove if necessary and whether
hasrpt = any(ismember(dimtok, {'rpt' 'subj'}));
if hasrpt,
% this also deals with fourier-spectra in the input
% or with multiple subjects in a frequency domain stat-structure
% on the fly computation of coherence spectrum is not supported
if isfield(data, 'crsspctrm'),
data = rmfield(data, 'crsspctrm');
end
tmpcfg = [];
tmpcfg.trials = cfg.trials;
tmpcfg.jackknife = 'no';
if isfield(cfg, 'zparam') && ~strcmp(cfg.zparam,'powspctrm')
% freqdesctiptives will only work on the powspctrm field
% hence a temporary copy of the data is needed
tempdata.dimord = data.dimord;
tempdata.freq = data.freq;
tempdata.label = data.label;
tempdata.powspctrm = data.(cfg.zparam);
tempdata.cfg = data.cfg;
tempdata = ft_freqdescriptives(tmpcfg, tempdata);
data.(cfg.zparam) = tempdata.powspctrm;
clear tempdata
else
data = ft_freqdescriptives(tmpcfg, data);
end
dimord = data.dimord;
dimtok = tokenize(dimord, '_');
end % if hasrpt
% Handle the bivariate case
% Check for bivariate metric with 'chan_chan' in the dimord
selchan = strmatch('chan', dimtok);
isfull = length(selchan)>1;
% Check for bivariate metric with a labelcmb
haslabelcmb = isfield(data, 'labelcmb');
if (isfull || haslabelcmb) && isfield(data, cfg.zparam)
% A reference channel is required:
if ~isfield(cfg, 'refchannel')
error('no reference channel is specified');
end
% check for refchannel being part of selection
if ~strcmp(cfg.refchannel,'gui')
if (isfull && ~any(ismember(data.label, cfg.refchannel))) || ...
(haslabelcmb && ~any(ismember(data.labelcmb(:), cfg.refchannel)))
error('cfg.refchannel is a not present in the (selected) channels)')
end
end
% Interactively select the reference channel
if strcmp(cfg.refchannel, 'gui')
error('coh.refchannel = ''gui'' is not supported at the moment for ft_singleplotTFR');
%
% % Open a single figure with the channel layout, the user can click on a reference channel
% h = clf;
% ft_plot_lay(lay, 'box', false);
% title('Select the reference channel by dragging a selection window, more than 1 channel can be selected...');
% % add the channel information to the figure
% info = guidata(gcf);
% info.x = lay.pos(:,1);
% info.y = lay.pos(:,2);
% info.label = lay.label;
% guidata(h, info);
% %set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'callback', {@select_topoplotER, cfg, data}});
% set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_multiplotTFR, cfg, data}, 'event', 'WindowButtonUpFcn'});
% set(gcf, 'WindowButtonDownFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_multiplotTFR, cfg, data}, 'event', 'WindowButtonDownFcn'});
% set(gcf, 'WindowButtonMotionFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_multiplotTFR, cfg, data}, 'event', 'WindowButtonMotionFcn'});
% return
end
if ~isfull,
% Convert 2-dimensional channel matrix to a single dimension:
if isempty(cfg.matrixside)
sel1 = strmatch(cfg.refchannel, data.labelcmb(:,2), 'exact');
sel2 = strmatch(cfg.refchannel, data.labelcmb(:,1), 'exact');
elseif strcmp(cfg.matrixside, 'outflow')
sel1 = [];
sel2 = strmatch(cfg.refchannel, data.labelcmb(:,1), 'exact');
elseif strcmp(cfg.matrixside, 'inflow')
sel1 = strmatch(cfg.refchannel, data.labelcmb(:,2), 'exact');
sel2 = [];
end
fprintf('selected %d channels for %s\n', length(sel1)+length(sel2), cfg.zparam);
data.(cfg.zparam) = data.(cfg.zparam)([sel1;sel2],:,:);
data.label = [data.labelcmb(sel1,1);data.labelcmb(sel2,2)];
data.labelcmb = data.labelcmb([sel1;sel2],:);
data = rmfield(data, 'labelcmb');
else
% General case
sel = match_str(data.label, cfg.refchannel);
siz = [size(data.(cfg.zparam)) 1];
if strcmp(cfg.matrixside, 'inflow') || isempty(cfg.matrixside)
%the interpretation of 'inflow' and 'outflow' depend on
%the definition in the bivariate representation of the data
%data.(cfg.zparam) = reshape(mean(data.(cfg.zparam)(:,sel,:),2),[siz(1) 1 siz(3:end)]);
sel1 = 1:siz(1);
sel2 = sel;
meandir = 2;
elseif strcmp(cfg.matrixside, 'outflow')
%data.(cfg.zparam) = reshape(mean(data.(cfg.zparam)(sel,:,:),1),[siz(1) 1 siz(3:end)]);
sel1 = sel;
sel2 = 1:siz(1);
meandir = 1;
elseif strcmp(cfg.matrixside, 'ff-fd')
error('cfg.matrixside = ''ff-fd'' is not supported anymore, you have to manually subtract the two before the call to ft_topoplotER');
elseif strcmp(cfg.matrixside, 'fd-ff')
error('cfg.matrixside = ''fd-ff'' is not supported anymore, you have to manually subtract the two before the call to ft_topoplotER');
end %if matrixside
end %if ~isfull
end %handle the bivariate data
% Apply baseline correction:
if ~strcmp(cfg.baseline, 'no')
data = ft_freqbaseline(cfg, data);
end
% Get physical x-axis range:
if strcmp(cfg.xlim,'maxmin')
xmin = min(data.(cfg.xparam));
xmax = max(data.(cfg.xparam));
else
xmin = cfg.xlim(1);
xmax = cfg.xlim(2);
end
% Replace value with the index of the nearest bin
if ~isempty(cfg.xparam)
xmin = nearest(data.(cfg.xparam), xmin);
xmax = nearest(data.(cfg.xparam), xmax);
end
% Get physical y-axis range:
if strcmp(cfg.ylim,'maxmin')
ymin = min(data.(cfg.yparam));
ymax = max(data.(cfg.yparam));
else
ymin = cfg.ylim(1);
ymax = cfg.ylim(2);
end
% Replace value with the index of the nearest bin
if ~isempty(cfg.yparam)
ymin = nearest(data.(cfg.yparam), ymin);
ymax = nearest(data.(cfg.yparam), ymax);
end
% test if X and Y are linearly spaced (to within 10^-12): % FROM UIMAGE
x = data.(cfg.xparam)(xmin:xmax);
y = data.(cfg.yparam)(ymin:ymax);
dx = min(diff(x)); % smallest interval for X
dy = min(diff(y)); % smallest interval for Y
evenx = all(abs(diff(x)/dx-1)<1e-12); % true if X is linearly spaced
eveny = all(abs(diff(y)/dy-1)<1e-12); % true if Y is linearly spaced
% masking only possible for evenly spaced axis
if strcmp(cfg.masknans, 'yes') && (~evenx || ~eveny)
warning('(one of the) axis are not evenly spaced -> nans cannot be masked out -> cfg.masknans is set to ''no'';')
cfg.masknans = 'no';
end
if ~isempty(cfg.maskparameter) && (~evenx || ~eveny)
warning('(one of the) axis are not evenly spaced -> no masking possible -> cfg.maskparameter cleared')
cfg.maskparameter = [];
end
% perform channel selection
selchannel = ft_channelselection(cfg.channel, data.label);
sellab = match_str(data.label, selchannel);
% cfg.maskparameter only possible for single channel
if length(sellab) > 1 && ~isempty(cfg.maskparameter)
warning('no masking possible for average over multiple channels -> cfg.maskparameter cleared')
cfg.maskparameter = [];
end
dat = data.(cfg.zparam);
if isfull
dat = dat(sel1, sel2, ymin:ymax, xmin:xmax);
dat = nanmean(dat, meandir);
siz = size(dat);
dat = reshape(dat, [max(siz(1:2)) siz(3) siz(4)]);
dat = dat(sellab, :, :);
elseif haslabelcmb
dat = dat(sellab, ymin:ymax, xmin:xmax);
else
dat = dat(sellab, ymin:ymax, xmin:xmax);
end
if ~isempty(cfg.maskparameter)
mask = data.(cfg.maskparameter);
if isfull && cfg.maskalpha == 1
mask = mask(sel1, sel2, ymin:ymax, xmin:xmax);
mask = nanmean(mask, meandir);
siz = size(mask);
mask = reshape(mask, [max(siz(1:2)) siz(3) siz(4)]);
mask = reshape(mask(sellab, :, :), [siz(3) siz(4)]);
elseif haslabelcmb && cfg.maskalpha == 1
mask = mask(sellab, ymin:ymax, xmin:xmax);
elseif cfg.maskalpha == 1
mask = mask(sellab, ymin:ymax, xmin:xmax);
elseif isfull && cfg.maskalpha ~= 1 %% check me
maskl = mask(sel1, sel2, ymin:ymax, xmin:xmax);
maskl = nanmean(maskl, meandir);
siz = size(maskl);
maskl = reshape(maskl, [max(siz(1:2)) siz(3) siz(4)]);
maskl = squeeze(reshape(maskl(sellab, :, :), [siz(3) siz(4)]));
mask = zeros(size(maskl));
mask(maskl) = 1;
mask(~maskl) = cfg.maskalpha;
elseif haslabelcmb && cfg.maskalpha ~= 1
maskl = squeeze(mask(sellab, ymin:ymax, xmin:xmax));
mask = zeros(size(maskl));
mask(maskl) = 1;
mask(~maskl) = cfg.maskalpha;
elseif cfg.maskalpha ~= 1
maskl = squeeze(mask(sellab, ymin:ymax, xmin:xmax));
mask = zeros(size(maskl));
mask(maskl) = 1;
mask(~maskl) = cfg.maskalpha;
end
end
siz = size(dat);
datamatrix = reshape(mean(dat, 1), siz(2:end));
xvector = data.(cfg.xparam)(xmin:xmax);
yvector = data.(cfg.yparam)(ymin:ymax);
% Get physical z-axis range (color axis):
if strcmp(cfg.zlim,'maxmin')
zmin = min(datamatrix(:));
zmax = max(datamatrix(:));
elseif strcmp(cfg.zlim,'maxabs')
zmin = -max(abs(datamatrix(:)));
zmax = max(abs(datamatrix(:)));
else
zmin = cfg.zlim(1);
zmax = cfg.zlim(2);
end
% set colormap
if isfield(cfg,'colormap')
if size(cfg.colormap,2)~=3, error('singleplotTFR(): Colormap must be a n x 3 matrix'); end
set(gcf,'colormap',cfg.colormap);
end;
% Draw plot (and mask NaN's if requested):
cla
if isequal(cfg.masknans,'yes') && isempty(cfg.maskparameter)
nans_mask = ~isnan(datamatrix);
mask = double(nans_mask);
ft_plot_matrix(xvector, yvector, datamatrix, 'clim',[zmin,zmax],'tag','cip','highlightstyle',cfg.maskstyle,'highlight', mask)
elseif isequal(cfg.masknans,'yes') && ~isempty(cfg.maskparameter)
nans_mask = ~isnan(datamatrix);
mask = mask .* nans_mask;
mask = double(mask);
ft_plot_matrix(xvector, yvector, datamatrix, 'clim',[zmin,zmax],'tag','cip','highlightstyle',cfg.maskstyle,'highlight', mask)
elseif isequal(cfg.masknans,'no') && ~isempty(cfg.maskparameter)
mask = double(mask);
ft_plot_matrix(xvector, yvector, datamatrix, 'clim',[zmin,zmax],'tag','cip','highlightstyle',cfg.maskstyle,'highlight', mask)
else
ft_plot_matrix(xvector, yvector, datamatrix, 'clim',[zmin,zmax],'tag','cip')
end
hold on
axis xy;
set(gca,'Color','k')
if isequal(cfg.colorbar,'yes')
colorbar;
end
% Set adjust color axis
if strcmp('yes',cfg.hotkeys)
% Attach data and cfg to figure and attach a key listener to the figure
set(gcf, 'KeyPressFcn', {@key_sub, zmin, zmax})
end
% Make the figure interactive:
if strcmp(cfg.interactive, 'yes')
set(gcf, 'WindowButtonUpFcn', {@ft_select_range, 'multiple', false, 'callback', {@select_topoplotTFR, cfg, data}, 'event', 'WindowButtonUpFcn'});
set(gcf, 'WindowButtonDownFcn', {@ft_select_range, 'multiple', false, 'callback', {@select_topoplotTFR, cfg, data}, 'event', 'WindowButtonDownFcn'});
set(gcf, 'WindowButtonMotionFcn', {@ft_select_range, 'multiple', false, 'callback', {@select_topoplotTFR, cfg, data}, 'event', 'WindowButtonMotionFcn'});
end
% Create title text containing channel name(s) and channel number(s):
if length(sellab) == 1
t = [char(cfg.channel) ' / ' num2str(sellab) ];
else
t = sprintf('mean(%0s)', join(',', cfg.channel));
end
h = title(t,'fontsize', cfg.fontsize);
axis tight;
hold off;
% Set renderer if specified
if ~isempty(cfg.renderer)
set(gcf, 'renderer', cfg.renderer)
end
% get the output cfg
cfg = ft_checkconfig(cfg, 'trackconfig', 'off', 'checksize', 'yes');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function t = join(separator,cells)
if isempty(cells)
t = '';
return;
end
t = char(cells{1});
for i=2:length(cells)
t = [t separator char(cells{i})];
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION which is called by ft_select_channel in case cfg.refchannel='gui'
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function select_singleplotTFR(label, cfg, varargin)
cfg.refchannel = label;
fprintf('selected cfg.refchannel = ''%s''\n', cfg.refchannel);
p = get(gcf, 'Position');
f = figure;
set(f, 'Position', p);
ft_singleplotTFR(cfg, varargin{:});
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION which is called after selecting a time range
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function select_topoplotTFR(range, cfg, varargin)
cfg.comment = 'auto';
cfg.xlim = range(1:2);
cfg.ylim = range(3:4);
% compatibility fix for new ft_topoplotER/TFR cfg options
if isfield(cfg,'showlabels') && strcmp(cfg.showlabels,'yes')
cfg = rmfield(cfg,'showlabels');
cfg.marker = 'labels';
elseif isfield(cfg,'showlabels') && strcmp(cfg.showlabels,'no')
cfg = rmfield(cfg,'showlabels');
cfg.marker = 'on';
end
fprintf('selected cfg.xlim = [%f %f]\n', cfg.xlim(1), cfg.xlim(2));
fprintf('selected cfg.ylim = [%f %f]\n', cfg.ylim(1), cfg.ylim(2));
p = get(gcf, 'Position');
f = figure;
set(f, 'Position', p);
ft_topoplotER(cfg, varargin{:});
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION which handles hot keys in the current plot
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function key_sub(handle, eventdata, varargin)
incr = (max(caxis)-min(caxis)) /10;
% symmetrically scale color bar down by 10 percent
if strcmp(eventdata.Key,'uparrow')
caxis([min(caxis)-incr max(caxis)+incr]);
% symmetrically scale color bar up by 10 percent
elseif strcmp(eventdata.Key,'downarrow')
caxis([min(caxis)+incr max(caxis)-incr]);
% resort to minmax of data for colorbar
elseif strcmp(eventdata.Key,'m')
caxis([varargin{1} varargin{2}]);
end
|
github
|
philippboehmsturm/antx-master
|
ft_multiplotER.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_multiplotER.m
| 30,333 |
utf_8
|
e0c6664daaa3c05950c772ba99a61345
|
function [cfg] = ft_multiplotER(cfg, varargin)
% ft_multiplotER plots the event-related fields or potentials versus time
% or of oscillatory activity (power or coherence) versus frequency. Multiple
% datasets can be overlayed. The plots are arranged according to their
% location specified in the layout.
%
% Use as:
% ft_multiplotER(cfg, data)
% ft_multiplotER(cfg, data, data2, ..., dataN)
%
% The data can be an ERP/ERF produced by FT_TIMELOCKANALYSIS, a powerspectrum
% produced by FT_FREQANALYSIS or a coherencespectrum produced by FT_FREQDESCRIPTIVES.
% If you specify multiple datasets they must contain the same channels, etc.
%
% The configuration can have the following parameters:
% cfg.xparam = field to be plotted on x-axis (default depends on data.dimord)
% 'time' or 'freq'
% cfg.zparam = field to be plotted on y-axis (default depends on data.dimord)
% 'avg', 'powspctrm' or 'cohspctrm'
% cfg.maskparameter = field in the first dataset to be used for marking significant data
% cfg.maskstyle = style used for masking of data, 'box', 'thickness' or 'saturation' (default = 'box')
% cfg.xlim = 'maxmin' or [xmin xmax] (default = 'maxmin')
% cfg.ylim = 'maxmin' or [ymin ymax] (default = 'maxmin')
% cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), see FT_CHANNELSELECTION for details
% cfg.refchannel = name of reference channel for visualising connectivity, can be 'gui'
% cfg.baseline = 'yes','no' or [time1 time2] (default = 'no'), see FT_TIMELOCKBASELINE or FT_FREQBASELINE
% cfg.baselinetype = 'absolute' or 'relative' (default = 'absolute')
% cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all')
% cfg.axes = 'yes', 'no' (default = 'yes')
% Draw x- and y-axes for each graph
% cfg.box = 'yes', 'no' (default = 'no')
% Draw a box around each graph
% cfg.comment = string of text (default = date + colors)
% Add 'comment' to graph (according to COMNT in the layout)
% cfg.showlabels = 'yes', 'no' (default = 'no')
% cfg.showoutline = 'yes', 'no' (default = 'no')
% cfg.fontsize = font size of comment and labels (if present) (default = 8)
% cfg.interactive = Interactive plot 'yes' or 'no' (default = 'no')
% In a interactive plot you can select areas and produce a new
% interactive plot when a selected area is clicked. Multiple areas
% can be selected by holding down the SHIFT key.
% cfg.renderer = 'painters', 'zbuffer',' opengl' or 'none' (default = [])
% cfg.linestyle = linestyle/marker type, see options of the matlab PLOT function (default = '-')
% can be a single style for all datasets, or a cell-array containing one style for each dataset
% cfg.linewidth = linewidth in points (default = 0.5)
% cfg.graphcolor = color(s) used for plotting the dataset(s) (default = 'brgkywrgbkywrgbkywrgbkyw')
% alternatively, colors can be specified as Nx3 matrix of RGB values
%
% cfg.layout = specify the channel layout for plotting using one of
% the following ways:
%
% The layout defines how the channels are arranged and what the size of each
% subplot is. You can specify the layout in a variety of ways:
% - you can provide a pre-computed layout structure (see prepare_layout)
% - you can give the name of an ascii layout file with extension *.lay
% - you can give the name of an electrode file
% - you can give an electrode definition, i.e. "elec" structure
% - you can give a gradiometer definition, i.e. "grad" structure
% If you do not specify any of these and the data structure contains an
% electrode or gradiometer structure, that will be used for creating a
% layout. If you want to have more fine-grained control over the layout
% of the subplots, you should create your own layout file.
%
% To facilitate data-handling and distributed computing with the peer-to-peer
% module, this function has the following option:
% cfg.inputfile = ...
% If you specify this option the input data will be read from a *.mat
% file on disk. This mat files should contain only a single variable named 'data',
% corresponding to the input structure. For this particular function, the
% data should be provided as a cell array.
%
% See also:
% FT_MULTIPLOTTFR, FT_SINGLEPLOTER, FT_SINGLEPLOTTFR, FT_TOPOPLOTER, FT_TOPOPLOTTFR,
% FT_PREPARE_LAYOUT
% Undocumented local options:
% cfg.layoutname
%
% This function depends on FT_TIMELOCKBASELINE which has the following options:
% cfg.baseline, documented
% cfg.channel
% cfg.baselinewindow
% cfg.previous
% cfg.version
%
% This function depends on FT_FREQBASELINE which has the following options:
% cfg.baseline, documented
% cfg.baselinetype
% Copyright (C) 2003-2006, Ole Jensen
% Copyright (C) 2007-2011, Roemer van der Meij & Jan-Mathijs Schoffelen
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_multiplotER.m 3734 2011-06-29 08:14:36Z jorhor $
ft_defaults
cfg = ft_checkconfig(cfg, 'trackconfig', 'on');
cfg = ft_checkconfig(cfg, 'unused', {'cohtargetchannel'});
cfg = ft_checkconfig(cfg, 'renamedval', {'zlim', 'absmax', 'maxabs'});
cfg = ft_checkconfig(cfg, 'renamedval', {'matrixside', 'feedforward', 'outflow'});
cfg = ft_checkconfig(cfg, 'renamedval', {'matrixside', 'feedback', 'inflow'});
cfg = ft_checkconfig(cfg, 'renamed', {'cohrefchannel', 'refchannel'});
% set default for inputfile
if ~isfield(cfg, 'inputfile'), cfg.inputfile = []; end
hasdata = nargin>1;
hasinputfile = ~isempty(cfg.inputfile);
if hasdata && hasinputfile
error('cfg.inputfile should not be used in conjunction with giving input data to this function');
end
if hasdata
% do nothing
elseif hasinputfile
if ~ischar(cfg.inputfile)
cfg.inputfile = {cfg.inputfile};
end
for i = 1:numel(cfg.inputfile)
varargin{i} = loadvar(cfg.inputfile{i}, 'data'); % read datasets
end
if isfield(cfg, 'interactive') && strcmp(cfg.interactive, 'yes'),
warning('switching off interactive mode, this is not supported when loading an inputfile from disk');
end
end
% set the defaults:
if ~isfield(cfg,'baseline'), cfg.baseline = 'no'; end
if ~isfield(cfg,'trials'), cfg.trials = 'all'; end
if ~isfield(cfg,'xlim'), cfg.xlim = 'maxmin'; end
if ~isfield(cfg,'ylim'), cfg.ylim = 'maxmin'; end
if ~isfield(cfg,'comment'), cfg.comment = strcat([date '\n']); end
if ~isfield(cfg,'axes'), cfg.axes = 'yes'; end
if ~isfield(cfg,'showlabels'), cfg.showlabels = 'no'; end
if ~isfield(cfg,'showoutline'), cfg.showoutline = 'no'; end
if ~isfield(cfg,'box'), cfg.box = 'no'; end
if ~isfield(cfg,'fontsize'), cfg.fontsize = 8; end
if ~isfield(cfg,'graphcolor'), cfg.graphcolor = 'brgkywrgbkywrgbkywrgbkyw'; end
if ~isfield(cfg,'interactive'), cfg.interactive = 'no'; end
if ~isfield(cfg,'renderer'), cfg.renderer = []; end
if ~isfield(cfg,'maskparameter'), cfg.maskparameter = []; end
if ~isfield(cfg,'linestyle'), cfg.linestyle = '-'; end
if ~isfield(cfg,'linewidth'), cfg.linewidth = 0.5; end
if ~isfield(cfg,'maskstyle'), cfg.maskstyle = 'box'; end
if ~isfield(cfg,'channel'), cfg.channel = 'all'; end
if ~isfield(cfg, 'matrixside'), cfg.matrixside = 'outflow'; end
Ndata = numel(varargin);
%FIXME rename matrixside and refchannel in more meaningful options
if ischar(cfg.graphcolor)
GRAPHCOLOR = ['k' cfg.graphcolor];
elseif isnumeric(cfg.graphcolor)
GRAPHCOLOR = [0 0 0; cfg.graphcolor];
end
% check for linestyle being a cell-array, check it's length, and lengthen it if does not have enough styles in it
if ischar(cfg.linestyle)
cfg.linestyle = {cfg.linestyle};
end
if Ndata > 1
if (length(cfg.linestyle) < Ndata ) && (length(cfg.linestyle) > 1)
error('either specify cfg.linestyle as a cell-array with one cell for each dataset, or only specify one linestyle')
elseif (length(cfg.linestyle) < Ndata ) && (length(cfg.linestyle) == 1)
tmpstyle = cfg.linestyle{1};
cfg.linestyle = cell(Ndata , 1);
for idataset = 1:Ndata
cfg.linestyle{idataset} = tmpstyle;
end
end
end
% % interactive plotting is not allowed with more than 1 input
% if numel(varargin)>1 && strcmp(cfg.interactive, 'yes')
% error('interactive plotting is not supported with more than 1 input data set');
% end
% ensure that the input is correct, also backward compatibility with old data structures:
for i=1:Ndata
varargin{i} = ft_checkdata(varargin{i}, 'datatype', {'timelock', 'freq'});
dtype{i} = ft_datatype(varargin{i});
% this is needed for correct treatment of GRAPHCOLOR later on
if nargin>1,
if ~isempty(inputname(i+1))
iname{i+1} = inputname(i+1);
else
iname{i+1} = ['input',num2str(i,'%02d')];
end
else
iname{i+1} = cfg.inputfile{i};
end
end
if Ndata>1,
if ~all(strcmp(dtype{1}, dtype))
error('input data are of different type; this is not supported');
end
end
dtype = dtype{1};
dimord = varargin{1}.dimord;
dimtok = tokenize(dimord, '_');
% Set x/y/zparam defaults according to datatype and dimord
switch dtype
case 'timelock'
if ~isfield(cfg, 'xparam'), cfg.xparam = 'time'; end
if ~isfield(cfg, 'yparam'), cfg.yparam = ''; end
if ~isfield(cfg, 'zparam'), cfg.zparam = 'avg'; end
case 'freq'
if any(ismember(dimtok, 'time'))
if ~isfield(cfg, 'xparam'), cfg.xparam = 'time'; end
if ~isfield(cfg, 'yparam'), cfg.yparam = 'freq'; end %FIXME
if ~isfield(cfg, 'zparam'), cfg.zparam = 'powspctrm'; end
else
if ~isfield(cfg, 'xparam'), cfg.xparam = 'freq'; end
if ~isfield(cfg, 'yparam'), cfg.yparam = ''; end
if ~isfield(cfg, 'zparam'), cfg.zparam = 'powspctrm'; end
end
case 'comp'
% not supported
otherwise
% not supported
end
% user specified own fields, but no yparam (which is not asked in help)
if isfield(cfg, 'xparam') && isfield(cfg, 'zparam') && ~isfield(cfg, 'yparam')
cfg.yparam = '';
end
if isfield(cfg, 'channel') && isfield(varargin{1}, 'label')
cfg.channel = ft_channelselection(cfg.channel, varargin{1}.label);
elseif isfield(cfg, 'channel') && isfield(varargin{1}, 'labelcmb')
cfg.channel = ft_channelselection(cfg.channel, unique(varargin{1}.labelcmb(:)));
end
% perform channel selection but only allow this when cfg.interactive = 'no'
if isfield(varargin{1}, 'label') && strcmp(cfg.interactive, 'no')
selchannel = ft_channelselection(cfg.channel, varargin{1}.label);
elseif isfield(varargin{1}, 'labelcmb') && strcmp(cfg.interactive, 'no')
selchannel = ft_channelselection(cfg.channel, unique(varargin{1}.labelcmb(:)));
end
% check whether rpt/subj is present and remove if necessary and whether
hasrpt = sum(ismember(dimtok, {'rpt' 'subj'}));
if strcmp(dtype, 'timelock') && hasrpt,
tmpcfg = [];
tmpcfg.trials = cfg.trials;
for i=1:Ndata
varargin{i} = ft_timelockanalysis(tmpcfg, varargin{i});
end
dimord = varargin{1}.dimord;
dimtok = tokenize(dimord, '_');
elseif strcmp(dtype, 'freq') && hasrpt,
% this also deals with fourier-spectra in the input
% or with multiple subjects in a frequency domain stat-structure
% on the fly computation of coherence spectrum is not supported
for i=1:Ndata
if isfield(varargin{i}, 'crsspctrm'),
varargin{i} = rmfield(varargin{i}, 'crsspctrm');
end
end
tmpcfg = [];
tmpcfg.trials = cfg.trials;
tmpcfg.jackknife = 'no';
for i=1:Ndata
if isfield(cfg, 'zparam') && ~strcmp(cfg.zparam,'powspctrm')
% freqdesctiptives will only work on the powspctrm field
% hence a temporary copy of the data is needed
tempdata.dimord = varargin{i}.dimord;
tempdata.freq = varargin{i}.freq;
tempdata.label = varargin{i}.label;
tempdata.powspctrm = varargin{i}.(cfg.zparam);
tempdata.cfg = varargin{i}.cfg;
tempdata = ft_freqdescriptives(tmpcfg, tempdata);
varargin{i}.(cfg.zparam) = tempdata.powspctrm;
clear tempdata
else
varargin{i} = ft_freqdescriptives(tmpcfg, varargin{i});
end
end
dimord = varargin{1}.dimord;
dimtok = tokenize(dimord, '_');
end
% Read or create the layout that will be used for plotting
cla
lay = ft_prepare_layout(cfg, varargin{1});
cfg.layout = lay;
ft_plot_lay(lay, 'box', false,'label','no','point','no');
% Apply baseline correction
if ~strcmp(cfg.baseline, 'no')
for i=1:Ndata
if strcmp(dtype, 'timelock') && strcmp(cfg.xparam, 'time')
varargin{i} = ft_timelockbaseline(cfg, varargin{i});
elseif strcmp(dtype, 'freq') && strcmp(cfg.xparam, 'time')
varargin{i} = ft_freqbaseline(cfg, varargin{i});
elseif strcmp(dtype, 'freq') && strcmp(cfg.xparam, 'freq')
error('Baseline correction is not supported for spectra without a time dimension');
else
warning('Baseline correction not applied, please set cfg.xparam');
end
end
end
% Handle the bivariate case
% Check for bivariate metric with 'chan_chan' in the dimord
selchan = strmatch('chan', dimtok);
isfull = length(selchan)>1;
% Check for bivariate metric with a labelcmb
haslabelcmb = isfield(varargin{1}, 'labelcmb');
if (isfull || haslabelcmb) && isfield(varargin{1}, cfg.zparam)
% A reference channel is required:
if ~isfield(cfg, 'refchannel')
error('no reference channel is specified');
end
% check for refchannel being part of selection
if ~strcmp(cfg.refchannel,'gui')
if (isfull && ~any(ismember(varargin{1}.label, cfg.refchannel))) || ...
(haslabelcmb && ~any(ismember(varargin{1}.labelcmb(:), cfg.refchannel)))
error('cfg.refchannel is a not present in the (selected) channels)')
end
end
% Interactively select the reference channel
if strcmp(cfg.refchannel, 'gui')
% Open a single figure with the channel layout, the user can click on a reference channel
h = clf;
ft_plot_lay(lay, 'box', false);
title('Select the reference channel by dragging a selection window, more than 1 channel can be selected...');
% add the channel information to the figure
info = guidata(gcf);
info.x = lay.pos(:,1);
info.y = lay.pos(:,2);
info.label = lay.label;
guidata(h, info);
%set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'callback', {@select_topoplotER, cfg, data}});
set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_multiplotER, cfg, varargin{1}}, 'event', 'WindowButtonUpFcn'});
set(gcf, 'WindowButtonDownFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_multiplotER, cfg, varargin{1}}, 'event', 'WindowButtonDownFcn'});
set(gcf, 'WindowButtonMotionFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_multiplotER, cfg, varargin{1}}, 'event', 'WindowButtonMotionFcn'});
return
end
for i=1:Ndata
if ~isfull,
% Convert 2-dimensional channel matrix to a single dimension:
if isempty(cfg.matrixside)
sel1 = strmatch(cfg.refchannel, varargin{i}.labelcmb(:,2), 'exact');
sel2 = strmatch(cfg.refchannel, varargin{i}.labelcmb(:,1), 'exact');
elseif strcmp(cfg.matrixside, 'outflow')
sel1 = [];
sel2 = strmatch(cfg.refchannel, varargin{i}.labelcmb(:,1), 'exact');
elseif strcmp(cfg.matrixside, 'inflow')
sel1 = strmatch(cfg.refchannel, varargin{i}.labelcmb(:,2), 'exact');
sel2 = [];
end
fprintf('selected %d channels for %s\n', length(sel1)+length(sel2), cfg.zparam);
varargin{i}.(cfg.zparam) = varargin{i}.(cfg.zparam)([sel1;sel2],:,:);
varargin{i}.label = [varargin{i}.labelcmb(sel1,1);varargin{i}.labelcmb(sel2,2)];
varargin{i}.labelcmb = varargin{i}.labelcmb([sel1;sel2],:);
varargin{i} = rmfield(varargin{i}, 'labelcmb');
else
% General case
sel = match_str(varargin{i}.label, cfg.refchannel);
siz = [size(varargin{i}.(cfg.zparam)) 1];
if strcmp(cfg.matrixside, 'inflow') || isempty(cfg.matrixside)
%the interpretation of 'inflow' and 'outflow' depend on
%the definition in the bivariate representation of the data
%in FieldTrip the row index 'causes' the column index channel
%data.(cfg.zparam) = reshape(mean(data.(cfg.zparam)(:,sel,:),2),[siz(1) 1 siz(3:end)]);
sel1 = 1:siz(1);
sel2 = sel;
meandir = 2;
elseif strcmp(cfg.matrixside, 'outflow')
%data.(cfg.zparam) = reshape(mean(data.(cfg.zparam)(sel,:,:),1),[siz(1) 1 siz(3:end)]);
sel1 = sel;
sel2 = 1:siz(1);
meandir = 1;
elseif strcmp(cfg.matrixside, 'ff-fd')
error('cfg.matrixside = ''ff-fd'' is not supported anymore, you have to manually subtract the two before the call to ft_topoplotER');
elseif strcmp(cfg.matrixside, 'fd-ff')
error('cfg.matrixside = ''fd-ff'' is not supported anymore, you have to manually subtract the two before the call to ft_topoplotER');
end %if matrixside
end %if ~isfull
end %for i
end %handle the bivariate data
% Get physical min/max range of x
if strcmp(cfg.xlim,'maxmin')
% Find maxmin throughout all varargins:
xmin = [];
xmax = [];
for i=1:length(varargin)
xmin = min([xmin varargin{i}.(cfg.xparam)]);
xmax = max([xmax varargin{i}.(cfg.xparam)]);
end
else
xmin = cfg.xlim(1);
xmax = cfg.xlim(2);
end
% Get the index of the nearest bin
for i=1:Ndata
xidmin(i,1) = nearest(varargin{i}.(cfg.xparam), xmin);
xidmax(i,1) = nearest(varargin{i}.(cfg.xparam), xmax);
end
%FIXME do something with yparam here
%technically should not be defined for multiplotER, but can be defined (and
%use ft_selectdata to average across frequencies
% Get physical y-axis range (ylim / zparam):
if strcmp(cfg.ylim,'maxmin')
% Find maxmin throughout all varargins:
ymin = [];
ymax = [];
for i=1:length(varargin)
% Select the channels in the data that match with the layout:
dat = [];
dat = varargin{i}.(cfg.zparam);
[seldat, sellay] = match_str(varargin{i}.label, lay.label);
if isempty(seldat)
error('labels in data and labels in layout do not match');
end
data = dat(seldat,:);
ymin = min([ymin min(min(min(data)))]);
ymax = max([ymax max(max(max(data)))]);
end
else
ymin = cfg.ylim(1);
ymax = cfg.ylim(2);
end
% convert the layout to Ole's style of variable names
X = lay.pos(:,1);
Y = lay.pos(:,2);
width = lay.width;
height = lay.height;
Lbl = lay.label;
% Create empty channel coordinates and labels arrays:
chanX(1:length(Lbl)) = NaN;
chanY(1:length(Lbl)) = NaN;
chanLabels = cell(1,length(Lbl));
hold on;
colorLabels = [];
if isfield(lay, 'outline') && strcmp(cfg.showoutline, 'yes')
for i=1:length(lay.outline)
if ~isempty(lay.outline{i})
tmpX = lay.outline{i}(:,1);
tmpY = lay.outline{i}(:,2);
h = line(tmpX, tmpY);
set(h, 'color', 'k');
set(h, 'linewidth', 2);
end
end
end
% Plot each data set:
for i=1:Ndata
% Make vector dat with one value for each channel
dat = varargin{i}.(cfg.zparam);
xparam = varargin{i}.(cfg.xparam);
% Take subselection of channels, this only works
% in the interactive mode
if exist('selchannel', 'var')
sellab = match_str(varargin{i}.label, selchannel);
label = varargin{i}.label(sellab);
else
sellab = 1:numel(varargin{i}.label);
label = varargin{i}.label;
end
if ~isempty(cfg.yparam)
if isfull
dat = dat(sel1, sel2, ymin:ymax, xidmin(i):xidmax(i));
dat = nanmean(nanmean(dat, meandir), 3);
siz = size(dat);
%FIXMEdat = reshape(dat, [siz(1:2) siz(4)]);
elseif haslabelcmb
dat = dat(sellab, ymin:ymax, xidmin(i):xidmax(i));
dat = nanmean(dat, 2);
siz = size(dat);
dat = reshape(dat, [siz(1) siz(3)]);
else
dat = dat(sellab, ymin:ymax, xidmin(i):xidmax(i));
dat = nanmean(nanmean(dat, 3), 2);
siz = size(dat);
dat = reshape(dat, [siz(1) siz(3)]);
end
else
if isfull
dat = dat(sel1, sel2, xidmin(i):xidmax(i));
dat = nanmean(dat, meandir);
%FIXME
elseif haslabelcmb
dat = dat(sellab, xidmin(i):xidmax(i));
else
dat = dat(sellab, xidmin(i):xidmax(i));
end
end
xparam = xparam(xidmin(i):xidmax(i));
% Select the channels in the data that match with the layout:
[seldat, sellay] = match_str(label, cfg.layout.label);
if isempty(seldat)
error('labels in data and labels in layout do not match');
end
datamatrix = dat(seldat, :);
% Select x and y coordinates and labels of the channels in the data
layX = cfg.layout.pos(sellay,1);
layY = cfg.layout.pos(sellay,2);
layLabels = cfg.layout.label(sellay);
if ~isempty(cfg.maskparameter)
% one value for each channel, or one value for each channel-time point
maskmatrix = varargin{1}.(cfg.maskparameter)(seldat,:);
maskmatrix = maskmatrix(:,xidmin:xidmax);
else
% create an Nx0 matrix
maskmatrix = zeros(length(seldat), 0);
end
if Ndata > 1
if ischar(GRAPHCOLOR); colorLabels = [colorLabels iname{i+1} '=' GRAPHCOLOR(i+1) '\n'];
elseif isnumeric(GRAPHCOLOR); colorLabels = [colorLabels iname{i+1} '=' num2str(GRAPHCOLOR(i+1,:)) '\n'];
end
end
if ischar(GRAPHCOLOR); color = GRAPHCOLOR(i+1);
elseif isnumeric(GRAPHCOLOR); color = GRAPHCOLOR(i+1,:);
end
for m=1:length(layLabels)
% Plot ER
plotWnd(xparam, datamatrix(m,:),[xmin xmax],[ymin ymax], layX(m), layY(m), width(m), height(m), layLabels(m), cfg, color, cfg.linestyle{i}, maskmatrix(m,:),i); %FIXME shouldn't this be replaced with a call to ft_plot_vector?
if i==1,
% Keep ER plot coordinates (at centre of ER plot), and channel labels (will be stored in the figure's UserData struct):
chanX(m) = X(m) + 0.5 * width(m);
chanY(m) = Y(m) + 0.5 * height(m);
chanLabels{m} = Lbl{m};
end
end %for m
end %for i
% Add the colors of the different datasets to the comment:
cfg.comment = [cfg.comment colorLabels];
% Write comment text:
l = cellstrmatch('COMNT',Lbl);
if ~isempty(l)
ft_plot_text(X(l),Y(l),sprintf(cfg.comment),'Fontsize',cfg.fontsize);
end
% Plot scales:
l = cellstrmatch('SCALE',Lbl);
if ~isempty(l)
plotScales([xmin xmax],[ymin ymax],X(l),Y(l),width(1),height(1),cfg)
end
% Make the figure interactive:
if strcmp(cfg.interactive, 'yes')
% add the channel information to the figure
info = guidata(gcf);
info.x = lay.pos(:,1);
info.y = lay.pos(:,2);
info.label = lay.label;
guidata(gcf, info);
set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_singleplotER, cfg, varargin{:}}, 'event', 'WindowButtonUpFcn'});
set(gcf, 'WindowButtonDownFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_singleplotER, cfg, varargin{:}}, 'event', 'WindowButtonDownFcn'});
set(gcf, 'WindowButtonMotionFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_singleplotER, cfg, varargin{:}}, 'event', 'WindowButtonMotionFcn'});
end
axis tight
axis off
if strcmp(cfg.box, 'yes')
abc = axis;
axis(abc + [-1 +1 -1 +1]*mean(abs(abc))/10)
end
orient landscape
hold off
% Set renderer if specified
if ~isempty(cfg.renderer)
set(gcf, 'renderer', cfg.renderer)
end
% get the output cfg
cfg = ft_checkconfig(cfg, 'trackconfig', 'off', 'checksize', 'yes');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function plotScales(xlim,ylim,xpos,ypos,width,height,cfg)
x1 = xpos;
x2 = xpos+width;
y1 = ypos;
y2 = ypos+width;
ft_plot_box([xpos xpos+width ypos ypos+height],'edgecolor','b')
if xlim(1) <= 0 && xlim(2) >= 0
xs = xpos+width*([0 0]-xlim(1))/(xlim(2)-xlim(1));
ys = ypos+height*(ylim-ylim(1))/(ylim(2)-ylim(1));
ft_plot_vector(xs,ys,'color','b');
end
if ylim(1) <= 0 && ylim(2) >= 0
xs = xpos+width*(xlim-xlim(1))/(xlim(2)-xlim(1));
ys = ypos+height*([0 0]-ylim(1))/(ylim(2)-ylim(1));
ft_plot_vector(xs,ys,'color','b');
end
ft_plot_text( x1,y1,num2str(xlim(1),3),'rotation',90,'HorizontalAlignment','Right','VerticalAlignment','middle','Fontsize',cfg.fontsize);
ft_plot_text( x2,y1,num2str(xlim(2),3),'rotation',90,'HorizontalAlignment','Right','VerticalAlignment','middle','Fontsize',cfg.fontsize);
ft_plot_text( x2,y1,num2str(ylim(1),3),'HorizontalAlignment','Left','VerticalAlignment','bottom','Fontsize',cfg.fontsize);
ft_plot_text( x2,y2,num2str(ylim(2),3),'HorizontalAlignment','Left','VerticalAlignment','bottom','Fontsize',cfg.fontsize);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function plotWnd(x,y,xlim,ylim,xpos,ypos,width,height,label,cfg,color,style,mask,i)
% Clip out of bounds y values:
y(y > ylim(2)) = ylim(2);
y(y < ylim(1)) = ylim(1);
xs = xpos+width*(x-xlim(1))/(xlim(2)-xlim(1));
ys = ypos+height*(y-ylim(1))/(ylim(2)-ylim(1));
% Add boxes when masktyle is box, ft_plot_vector doesnt support boxes higher than ydata yet, so this code is left here
if i<2 && ~isempty(mask) && strcmp(cfg.maskstyle, 'box') % i stops box from being plotted more than once
% determine how many boxes
mask = mask(:)';
mask = mask~=0;
mask = diff([0 mask 0]);
boxbeg = find(mask== 1);
boxend = find(mask==-1)-1;
numbox = length(boxbeg);
for i = 1:numbox
xmaskmin = xpos+width*(x(boxbeg(i))-xlim(1))/(xlim(2)-xlim(1));
xmaskmax = xpos+width*(x(boxend(i))-xlim(1))/(xlim(2)-xlim(1));
%plot([xmaskmin xmaskmax xmaskmax xmaskmin xmaskmin],[ypos ypos ypos+height ypos+height ypos],'r');
hs = patch([xmaskmin xmaskmax xmaskmax xmaskmin xmaskmin],[ypos ypos ypos+height ypos+height ypos], [.6 .6 .6]);
set(hs, 'EdgeColor', 'none');
end
end
if isempty(mask) || (~isempty(mask) && strcmp(cfg.maskstyle,'box'))
ft_plot_vector(xs, ys, 'color', color, 'style', style, 'linewidth', cfg.linewidth);
elseif ~isempty(mask) && ~strcmp(cfg.maskstyle,'box') % ft_plot_vector does not support boxes higher than ydata yet, so a separate option remains below
ft_plot_vector(xs, ys, 'color', color, 'style', style, 'linewidth', cfg.linewidth, 'highlight', mask, 'highlightstyle', cfg.maskstyle);
end
if strcmp(cfg.showlabels,'yes')
ft_plot_text(xpos,ypos+1.0*height,label,'Fontsize',cfg.fontsize);
end
% Draw x axis
if strcmp(cfg.axes,'yes') || strcmp(cfg.axes, 'xy') || strcmp(cfg.axes,'x')
xs = xpos+width*(xlim-xlim(1))/(xlim(2)-xlim(1));
if prod(ylim) < 0 % this is equivalent to including 0
ys = ypos+height*([0 0]-ylim(1))/(ylim(2)-ylim(1));
else
ys = [ypos ypos];
end
ft_plot_vector(xs,ys,'color','k');
end
% Draw y axis
if strcmp(cfg.axes,'yes') || strcmp(cfg.axes, 'xy') || strcmp(cfg.axes,'y')
if prod(xlim) < 0 % this is equivalent to including 0
xs = xpos+width*([0 0]-xlim(1))/(xlim(2)-xlim(1));
else % if not, move the y-axis to the x-axis
xs = [xpos xpos];
end
ys = ypos+height*(ylim-ylim(1))/(ylim(2)-ylim(1));
ft_plot_vector(xs,ys,'color','k');
end
% Draw box around plot:
if strcmp(cfg.box,'yes')
ft_plot_box([xpos xpos+width ypos ypos+height],'edgecolor','k');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function l = cellstrmatch(str,strlist)
l = [];
for k=1:length(strlist)
if strcmp(char(str),char(strlist(k)))
l = [l k];
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION which is called after selecting channels in case of cfg.refchannel='gui'
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function select_multiplotER(label, cfg, varargin)
if iscell(label)
label = label{1};
end
cfg.refchannel = label; %FIXME this only works with label being a string
fprintf('selected cfg.refchannel = ''%s''\n', cfg.refchannel);
p = get(gcf, 'Position');
f = figure;
set(f, 'Position', p);
ft_multiplotER(cfg, varargin{:});
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION which is called after selecting channels in case of cfg.interactive='yes'
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function select_singleplotER(label, cfg, varargin)
if ~isempty(label)
%cfg.xlim = 'maxmin';
cfg.channel = label;
fprintf('selected cfg.channel = {');
for i=1:(length(cfg.channel)-1)
fprintf('''%s'', ', cfg.channel{i});
end
fprintf('''%s''}\n', cfg.channel{end});
p = get(gcf, 'Position');
f = figure;
set(f, 'Position', p);
ft_singleplotER(cfg, varargin{:});
end
|
github
|
philippboehmsturm/antx-master
|
ft_spikesorting.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_spikesorting.m
| 7,854 |
utf_8
|
a39d6cf535b4f2352fc27a704698a019
|
function [spike] = ft_spikesorting(cfg, spike);
% FT_SPIKESORTING performs clustering of spike-waveforms and returns the unit number to which each spike belongs.
%
% Use as
% [spike] = ft_spikesorting(cfg, spike)
%
% The configuration can contain
% cfg.channel cell-array with channel selection (default = 'all'), see FT_CHANNELSELECTION for details
% cfg.method 'kmeans', 'ward'
% cfg.feedback 'no', 'text', 'textbar', 'gui' (default = 'textbar')
% cfg.kmeans substructure with additional low-level options for this method
% cfg.ward substructure with additional low-level options for this method
% cfg.ward.distance 'L1', 'L2', 'correlation', 'cosine'
%
% The input spike structure can be imported using READ_FCDC_SPIKE and should contain
% spike.label = 1 x Nchans cell-array, with channel labels
% spike.waveform = 1 x Nchans cell-array, each element contains a matrix (Nsamples x Nspikes), can be empty
% spike.timestamp = 1 x Nchans cell-array, each element contains a vector (1 x Nspikes)
% spike.unit = 1 x Nchans cell-array, each element contains a vector (1 x Nspikes)
%
% To facilitate data-handling and distributed computing with the peer-to-peer
% module, this function has the following options:
% cfg.inputfile = ...
% cfg.outputfile = ...
% If you specify one of these (or both) the input data will be read from a *.mat
% file on disk and/or the output data will be written to a *.mat file. These mat
% files should contain only a single variable, corresponding with the
% input/output structure.
%
% See also FT_READ_SPIKE, FT_SPIKEDOWNSAMPLE
% Copyright (C) 2006-2007, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_spikesorting.m 3710 2011-06-16 14:04:19Z eelspa $
ft_defaults
% record start time and total processing time
ftFuncTimer = tic();
ftFuncClock = clock();
% set the defaults
if ~isfield(cfg, 'feedback'), cfg.feedback = 'textbar'; end
if ~isfield(cfg, 'method'), cfg.method = 'ward'; end
if ~isfield(cfg, 'channel'), cfg.channel = 'all'; end
if ~isfield(cfg, 'inputfile'), cfg.inputfile = []; end
if ~isfield(cfg, 'outputfile'), cfg.outputfile = []; end
if isequal(cfg.method, 'ward')
if ~isfield(cfg, 'ward'), cfg.ward = []; end
if ~isfield(cfg.ward, 'distance'), cfg.ward.distance = 'L2'; end
if ~isfield(cfg.ward, 'optie'), cfg.ward.optie = 'ward'; end
if ~isfield(cfg.ward, 'aantal'), cfg.ward.aantal = 10; end
if ~isfield(cfg.ward, 'absoluut'), cfg.ward.absoluut = 1; end
end
if isequal(cfg.method, 'kmeans')
if ~isfield(cfg, 'kmeans'), cfg.kmeans = []; end
if ~isfield(cfg.kmeans, 'aantal'), cfg.kmeans.aantal = 10; end
end
% load optional given inputfile as data
hasdata = (nargin>1);
if ~isempty(cfg.inputfile)
% the input data should be read from file
if hasdata
error('cfg.inputfile should not be used in conjunction with giving input data to this function');
else
data = loadvar(cfg.inputfile, 'data');
end
end
% select the channels
cfg.channel = ft_channelselection(cfg.channel, spike.label);
sel = match_str(spike.label, cfg.channel);
spike.label = spike.label(sel);
spike.waveform = spike.waveform(sel);
spike.timestamp = spike.timestamp(sel);
spike.unit = {}; % this will be assigned by the clustering
nchan = length(spike.label);
for chanlop=1:nchan
label = spike.label{chanlop};
waveform = spike.waveform{chanlop};
timestamp = spike.timestamp{chanlop};
nspike = size(waveform,2);
unit = zeros(1,nspike);
fprintf('sorting %d spikes in channel %s\n', nspike, label);
switch cfg.method
case 'ward'
dist = ward_distance(cfg, waveform);
[grootte,ordening] = cluster_ward(dist,cfg.ward.optie,cfg.ward.absoluut,cfg.ward.aantal);
for i=1:cfg.ward.aantal
begsel = sum([1 grootte(1:(i-1))]);
endsel = sum([0 grootte(1:(i ))]);
unit(ordening(begsel:endsel)) = i;
end
case 'kmeans'
unit = kmeans(waveform', cfg.kmeans.aantal)';
% 'sqEuclidean' - Squared Euclidean distance
% 'cityblock' - Sum of absolute differences, a.k.a. L1
% 'cosine' - One minus the cosine of the included angle
% between points (treated as vectors)
% 'correlation' - One minus the sample correlation between
% points (treated as sequences of values)
otherwise
error('unsupported clustering method');
end
% remember the sorted units
spike.unit{chanlop} = unit;
end
% add version information to the configuration
cfg.version.name = mfilename('fullpath');
cfg.version.id = '$Id: ft_spikesorting.m 3710 2011-06-16 14:04:19Z eelspa $';
% add information about the Matlab version used to the configuration
cfg.callinfo.matlab = version();
% add information about the function call to the configuration
cfg.callinfo.proctime = toc(ftFuncTimer);
cfg.callinfo.calltime = ftFuncClock;
cfg.callinfo.user = getusername();
% remember the configuration details of the input data
try, cfg.previous = spike.cfg; end
% remember the configuration
spike.cfg = cfg;
% the output data should be saved to a MATLAB file
if ~isempty(cfg.outputfile)
savevar(cfg.outputfile, 'data', spike); % use the variable name "data" in the output file
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION that computes the distance between all spike waveforms
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [dist] = ward_distance(cfg, waveform);
nspike = size(waveform,2);
dist = zeros(nspike, nspike);
ft_progress('init', cfg.feedback, 'computing distance');
switch lower(cfg.ward.distance)
case 'l1'
for i=1:nspike
ft_progress((i-1)/nspike, 'computing distance for spike %d/%d', i, nspike);
for j=2:nspike
dist(i,j) = sum(abs(waveform(:,j)-waveform(:,i)));
dist(j,i) = dist(i,j);
end
end
case 'l2'
for i=1:nspike
ft_progress((i-1)/nspike, 'computing distance for spike %d/%d', i, nspike);
for j=2:nspike
dist(i,j) = sqrt(sum((waveform(:,j)-waveform(:,i)).^2));
dist(j,i) = dist(i,j);
end
end
case 'correlation'
for i=1:nspike
ft_progress((i-1)/nspike, 'computing distance for spike %d/%d', i, nspike);
for j=2:nspike
dist(i,j) = corrcoef(waveform(:,j),waveform(:,i));
dist(j,i) = dist(i,j);
end
end
case 'cosine'
for i=1:nspike
ft_progress((i-1)/nspike, 'computing distance for spike %d/%d', i, nspike);
for j=2:nspike
x = waveform(:,j);
y = waveform(:,i);
x = x./norm(x);
y = y./norm(y);
dist(i,j) = dot(x, y);
dist(j,i) = dist(i,j);
end
end
otherwise
error('unsupported distance metric');
end
ft_progress('close');
|
github
|
philippboehmsturm/antx-master
|
ft_spike_plot_isi.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_spike_plot_isi.m
| 3,481 |
utf_8
|
7fae512a14b0530b7173a35ff65c5dbf
|
function [H] = ft_spike_plot_isih(cfg,isih)
% FT_SPIKE_PLOT_ISI makes an inter-spike-interval bar plot
%
% Inputs:
% ISIH is the output from FT_SPIKE_ISIHIST
%
% Configurations (cfg):
%
% cfg.spikechannel = string or index or logical array to to select 1 spike channel.
% (default = 1).
% cfg.ylim = [min max] or 'auto' (default)
% If 'auto', we plot from 0 to 110% of maximum plotted value);
% cfg.plotfit = 'yes' (default) or 'no'. This requires that when calling
% FT_SPIKESTATION_ISI, cfg.gammafit = 'yes'.
%
% Outputs:
% H.fit = handle for line fit. Use SET and GET to access.
% H.isih = handle for bar isi histogram. Use SET and GET to access.
%
% Martin Vinck (C) 2010.
defaults.plotfit = {'no' 'yes'};
defaults.spikechannel = {1};
defaults.ylim = {'auto'};
cfg = ft_spike_sub_defaultcfg(cfg,defaults);
% get the spikechannels
cfg.channel = ft_channelselection(cfg.spikechannel, isih.label);
spikesel = match_str(isih.label, cfg.channel);
nUnits = length(spikesel); % number of spike channels
if nUnits~=1, error('MATLAB:ft_spike_plot_isi:cfg:spikechannel:wrongInput',...
'One spikechannel should be selected by means of cfg.spikechannel');
end
% plot the average isih
isiHdl = bar(isih.time,isih.avg(spikesel,:),'k');
set(isiHdl,'BarWidth', 1)
if strcmp(cfg.plotfit,'yes')
if ~isfield(isih,'gammaShape') || ~isfield(isih,'gammaScale')
error('MATLAB:ft_spike_plot_isi:fitConflict',...
'ISIH.gammaShape and .gammaScale should be present when cfg.plotfit = yes');
end
% generate the probabilities according to the gamma model
pGamma = gampdf(isih.time, isih.gammaShape(spikesel), isih.gammaScale(spikesel));
pGamma = pGamma./sum(pGamma);
% scale the fit in the same way (total area is equal)
sumIsih = sum(isih.avg(spikesel,:),2);
pGamma = pGamma*sumIsih;
% plot the fit
hold on
fitHdl = plot(isih.time, pGamma,'r');
else
pGamma = 0;
end
try
if strcmp(isih.cfg.outputunit, 'proportion')
ylabel('probability')
elseif strcmp(isih.cfg.outputunit, 'spikecount')
ylabel('spikecount')
end
end
xlabel('bin edges (sec)')
% set the x axis
set(gca,'XLim', [min(isih.time) max(isih.time)])
% set the y axis
if strcmp(cfg.ylim, 'auto')
y = [isih.avg(spikesel,:) pGamma];
cfg.ylim = [0 max(y(:))*1.1+eps];
elseif ~isrealvec(cfg.ylim)||length(cfg.ylim)~=2 || cfg.ylim(2)<cfg.ylim(1)
error('MATLAB:ft_spike_plot_isi:cfg:ylim',...
'cfg.ylim should be "auto" or ascending order 1-by-2 vector in seconds');
end
set(gca,'YLim', cfg.ylim)
set(gca,'TickDir','out')
% store the handles
if strcmp(cfg.plotfit,'yes'), H.fit = fitHdl; end
H.isih = isiHdl;
% as usual, make sure that panning and zooming does not distort the y limits
set(zoom,'ActionPostCallback',{@mypostcallback,cfg.ylim,[min(isih.time) max(isih.time)]});
set(pan,'ActionPostCallback',{@mypostcallback,cfg.ylim,[min(isih.time) max(isih.time)]});
function [] = mypostcallback(fig,evd,limY,limX)
% get the x limits and reset them
ax = evd.Axes;
xlim = get(ax(1), 'XLim');
ylim = get(ax(1), 'YLim');
if limX(1)>xlim(1), xlim(1) = limX(1); end
if limX(2)<xlim(2), xlim(2) = limX(2); end
if limY(1)>ylim(1), ylim(1) = limY(1); end
if limY(2)<ylim(2), ylim(2) = limY(2); end
set(ax(1), 'XLim',xlim)
set(ax(1), 'YLim',ylim);
|
github
|
philippboehmsturm/antx-master
|
ft_spike_plot_jpsth.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_spike_plot_jpsth.m
| 12,629 |
utf_8
|
d6fc9d84b5e6bbd6b41575640eb64396
|
function [H] = plot_jpsth(cfg,jpsth)
% plot_jpsth makes a return plot from JPSTH structure (output from
% plot_jpsth).
%
% Inputs:
% JPSTH must be the output structure from SPIKE_JPSTH and contain the field
% JPSTH.avg. If cfg.psth = 'yes', the field JPSTH.psth must be
% present as well.
%
% Use must be as follows:
% [HDL]=plot_jpsth(CFG,JPSTH)
%
% Here we should definitely think of making a matrix
% With the same electrode somehow as the diagonal
%
% General configurations (cfg):
%
% cfg.channelcmb = string or index of single channel combination to trigger on.
% See SPIKESTATION_FT_SUB_CHANNELCOMBINATION for details.
% cfg.psth = 'yes' (default) or 'no'. If 'yes', the psth histogram is down
% the x and left from the y axis.
% cfg.axlim = [begin end] in seconds or 'max' (default), 'prestim' or
% 'poststim';
% cfg.colorbar = 'yes' (default) or 'no'
% cfg.colormap = N-by-3 colormap (see COLORMAP). or 'auto' (default,hot(256))
% cfg.interpolate = 'yes' or 'no', determines whether we interpolate the density
% plot
% Configurations related to smoothing
%
% cfg.smooth = 'yes' or 'no' (default)
% If 'yes', we overlay a smooth density plot calculated by
% non-parametric symmetric kernel smoothing with cfg.kernel.
% cfg.kernel = 'gausswin' or 'boxcar', or N-by-N matrix containing window
% values with which we convolve the scatterplot that is binned
% with resolution cfg.dt. N should be uneven, so it can be centered
% at each point of the lattice.
% 'gausswin' is N-by-N multivariate gaussian, where the diagonal of the
% covariance matrix is set by cfg.gaussvar.
% 'boxcar' is N-by-N rectangular window.
% If cfg.kernel is numeric, it should be of size N-by-N.
% cfg.gaussvar = variance (default = 1/16 of window length in sec).
% cfg.winlen = window length in seconds (default = 5*binwidth). The total
% length of our window is 2*round*(cfg.winlen/binwidth)
% where binwidth is the binwidth of the jpsth (jpsth.time(2) -
% jpsth.time(1)).
%
% See also SPIKE_JOINTPSTH, SPIKE_PSTH, SPIKE_XCORR
%
if nargin~=2, error('MATLAB:spikestation:plot_jpsth:narginWrong',...
'Two input arguments are required')
end
% general configuration options
defaults.channelcmb = {{1,2}};
defaults.psth = {'yes' 'no'};
defaults.latency = {'maxperiod'};
defaults.colorbar = {'yes' 'no'};
defaults.colormap = {jet(256)};
defaults.interpolate = {'no' 'yes'};
% further kernel smoothing configurations
defaults.smooth = {'no' 'yes'};
defaults.kernel = {'mvgauss'};
try
defaults.winlen = {5*(jpsth.time(2)-jpsth.time(1))};
catch
defaults.winlen = {0.01}; %sec
end
try
defaults.gaussvar = {(cfg.winlen/4).^2};
catch
defaults.gaussvar = {(defaults.winlen{1}/4).^2};
end
cfg = ft_spike_sub_defaultcfg(cfg,defaults);
% channel combination selection
cmbindx = ft_spikestation_sub_channelcombination(cfg.channelcmb, jpsth.label);
nCmbs = size(cmbindx,1);
if nCmbs~=1, error('MATLAB:spikestation:plot_jpsth:cfg:channelcmb:tooManySelected', ...
'Currently only supported for a single channel combination')
end
% select the time
minTime = jpsth.time(1);
maxTime = jpsth.time(end);
if strcmp(cfg.latency,'maxperiod')
cfg.latency = [minTime maxTime];
elseif strcmp(cfg.latency,'poststim')
cfg.latency = [0 maxTime];
elseif strcmp(cfg.latency,'prestim')
cfg.latency = [minTime 0];
elseif ~isrealvec(cfg.latency)||length(cfg.latency)~=2
error('MATLAB:spikestation:plot_jpsth:cfg:latency',...
'cfg.latency should be "max" or 1-by-2 numerical vector');
end
if cfg.latency(1)>=cfg.latency(2),
error('MATLAB:spikestation:plot_jpsth:cfg:latency:wrongOrder',...
'cfg.latency(2) should be greater than cfg.latency(1)')
end
% check whether the time window fits with the data
if (cfg.latency(1) < minTime), cfg.latency(1) = minTime;
warning('MATLAB:spikestation:plot_jpsth:correctLatencyBeg',...
'Correcting begin latency of averaging window');
end
if (cfg.latency(2) > maxTime), cfg.latency(2) = maxTime;
warning('MATLAB:spikestation:plot_jpsth:correctLatencyEnd',...
'Correcting end latency of averaging window');
end
% get the samples of our window, and the binwidth of the JPSTH
timeSel = jpsth.time>=cfg.latency(1) & jpsth.time <= cfg.latency(2);
sampleTime = jpsth.time(2) - jpsth.time(1); % get the binwidth
% for convenience create a separate variable
dens = squeeze(jpsth.avg(:,:,cmbindx(1,1),cmbindx(1,2))); % density
% smooth the jpsth with a kernel if requested
if strcmp(cfg.smooth,'yes')
% construct the kernel
winTime = [fliplr(0:-sampleTime:-cfg.winlen) sampleTime:sampleTime:cfg.winlen];
winLen = length(winTime);
if strcmp(cfg.kernel, 'mvgauss') % multivariate gaussian
A = winTime'*ones(1,winLen);
B = A';
T = [A(:) B(:)]; % makes rows with each time combination on it
covmat = diag([cfg.gaussvar cfg.gaussvar]); % covariance matrix
win = mvnpdf(T,0,covmat); % multivariate gaussian function
elseif strcmp(cfg.kernel, 'boxcar')
win = ones(winLen);
elseif ~isrealmat(cfg.kernel)
error('MATLAB:spikestation:plot_jpsth:cfg:kernel:unknownOption',...
'cfg.kernel should be "gausswin", "boxcar" or numerical N-by-N matrix')
else
win = cfg.kernel;
szWin = size(cfg.kernel);
if szWin(1)~=szWin(2)||~mod(szWin(1),2),
error('MATLAB:spikestation:plot_jpsth:cfg:kernel:wrongSize', ...
'cfg.kernel should be 2-dimensional, N-by-N matrix with N uneven')
end
end
% turn into discrete probabilities again (sum(p)=1);
win = win./sum(win(:));
win = reshape(win,[],winLen);
% do 2-D convolution and rescale
dens = conv2(dens,win,'same');
outputOnes = conv2(ones(size(dens)),win,'same'); % NOTE $$$ SHOULD BE IN RIGHT ROW/COLUMN!
rescale = 1./outputOnes;
dens = dens.*rescale;
end
bins = jpsth.time;
ax(1) = newplot; % create a new axis object
origPos = get(ax(1), 'Position');
pos = origPos;
if strcmp(cfg.interpolate,'yes')
binAxis = linspace(min(bins), max(bins), 1000); % CHANGE THIS
densInterp = interp2(bins(:), bins(:), dens, binAxis(:), binAxis(:)', 'spline');
jpsthHdl = imagesc(binAxis, binAxis, densInterp);
else
jpsthHdl = imagesc(bins,bins,dens);
end
axis xy;
colormap(cfg.colormap); % set the colormap
view(ax(1),2); % use the top view
grid(ax(1),'off'); % toggle grid off
% we need to leave some space for the colorbar on the top
if strcmp(cfg.colorbar,'yes'), pos(3) = pos(3)*0.95; end
% plot the histogram if requested
if strcmp(cfg.psth,'yes')
startPos = pos(1:2) + pos(3:4)*0.2 ; % shift the height and the width 20%
sz = pos(3:4)*0.8; % decrease the size of width and height
set(ax(1), 'ActivePositionProperty', 'position', 'Position', [startPos sz])
% scale the isi such that it becomes 1/5 of the return plot
for iChan = 1:2
% get the data and create the strings that should be the labels
psth = jpsth.psth(cmbindx(1,iChan),timeSel);
label = jpsth.label{cmbindx(1,iChan)};
if iChan==2
startPos = pos(1:2) + pos(3:4).*[0.2 0] ; % shift the width 20%
sz = pos(3:4).*[0.8 0.2]; % and decrease the size of width and height
ax(2) = axes('Units', get(ax(1), 'Units'), 'Position', [startPos sz],...
'Parent', get(ax(1), 'Parent'));
psthHdl(iChan) = bar(jpsth.time(timeSel),psth,'k'); % plot the psth under the jpsth
set(ax(2),'YDir', 'reverse')
ylabel(label)
else
startPos = pos(1:2) + pos(3:4).*[0 0.2] ; % shift the height 20%
sz = pos(3:4).*[0.2 0.8]; % and decrease the size of width and height
ax(3) = axes('Units', get(ax(1), 'Units'), 'Position', [startPos sz],...
'Parent', get(ax(1), 'Parent'));
psthHdl(iChan) = barh(jpsth.time(timeSel),psth,'k'); % plot the psth left
set(ax(3),'XDir', 'reverse')
xlabel(label)
end
end
set(ax(2), 'YAxisLocation', 'Right', 'XGrid', 'off'); % change the y axis location
set(ax(3), 'XAxisLocation', 'Top', 'XGrid', 'off'); % change the x axis location
set(psthHdl, 'BarWidth', 1); % make sure bars have no space between
% change the limits to get the same time limits
set(ax(2),'XLim', cfg.latency)
set(ax(3),'YLim', cfg.latency)
set(get(ax(2),'XLabel'),'String', 'time (sec)')
set(get(ax(3),'YLabel'),'String', 'time (sec)')
set(ax(1), 'YTickLabel', {},'XTickLabel', {}); % we remove the labels from JPSTH now
H.psthleft = psthHdl(2);
H.psthbottom = psthHdl(1);
elseif strcmp(cfg.psth,'no')
xlabel('time (sec)')
ylabel('time (sec')
set(ax(1), 'ActivePositionProperty', 'position', 'Position',pos)
end
% create the colorbar if requested
if strcmp(cfg.colorbar,'yes')
caxis([min(dens(:)) max(dens(:))])
colormap(cfg.colormap); % create the colormap as the user wants
H.colorbarHdl = colorbar; % create a colorbar
% create a position vector and reset the position, it should be alligned right of JPSTH
startPos = [(pos(1) + 0.96*origPos(3)) (pos(2) + pos(4)*0.25)];
sizePos = [0.04*origPos(3) 0.75*pos(4)];
set(H.colorbarHdl, 'Position', [startPos sizePos])
% set the text, try all the possible configurations
try
isNormalized = strcmp(jpsth.cfg.normalization,'yes');
catch
isNormalized = 0;
end
try
unit = jpsth.cfg.previous.outputunit;
if strcmp(unit,'rate')
isRate = 1;
elseif strcmp(unit,'spikecount')
isRate = 2;
end
catch
isRate = 3;
end
if isNormalized
colorbarLabel = 'Normalized Joint Activity';
elseif isRate==1
colorbarLabel = 'Joint Firing Rate (spikes^2/sec^2)';
elseif isRate==2
colorbarLabel = 'Joint Spike Count (spikes^2)';
else
colorbarLabel = 'Joint Peristimulus Activity';
end
try
if strcmp(jpsth.cfg.shiftpredictor,'yes')
colorbarLabel = strcat(colorbarLabel,' Shift Predictor');
end
catch,end
set(get(H.colorbarHdl,'YLabel'),'String',colorbarLabel)
end
set(ax,'TickDir','out')
set(ax(1),'XLim', cfg.latency,'YLim', cfg.latency)
% get the psth limits for constraining the zooming and panning
psthLim = {};
if strcmp(cfg.psth,'yes')
psthLim{1} = get(ax(2),'YLim');
psthLim{2} = get(ax(3),'XLim');
end
% collect the handles
H.ax = ax;
H.jpsth = jpsthHdl;
H.cfg = cfg;
% constrain the zooming and zoom psth together with the jpsth, remove ticklabels jpsth
set(zoom,'ActionPostCallback',{@mypostcallback,ax,cfg.latency,psthLim});
set(pan,'ActionPostCallback',{@mypostcallback,ax,cfg.latency,psthLim});
function [] = mypostcallback(fig,evd,ax,lim,psthLim)
currentAxes = evd.Axes;
xlim = get(currentAxes, 'XLim');
ylim = get(currentAxes, 'YLim');
if currentAxes==ax(1)
% reset the x limits to the shared limits
if lim(1)>xlim(1), xlim(1) = lim(1); end
if lim(2)<xlim(2), xlim(2) = lim(2); end
set(ax(1:2), 'XLim',xlim)
% reset the y limits
if lim(1)>ylim(1), ylim(1) = lim(1); end
if lim(2)<ylim(2), ylim(2) = lim(2); end
set(ax([1 3]), 'YLim',ylim)
elseif currentAxes == ax(2)
% reset the x and y limits
if lim(1)>xlim(1), xlim(1) = lim(1); end
if lim(2)<xlim(2), xlim(2) = lim(2); end
if psthLim{1}(1)>ylim(1), ylim(1) = psthLim{1}(1); end
if psthLim{1}(2)<ylim(2), ylim(2) = psthLim{1}(2); end
set(ax(1:2), 'XLim',xlim)
set(ax(3), 'YLim', xlim)
set(ax(2),'YLim', ylim)
elseif currentAxes == ax(3)
% y limits are shared limits here
if lim(1)>ylim(1), ylim(1) = lim(1); end
if lim(2)<ylim(2), ylim(2) = lim(2); end
% psth limit is specific to its x axis
if psthLim{2}(1)>xlim(1), xlim(1) = psthLim{2}(1); end
if psthLim{2}(2)<xlim(2), xlim(2) = psthLim{2}(2); end
set(ax(1:2), 'XLim',ylim)
set(ax(3), 'YLim', ylim)
set(ax(3),'XLim', xlim)
end
set(ax(1), 'YTickLabel', {});
set(ax(1), 'XTickLabel', {});
|
github
|
philippboehmsturm/antx-master
|
besa2fieldtrip.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/besa2fieldtrip.m
| 16,494 |
utf_8
|
a73c6b43c6f501a6bf90b208ebe22bdf
|
function [data] = besa2fieldtrip(input)
% BESA2FIELDTRIP reads and converts various BESA datafiles into a FieldTrip
% data structure, which subsequently can be used for statistical analysis
% or other analysis methods implemented in Fieldtrip.
%
% Use as
% [data] = besa2fieldtrip(filename)
% where the filename should point to a BESA datafile (or data that
% is exported by BESA). The output is a Matlab structure that is
% compatible with FieldTrip.
%
% The format of the output structure depends on the type of datafile:
% *.avr is converted to a structure similar to the output of TIMELOCKANALYSIS
% *.mul is converted to a structure similar to the output of TIMELOCKANALYSIS
% *.swf is converted to a structure similar to the output of TIMELOCKANALYSIS (*)
% *.tfc is converted to a structure similar to the output of FREQANALYSIS (*)
% *.dat is converted to a structure similar to the output of SOURCANALYSIS
% *.dat combined with a *.gen or *.generic is converted to a structure similar to the output of PREPROCESSING
%
% Note (*): If the BESA toolbox by Karsten Hochstatter is found on your
% Matlab path, the readBESAxxx functions will be used (where xxx=tfc/swf),
% alternatively the private functions from FieldTrip will be used.
%
% See also EEGLAB2FIELDTRIP
% Copyright (C) 2005-2010, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: besa2fieldtrip.m 3710 2011-06-16 14:04:19Z eelspa $
ft_defaults
% record start time and total processing time
ftFuncTimer = tic();
ftFuncClock = clock();
if isstruct(input) && numel(input)>1
% use a recursive call to convert multiple inputs
data = cell(size(input));
for i=1:numel(input)
data{i} = besa2fieldtrip(input(i));
end
return
end
if isstruct(input)
fprintf('besa2fieldtrip: converting structure\n');
%---------------------TFC-------------------------------------------------%
if strcmp(input.structtype, 'besa_tfc')
%fprintf('BESA tfc\n');
data.time = input.latencies;
data.freq = input.frequencies;
temp_chans = char(input.channellabels');
Nchan = size(temp_chans,1);
%{
if strcmp(input.type,'COHERENCE_SQUARED')
% it contains coherence between channel pairs
fprintf('reading coherence between %d channel pairs\n', Nchan);
for i=1:Nchan
tmp = tokenize(deblank(temp_chans(i,:)), '-');
data.labelcmb{i,1} = deblank(tmp{1});
data.labelcmb{i,2} = deblank(tmp{2});
data.label{i,1} = deblank(temp_chans(i,:));
end
data.cohspctrm = input.data;
else
%}
% it contains power on channels
fprintf('reading power on %d channels\n', Nchan);
for i=1:Nchan
data.label{i,1} = deblank(temp_chans(i,:));
end
data.powspctrm = input.data;
data.dimord = 'chan_freq_time';
data.condition = input.condition; %not original Fieldtrip fieldname
%end
clear temp;
%--------------------Image------------------------------------------------%
elseif strcmp(input.structtype, 'besa_image')
%fprintf('BESA image\n');
data.avg.pow = input.data;
xTemp = input.xcoordinates;
yTemp = input.ycoordinates;
zTemp = input.zcoordinates;
data.xgrid = xTemp;
data.ygrid = yTemp;
data.zgrid = zTemp;
nx = size(data.xgrid,2);
ny = size(data.ygrid,2);
nz = size(data.zgrid,2);
% Number of points in each dimension
data.dim = [nx ny nz];
% Array with all possible positions (x,y,z)
data.pos = WritePosArray(xTemp,yTemp,zTemp,nx,ny,nz);
data.inside = 1:prod(data.dim);%as in Fieldtrip - not correct
data.outside = [];
%--------------------Source Waveform--------------------------------------%
elseif strcmp(input.structtype, 'besa_sourcewaveforms')
%fprintf('BESA source waveforms\n');
data.label = input.labels'; %not the same as Fieldtrip!
data.dimord = 'chan_time';
data.fsample = input.samplingrate;
data.time = input.latencies / 1000.0;
data.avg = input.waveforms';
data.cfg.filename = input.datafile;
%--------------------Data Export------------------------------------------%
elseif strcmp(input.structtype, 'besa_channels')
%fprintf('BESA data export\n');
if isfield(input,'datatype')
switch input.ft_datatype
case {'Raw_Data','Epoched_Data','Segment'}
data.fsample = input.samplingrate;
data.label = input.channellabels';
for k=1:size(input.data,2)
data.time{1,k} = input.data(k).latencies / 1000.0';
data.trial{1,k} = input.data(k).amplitudes';
end
otherwise
fprintf('ft_datatype other than Raw_Data, Epoched or Segment');
end
else
fprintf('workspace created with earlier MATLAB version');
end
%--------------------else-------------------------------------------------%
else
error('unrecognized format of the input structure');
end
elseif ischar(input)
fprintf('besa2fieldtrip: reading from file\n');
% This function can either use the reading functions included in FieldTrip
% (with contributions from Karsten, Vladimir and Robert), or the official
% released functions by Karsten Hoechstetter from BESA. The functions in the
% official toolbox have precedence.
hasbesa = ft_hastoolbox('besa',1, 1);
type = filetype(input);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if strcmp(type, 'besa_avr') && hasbesa
fprintf('reading ERP/ERF\n');
% this should be similar to the output of TIMELOCKANALYSIS
tmp = readBESAavr(input);
% convert into a TIMELOCKANALYSIS compatible data structure
data = [];
data.label = [];
if isfield(tmp, 'ChannelLabels'),
data.label = fixlabels(tmp.ChannelLabels);
end;
data.avg = tmp.Data;
data.time = tmp.Time / 1000; % convert to seconds
data.fsample = 1000/tmp.DI;
data.dimord = 'chan_time';
elseif strcmp(type, 'besa_avr') && ~hasbesa
fprintf('reading ERP/ERF\n');
% this should be similar to the output of TIMELOCKANALYSIS
tmp = read_besa_avr(input);
% convert into a TIMELOCKANALYSIS compatible data structure
data = [];
data.label = fixlabels(tmp.label);
data.avg = tmp.data;
data.time = (0:(tmp.npnt-1)) * tmp.di + tmp.tsb;
data.time = data.time / 1000; % convert to seconds
data.fsample = 1000/tmp.di;
data.dimord = 'chan_time';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif strcmp(type, 'besa_mul') && hasbesa
fprintf('reading ERP/ERF\n');
% this should be similar to the output of TIMELOCKANALYSIS
tmp = readBESAmul(input);
% convert into a TIMELOCKANALYSIS compatible data structure
data = [];
data.label = tmp.ChannelLabels(:);
data.avg = tmp.data';
data.time = (0:(tmp.Npts-1)) * tmp.DI + tmp.TSB;
data.time = data.time / 1000; %convert to seconds
data.fsample = 1000/tmp.DI;
data.dimord = 'chan_time';
elseif strcmp(type, 'besa_mul') && ~hasbesa
fprintf('reading ERP/ERF\n');
% this should be similar to the output of TIMELOCKANALYSIS
tmp = read_besa_mul(input);
% convert into a TIMELOCKANALYSIS compatible data structure
data = [];
data.label = tmp.label(:);
data.avg = tmp.data;
data.time = (0:(tmp.TimePoints-1)) * tmp.SamplingInterval_ms_ + tmp.BeginSweep_ms_;
data.time = data.time / 1000; % convert to seconds
data.fsample = 1000/tmp.SamplingInterval_ms_;
data.dimord = 'chan_time';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif strcmp(type, 'besa_sb')
if hasbesa
fprintf('reading preprocessed channel data using BESA toolbox\n');
else
error('this data format requires the BESA toolbox');
end
[p, f, x] = fileparts(input);
input = fullfile(p, [f '.dat']);
[time,buf,ntrial] = readBESAsb(input);
time = time/1000; % convert from ms to sec
nchan = size(buf,1);
ntime = size(buf,3);
% convert into a PREPROCESSING compatible data structure
data = [];
data.trial = {};
data.time = {};
for i=1:ntrial
data.trial{i} = reshape(buf(:,i,:), [nchan, ntime]);
data.time{i} = time;
end
data.label = {};
for i=1:size(buf,1)
data.label{i,1} = sprintf('chan%03d', i);
end
data.fsample = 1/(time(2)-time(1)); % time is already in seconds
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif strcmp(type, 'besa_tfc') && hasbesa
fprintf('reading time-frequency representation using BESA toolbox\n');
% this should be similar to the output of FREQANALYSIS
tfc = readBESAtfc(input);
Nchan = size(tfc.ChannelLabels,1);
% convert into a FREQANALYSIS compatible data structure
data = [];
data.time = tfc.Time(:)';
data.freq = tfc.Frequency(:)';
if isfield(tfc, 'DataType') && strcmp(tfc.DataType, 'COHERENCE_SQUARED')
% it contains coherence between channel pairs
fprintf('reading coherence between %d channel pairs\n', Nchan);
for i=1:Nchan
tmp = tokenize(deblank(tfc.ChannelLabels(i,:)), '-');
data.labelcmb{i,1} = tmp{1};
data.labelcmb{i,2} = tmp{2};
end
data.cohspctrm = permute(tfc.Data, [1 3 2]);
else
% it contains power on channels
fprintf('reading power on %d channels\n', Nchan);
for i=1:Nchan
data.label{i,1} = deblank(tfc.ChannelLabels(i,:));
end
data.powspctrm = permute(tfc.Data, [1 3 2]);
end
data.dimord = 'chan_freq_time';
data.condition = tfc.ConditionName;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif strcmp(type, 'besa_tfc') && ~hasbesa
fprintf('reading time-frequency representation\n');
% this should be similar to the output of FREQANALYSIS
[ChannelLabels, Time, Frequency, Data, Info] = read_besa_tfc(input);
Nchan = size(ChannelLabels,1);
% convert into a FREQANALYSIS compatible data structure
data = [];
data.time = Time * 1e-3; % convert to seconds;
data.freq = Frequency;
if isfield(Info, 'DataType') && strcmp(Info.DataType, 'COHERENCE_SQUARED')
% it contains coherence between channel pairs
fprintf('reading coherence between %d channel pairs\n', Nchan);
for i=1:Nchan
tmp = tokenize(deblank(ChannelLabels(i,:)), '-');
data.labelcmb{i,1} = tmp{1};
data.labelcmb{i,2} = tmp{2};
end
data.cohspctrm = permute(Data, [1 3 2]);
else
% it contains power on channels
fprintf('reading power on %d channels\n', Nchan);
for i=1:Nchan
data.label{i} = deblank(ChannelLabels(i,:));
end
data.powspctrm = permute(Data, [1 3 2]);
end
data.dimord = 'chan_freq_time';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif strcmp(type, 'besa_swf') && hasbesa
fprintf('reading source waveform using BESA toolbox\n');
swf = readBESAswf(input);
% convert into a TIMELOCKANALYSIS compatible data structure
data = [];
data.label = fixlabels(swf.waveName);
data.avg = swf.data;
data.time = swf.Time * 1e-3; % convert to seconds
data.fsample = 1/(data.time(2)-data.time(1));
data.dimord = 'chan_time';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif strcmp(type, 'besa_swf') && ~hasbesa
fprintf('reading source waveform\n');
% hmm, I guess that this should be similar to the output of TIMELOCKANALYSIS
tmp = read_besa_swf(input);
% convert into a TIMELOCKANALYSIS compatible data structure
data = [];
data.label = fixlabels(tmp.label);
data.avg = tmp.data;
data.time = (0:(tmp.npnt-1)) * tmp.di + tmp.tsb;
data.time = data.time / 1000; % convert to seconds
data.fsample = 1000/tmp.di;
data.dimord = 'chan_time';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif strcmp(type, 'besa_src') && hasbesa
src = readBESAimage(input);
data.xgrid = src.Coordinates.X;
data.ygrid = src.Coordinates.Y;
data.zgrid = src.Coordinates.Z;
data.avg.pow = src.Data;
data.dim = size(src.Data);
[X, Y, Z] = ndgrid(data.xgrid, data.ygrid, data.zgrid);
data.pos = [X(:) Y(:) Z(:)];
% cannot determine which voxels are inside the brain volume
data.inside = 1:prod(data.dim);
data.outside = [];
elseif strcmp(type, 'besa_src') && ~hasbesa
src = read_besa_src(input);
data.xgrid = linspace(src.X(1), src.X(2), src.X(3));
data.ygrid = linspace(src.Y(1), src.Y(2), src.Y(3));
data.zgrid = linspace(src.Z(1), src.Z(2), src.Z(3));
data.avg.pow = src.vol;
data.dim = size(src.vol);
[X, Y, Z] = ndgrid(data.xgrid, data.ygrid, data.zgrid);
data.pos = [X(:) Y(:) Z(:)];
% cannot determine which voxels are inside the brain volume
data.inside = 1:prod(data.dim);
data.outside = [];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif strcmp(type, 'besa_pdg')
% hmmm, I have to think about this one...
error('sorry, pdg is not yet supported');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
else
error('unrecognized file format for importing BESA data');
end
end % isstruct || ischar
% construct and add a configuration to the output
cfg = [];
if isstruct(input) && isfield(input,'datafile')
cfg.filename = input.datafile;
elseif isstruct(input) && ~isfield(input,'datafile')
cfg.filename = 'Unknown';
elseif ischar(input)
cfg.filename = input;
end
% add the version details of this function call to the configuration
cfg.version.name = mfilename('fullpath');
cfg.version.id = '$Id: besa2fieldtrip.m 3710 2011-06-16 14:04:19Z eelspa $';
% add information about the Matlab version used to the configuration
cfg.callinfo.matlab = version();
% add information about the function call to the configuration
cfg.callinfo.proctime = toc(ftFuncTimer);
cfg.callinfo.calltime = ftFuncClock;
cfg.callinfo.user = getusername();
data.cfg = cfg;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION that fixes the channel labels, should be a cell-array
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [newlabels] = fixlabels(labels)
if iscell(labels) && length(labels)>1
% seems to be ok
newlabels = labels;
elseif iscell(labels) && length(labels)==1
% could be a cell with a single long string in it
if length(tokenize(labels{1}, ' '))>1
% seems like a long string that accidentaly ended up in a single
cell
newlabels = tokenize(labels{1}, ' ');
else
% seems to be ok
newlabels = labels;
end
elseif ischar(labels) && any(size(labels)==1)
newlabels = tokenize(labels(:)', ' '); % also ensure that it is a row-string
elseif ischar(labels) && ~any(size(labels)==1)
for i=1:size(labels)
newlabels{i} = strtrim(labels(i,:));
end
end
% convert to column
newlabels = newlabels(:);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [PArray] = WritePosArray(x,y,z,mx,my,mz)
A1 = repmat(x,1,my*mz);
A21 = repmat(y,mx,mz);
A2 = reshape(A21,1,mx*my*mz);
A31 = repmat(z,mx*my,1);
A3 = reshape(A31,1,mx*my*mz);
PArray = [A1;A2;A3]';
|
github
|
philippboehmsturm/antx-master
|
ft_spike_plot_isireturn.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_spike_plot_isireturn.m
| 11,709 |
utf_8
|
1cdf323ebae6bacda934fc6851fbdc30
|
function [hdl] = ft_spike_plot_isireturn(cfg,isih)
% FT_SPIKE_PLOT_ISIRETURN makes a return plot from ISIH structure (output from FT_SPIKE_ISIHIST). A
% return plot (or Poincare plots) plots the isi to the next spike versus the isi from the next
% spike to the second next spike, and thus gives insight in the second order isi statistics.
% This func also plots the raw isi-histogram on left and bottom and thereby give a rather
% complete visualization of the spike-train interval statistics.
%
% Inputs:
% ISIH must be the output structure from SPIKE_ISIH and contain the field
% ISIH.isi. If cfg.isihist = 'yes', the field ISIH.isih & ISIH.time must be
% present as well.
%
% Use must be as follows:
% [HDL]=SPIKE_ISIRETURNPLOT(CFG,DATA)
%
% General configurations (cfg):
%
% cfg.spikechannel = string or index of single spike channel to trigger on (default = 1)
% Only one spikechannel can be plotted at a time.
% cfg.density = 'yes' or 'no', if 'yes', we will use color shading on top of
% the individual datapoints to indicate the density.
% cfg.scatter = 'yes' (default) or 'no'. If 'yes', we plot the individual values.
%
% General configurations related to smoothing the scatterplot
%
% cfg.smoothmethod = 'kernel' (default) or 'hist'.
% If 'kernel', we overlay a smooth density plot calculated by
% non-parametric kernel smoothing with cfg.kernel.
% If 'hist', we overlay a 2-D histogram.
% cfg.dt = resolution of the 2-D histogram, or of the kernel plot. Since we
% have to smooth for a finite number of values, cfg.dt determines
% the resolution of our smooth density plot.
% cfg.colormap = N-by-3 colormap (see COLORMAP). Default = hot(256);
% cfg.interpolate = 'yes' or 'no', determines whether we interpolate the density
% plot
%
% Specific configurations related to kernel smoothing of scatterplot.
% cfg.kernel = 'gausswin' or 'boxcar', or N-by-N matrix containing window
% values with which we convolve the scatterplot that is binned
% with resolution cfg.dt. N should be uneven, so it can be centered
% at each point of the lattice.
% 'gausswin' is N-by-N multivariate gaussian, where the diagonal of the
% covariance matrix is set by cfg.gaussvar.
% 'boxcar' is N-by-N rectangular window.
% If cfg.kernel is numeric, it should be of size N-by-N.
% cfg.gaussvar = variance (default = 1/16 of window length in sec).
% cfg.winlen = window length in seconds (default = 5*cfg.dt). The total
% length of our window is 2*round*(cfg.winlen/cfg.dt) +1;
if nargin~=2, error('MATLAB:spikestation:isireturn:nargin','Two input arguments required'), end
% general configuration defaults
defaults.spikechannel = {1};
defaults.scatter = {'yes' 'no'};
defaults.density = {'yes' 'no'};
defaults.colormap = flipud(hot(300)); defaults.colormap = {defaults.colormap(1:256,:)};
defaults.interpolate = {'yes' 'no'};
defaults.scattersize = {0.3};
defaults.smoothmethod = {'kernel' 'hist'};
defaults.dt = {0.001};
defaults.kernel = {'mvgauss'};
try
defaults.winlen = {cfg.dt*5};
catch
defaults.winlen = {0.003};
end
try
defaults.gaussvar = {(diff(cfg.winlen)/4).^2};
catch
defaults.gaussvar = {(defaults.winlen{1}/4).^2};
end
cfg = ft_spike_sub_defaultcfg(cfg,defaults);
% check if all the required fields are there
if ~all(isfield(isih,{'isi' 'label' 'time'}))
error('MATLAB:spikestation:plot_isireturn:cfg:spikechannel:missingFields',...
'input ISIH should contain the fields isi, label and time')
end
% get the spikechannels: maybe replace this by one function with checking etc. in it
cfg.channel = ft_channelselection(cfg.spikechannel, isih.label);
spikesel = match_str(isih.label, cfg.channel);
nUnits = length(cfg.spikechannel); % number of spike channels
if nUnits~=1, error('MATLAB:spikestation:plot_isireturn:cfg:spikechannel:notOneChan',...
'Only one unit can be selected at a time');
end
isi = isih.isi{spikesel};
% create the axis
ax(1) = newplot;
[origPos,pos] = deal(get(ax(1), 'Position'));
if strcmp(cfg.density,'yes'), pos(3) = pos(3)*0.95; end % because of the color bar which takes place
bins = min(isih.time):cfg.dt:max(isih.time);
nbins = length(bins);
% two-dimensional kernel smoothing to get a density behind our scatterplot
if strcmp(cfg.density,'yes')
isivld1 = (~isnan(isi(1:end-1))&~isnan(isi(2:end)));
isivld2 = (isi(1:end-1)<=max(isih.time)-cfg.dt&isi(2:end)<=max(isih.time)-cfg.dt);
isivld = isivld1&isivld2;
hold on
% make a 2-D histogram, we need this for both the kernel and the hist
[N,indx1] = histc(isi(find(isivld)),bins);
[N,indx2] = histc(isi(find(isivld)+1),bins);
% remove the outer counts
rmv = indx1==length(bins)|indx2==length(bins);
indx1(rmv) = [];
indx2(rmv) = [];
dens = full(sparse(indx2,indx1,ones(1,length(indx1)),nbins,nbins));
if strcmp(cfg.smoothmethod,'kernel')
if cfg.winlen<cfg.dt, error('MATLAB:spikestation:plot_isireturn:cfg:dt:winlen',...
'please configure cfg.winlen such that cfg.winlen>=cfg.dt')
end
winTime = [fliplr(0:-cfg.dt:-cfg.winlen) cfg.dt:cfg.dt:cfg.winlen];
winLen = length(winTime);
if strcmp(cfg.kernel, 'mvgauss') % multivariate gaussian
A = winTime'*ones(1,winLen);
B = A';
T = [A(:) B(:)]; % makes rows with each time combination on it
covmat = diag([cfg.gaussvar cfg.gaussvar]); % covariance matrix
win = mvnpdf(T,0,covmat); % multivariate gaussian function
elseif strcmp(cfg.kernel, 'boxcar')
win = ones(winLen);
elseif ~isrealmat(cfg.kernel)
error('MATLAB:spikestation:plot_isireturn:cfg:kernel:wrongInput',...
'cfg.kernel should be "gausswin", "boxcar" or numerical N-by-N matrix')
else
win = cfg.kernel;
szWin = size(cfg.kernel);
if szWin(1)~=szWin(2)||~mod(szWin(1),2),
error('MATLAB:spikestation:spike_isireturnplot:cfg:kernel:wrongSize', ...
'cfg.kernel should be N-by-N matrix with N an uneven number')
end
end
% turn into discrete probabilities again (sum(p)=1);
win = win./sum(win);
win = reshape(win,[],length(winTime)); % reshape to matrix corresponding to grid again
% do 2-D convolution and rescale
dens = conv2(dens,win,'same');
outputOnes = conv2(ones(size(dens)),win,'same');
rescale = 1./outputOnes;
dens = dens.*rescale;
end
% create the surface
hdl.density = imagesc(bins,bins,dens);
if strcmp(cfg.interpolate,'yes')
binAxis = linspace(min(bins)-0.5*(bins(2)-bins(1)), max(bins)+0.5*(bins(2)-bins(1)), 1000);
densInterp = interp2(bins(:), bins(:), dens, binAxis(:), binAxis(:)', 'spline');
hdl.density = imagesc(binAxis, binAxis, densInterp);
end
if isrealmat(cfg.colormap) && size(cfg.colormap,2)==3
colormap(cfg.colormap);
else
error('MATLAB:spikestation:plot_isireturn:cfg:colormap', ...
'cfg.colormap should be N-by-3 numerical matrix')
end
view(ax(1),2); % use the top view
grid(ax(1),'off')
end
hold on
% create scatter return plot and get the handle
if strcmp(cfg.scatter, 'yes')
hdl.scatter = plot(isi(1:end-1), isi(2:end),'ko');
set(hdl.scatter,'MarkerFaceColor', 'k','MarkerSize', cfg.scattersize)
end
%keyboard
% plot the histogram (user can cut away in adobe of canvas himself if needed)
posisih = [pos(1:2) + pos(3:4)*0.2 pos(3:4)*0.8]; % shift the height and the width 20%
set(ax(1), 'ActivePositionProperty', 'position', 'Position', posisih)
startPos = pos(1:2) + pos(3:4).*[0.2 0] ; % shift the width 20%
sz = pos(3:4).*[0.8 0.2]; % and decrease the size of width and height
ax(2) = axes('Units', get(ax(1), 'Units'), 'Position', [startPos sz],...
'Parent', get(ax(1), 'Parent'));
isihist = isih.avg(spikesel,:); %divide by proportion and 5 to get 20% of size
hdl.isi(1) = bar(isih.time(:),isihist,'k');
set(ax(2),'YDir', 'reverse')
startPos = pos(1:2) + pos(3:4).*[0 0.2] ; % shift the height 20%
sz = pos(3:4).*[0.2 0.8]; % and decrease the size of width and height
ax(3) = axes('Units', get(ax(1), 'Units'), 'Position', [startPos sz],...
'Parent', get(ax(1), 'Parent'));
hdl.isi(2) = barh(isih.time(:),isihist,'k');
set(hdl.isi,'BarWidth',1)
set(ax(2:3), 'Box', 'off')
set(ax(3),'XDir', 'reverse')
set(ax(1), 'YTickLabel', {},'XTickLabel',{}, 'XTick',[],'YTick', []);
% take care of all the x and y limits at once
set(ax,'Box', 'off','TickDir','out')
set(ax(1),'XLim', [0 max(isih.time)],'YLim',[0 max(isih.time)]);
limIsi = [0 max(isih.avg(:))*1.05];
set(ax(2),'XLim', [0 max(isih.time)],'YLim',limIsi);
set(ax(3),'YLim', [0 max(isih.time)],'XLim',limIsi);
set(ax(2),'YAxisLocation', 'Right')
set(ax(3),'XAxisLocation', 'Top')
set(get(ax(2),'Xlabel'),'String','isi(n) (sec)')
set(get(ax(3),'Ylabel'),'String','isi(n+1) (sec)')
% create the colorbar (who doesn't want one)
caxis([min(dens(:)) max(dens(:))]);
colormap(cfg.colormap); % create the colormap as the user wants
colorbarHdl = colorbar; % create a colorbar
% create a position vector and reset the position, it should be alligned right of isih
startPos = [(pos(1) + 0.96*origPos(3)) (pos(2) + pos(4)*0.25)];
sizePos = [0.04*origPos(3) 0.75*pos(4)];
set(colorbarHdl, 'Position', [startPos sizePos])
set(get(colorbarHdl,'YLabel'),'String','Number of spikes per bin'); % set the text
hdl.colorbar = colorbarHdl;
hdl.ax = ax;
hdl.cfg = cfg;
% constrain the zooming and zoom psth together with the isih, remove ticklabels isih
set(zoom,'ActionPostCallback',{@mypostcallback,ax,[0 max(isih.time)],limIsi});
set(pan,'ActionPostCallback',{@mypostcallback,ax,[0 max(isih.time)],limIsi});
function [] = mypostcallback(fig,evd,ax,lim,limIsi)
currentAxes = evd.Axes;
indx = find(currentAxes==ax);
if currentAxes==ax(1)
% get the x limits and reset them
xlim = get(ax(1), 'XLim');
ylim = get(ax(1), 'YLim');
[axlim] = [min(xlim(1),ylim(1)) max(xlim(2),ylim(2))]; % make the zoom symmetric
if lim(1)>axlim(1), axlim(1) = lim(1); end
if lim(2)<axlim(2), axlim(2) = lim(2); end
set(ax(1:2), 'XLim',axlim)
set(ax([1 3]), 'YLim',axlim);
elseif currentAxes == ax(2)
xlim = get(ax(2), 'XLim');
if lim(1)>xlim(1), xlim(1) = lim(1); end
if lim(2)<xlim(2), xlim(2) = lim(2); end
set(ax(1:2), 'XLim',xlim)
set(ax(3), 'YLim', xlim)
ylim = get(ax(2), 'YLim');
if limIsi(1)>ylim(1), ylim(1) = limIsi(1); end
if limIsi(2)<ylim(2), ylim(2) = limIsi(2); end
set(ax(2), 'YLim', ylim)
set(ax(3), 'XLim', ylim)
elseif currentAxes == ax(3)
ylim = get(ax(3), 'YLim');
if lim(1)>ylim(1), ylim(1) = lim(1); end
if lim(2)<ylim(2), ylim(2) = lim(2); end
set(ax([1 3]), 'YLim',ylim);
set(ax(2), 'XLim', ylim)
xlim = get(ax(3), 'XLim');
if limIsi(1)>xlim(1), xlim(1) = limIsi(1); end
if limIsi(2)<xlim(2), xlim(2) = limIsi(2); end
set(ax(3), 'XLim', xlim)
set(ax(2), 'YLim', xlim)
end
|
github
|
philippboehmsturm/antx-master
|
ft_movieplotER.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_movieplotER.m
| 12,072 |
utf_8
|
f8d2c7570d15e8b4bdfd15e988591d98
|
function ft_movieplotER(cfg, timelock)
% FT_MOVIEPLOTER makes a movie of the topographic distribution of the
% time-locked average.
%
% Use as
% ft_movieplotER(cfg, timelock)
% where the input data is from FT_TIMELOCKANALYSIS and the configuration
% can contain
% cfg.xparam = string, parameter over which the movie unrolls (default = 'time')
% cfg.zparam = string, parameter that is color coded (default = 'avg')
% cfg.xlim = 'maxmin' or [xmin xmax] (default = 'maxmin')
% cfg.zlim = 'maxmin', 'maxabs' or [zmin zmax] (default = 'maxmin')
% cfg.samperframe = number, samples per fram (default = 1)
% cfg.framespersec = number, frames per second (default = 5)
% cfg.framesfile = 'no', no file saved, or 'sting', filename of saved frames.mat (default = 'no');
% cfg.layout = specification of the layout, see below
%
% The layout defines how the channels are arranged. You can specify the
% layout in a variety of ways:
% - you can provide a pre-computed layout structure (see prepare_layout)
% - you can give the name of an ascii layout file with extension *.lay
% - you can give the name of an electrode file
% - you can give an electrode definition, i.e. "elec" structure
% - you can give a gradiometer definition, i.e. "grad" structure
% If you do not specify any of these and the data structure contains an
% electrode or gradiometer structure, that will be used for creating a
% layout. If you want to have more fine-grained control over the layout
% of the subplots, you should create your own layout file.
%
% To facilitate data-handling and distributed computing with the peer-to-peer
% module, this function has the following option:
% cfg.inputfile = ...
% If you specify this option the input data will be read from a *.mat
% file on disk. This mat files should contain only a single variable named 'data',
% corresponding to the input structure.
% Copyright (C) 2009, Ingrid Nieuwenhuis
% Copyright (C) 2011, Jan-Mathijs Schoffelen, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_movieplotER.m 3710 2011-06-16 14:04:19Z eelspa $
ft_defaults
% record start time and total processing time
ftFuncTimer = tic();
ftFuncClock = clock();;
% check if the input cfg is valid for this function
cfg = ft_checkconfig(cfg, 'renamedval', {'zlim', 'absmax', 'maxabs'});
cfg = ft_checkconfig(cfg, 'trackconfig', 'on');
% set defaults
xlim = ft_getopt(cfg, 'xlim', 'maxmin');
zlim = ft_getopt(cfg, 'zlim', 'maxmin');
xparam = ft_getopt(cfg, 'xparam', 'time');
zparam = ft_getopt(cfg, 'zparam', 'avg');
samperframe = ft_getopt(cfg, 'samperframe', 1);
framespersec = ft_getopt(cfg, 'framespersec', 5);
framesfile = ft_getopt(cfg, 'framesfile', []);
inputfile = ft_getopt(cfg, 'inputfile', []);
mask = ft_getopt(cfg, 'mask', []);
interactive = ft_getopt(cfg, 'interactive', 'no');
dointeractive = istrue(interactive);
% load optional given inputfile as data
hasdata = (nargin>1);
hasinputfile = ~isempty(inputfile);
if hasinputfile && hasdata
error('cfg.inputfile should not be used in conjunction with giving input data to this function');
elseif hasinputfile
timelock = loadvar(inputfile, 'data');
elseif hasdata
% nothing to be done
end
% Checkdata
timelock = ft_checkdata(timelock, 'datatype', 'timelock');
% Read or create the layout that will be used for plotting:
layout = ft_prepare_layout(cfg);
% update the configuration
cfg.xparam = xparam;
cfg.zparam = zparam;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% the actual computation is done in the middle part
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
xparam = timelock.(xparam);
zparam = timelock.(zparam);
if length(xparam)~=size(zparam,2)
error('inconsistent size of "%s" compared to "%s"', cfg.zparam, cfg.xparam);
end
if ischar(xlim) && strcmp(xlim, 'maxmin')
xlim = [];
xlim(1) = min(xparam);
xlim(2) = max(xparam);
end
xbeg = nearest(xparam, xlim(1));
xend = nearest(xparam, xlim(2));
% update the configuration
cfg.xlim = xparam([xbeg xend]);
% select the channels in the data that match with the layout:
[seldat, sellay] = match_str(timelock.label, layout.label);
if isempty(seldat)
error('labels in timelock and labels in layout do not match');
end
% make a subselection of the data
xparam = xparam(xbeg:xend);
zparam = zparam(seldat, xbeg:xend);
clear xbeg xend
% get the x and y coordinates and labels of the channels in the data
chanX = layout.pos(sellay,1);
chanY = layout.pos(sellay,2);
% get the z-range
if ischar(zlim) && strcmp(zlim, 'maxmin')
zlim = [];
zlim(1) = min(zparam(:));
zlim(2) = max(zparam(:));
% update the configuration
cfg.zlim = zlim;
elseif ischar(zlim) && strcmp(cfg.zlim,'maxabs')
zlim = [];
zlim(1) = -max(abs(datavector(:)));
zlim(2) = max(abs(datavector(:)));
cfg.zlim = zlim;
end
h = gcf;
pos = get(gcf, 'position');
set(h, 'toolbar', 'figure');
if dointeractive,
s = uicontrol('style', 'slider');
set(s, 'position', [20 20 pos(3)-40 20]);
p = uicontrol('style', 'pushbutton');
set(p, 'position', [20 50 50 20]);
set(p, 'string', 'play')
button_slower = uicontrol('style', 'pushbutton');
set(button_slower, 'position', [75 50 20 20]);
set(button_slower, 'string', '-')
set(button_slower, 'Callback', @cb_slower);
button_faster = uicontrol('style', 'pushbutton');
set(button_faster, 'position', [100 50 20 20]);
set(button_faster, 'string', '+')
set(button_faster, 'Callback', @cb_faster);
ht = uicontrol('style', 'text');
set(ht, 'position', [20 80 100 20]);
set(ht, 'string', 'time = ');
set(ht, 'horizontalalignment', 'left');
%text(0,0, sprintf('%s = \n', cfg.xparam));
%t = timer;
%set(t, 'timerfcn', {@cb_timer, h}, 'period', 0.1, 'executionmode', 'fixedSpacing');
% collect the data and the options to be used in the figure
opt.lay = layout;
opt.chanX = chanX;
opt.chanY = chanY;
opt.tim = xparam;
opt.dat = zparam;
opt.zlim = zlim;
opt.speed = 1;
opt.cfg = cfg;
opt.s = s;
opt.p = p;
opt.t = t;
if ~isempty(mask) && ischar(mask)
opt.mask = double(getsubfield(source, mask));
end
[dum, hs] = ft_plot_topo(chanX, chanY, zeros(numel(chanX),1), 'mask', layout.mask, 'outline', layout.outline, 'interpmethod', 'cubic');
caxis(cfg.zlim);
axis off;
% add sum stuff at a higher level for quicker access in the callback
% routine
opt.xdata = get(hs, 'xdata');
opt.ydata = get(hs, 'ydata');
opt.nanmask = get(hs, 'cdata');
% add the handle to the mesh
opt.hs = hs;
% add the text-handle to the guidata
opt.ht = ht;
guidata(h, opt);
% from now it is safe to hand over the control to the callback function
set(s, 'Callback', @cb_slider);
% from now it is safe to hand over the control to the callback function
set(p, 'Callback', @cb_playbutton);
else
% old implementation: use variables samperframe and framepersec
% and optionally save movie in a file
[dum, hs] = ft_plot_topo(chanX, chanY, zeros(numel(chanX),1), 'mask', layout.mask, 'outline', layout.outline, 'interpmethod', 'cubic');
caxis(cfg.zlim);
axis off;
xdata = get(hs, 'xdata');
ydata = get(hs, 'ydata');
nanmask = get(hs, 'cdata');
for iFrame = 1:floor(size(zparam, 2)/samperframe)
indx = ((iFrame-1)*samperframe+1):iFrame*samperframe;
datavector = mean(zparam(:, indx), 2);
datamatrix = griddata(chanX, chanY, datavector, xdata, ydata, 'cubic');
set(hs, 'cdata', datamatrix + nanmask);
F(iFrame) = getframe;
end
if ~isempty(framesfile)
save(framesfile, 'F');
end
movie(F, 1, framespersec);
% hmov = figure;
% axis off
% data_movie.F = F;
% data_movie.cfg = cfg;
%
% uicontrol('parent', hmov, 'units', 'normalized', 'style', 'pushbutton', 'string', 'replay', 'userdata', 1, 'position', [0.86, 0.1, 0.12, 0.05], 'backgroundcolor', [1 1 1], 'callback', @replay_cb)
% uicontrol('parent', hmov, 'units', 'normalized', 'style', 'pushbutton', 'string', 'frames/s', 'userdata', 1, 'position', [0.86, 0.18, 0.12, 0.05], 'backgroundcolor', [1 1 1], 'callback', @framespersec_cb)
%
% movie(F,1,cfg.framespersec)
% guidata(hmov, data_movie);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% deal with the output
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% get the output cfg
cfg = ft_checkconfig(cfg, 'trackconfig', 'off', 'checksize', 'yes');
% add the version details of this function call to the configuration
cfg.version.name = mfilename('fullpath'); % this is helpful for debugging
cfg.version.id = '$Id: ft_movieplotER.m 3710 2011-06-16 14:04:19Z eelspa $'; % this will be auto-updated by the revision control system
% add information about the Matlab version used to the configuration
cfg.callinfo.matlab = version();
% add information about the function call to the configuration
cfg.callinfo.proctime = toc(ftFuncTimer);
cfg.callinfo.calltime = ftFuncClock;
cfg.callinfo.user = getusername(); % this is helpful for debugging
if isfield(timelock, 'cfg')
% remember the configuration details of the input data
cfg.previous = timelock.cfg;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_slider(h, eventdata)
opt = guidata(h);
val = get(opt.s, 'value');
val = round(val*(size(opt.dat,2)-1))+1;
val = min(val, size(opt.dat,2));
val = max(val, 1);
% update timer info
set(opt.ht, 'string', sprintf('%s = %1.3f\n', opt.cfg.xparam, opt.tim(val)));
% update data, interpolate and render
datamatrix = griddata(opt.chanX, opt.chanY, opt.dat(:,val), opt.xdata, opt.ydata, 'cubic');
set(opt.hs, 'cdata', datamatrix + opt.nanmask);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_playbutton(h, eventdata)
if ~ishandle(h)
return
end
opt = guidata(h);
switch get(h, 'string')
case 'play'
set(h, 'string', 'stop');
start(opt.t);
case 'stop'
set(h, 'string', 'play');
stop(opt.t);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_timer(obj, info, h)
if ~ishandle(h)
return
end
opt = guidata(h);
delta = opt.speed/size(opt.dat,2);
val = get(opt.s, 'value');
val = val + delta;
if val>1
val = val-1;
end
set(opt.s, 'value', val);
cb_slider(h);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_faster(h, eventdata)
if ~ishandle(h)
return
end
opt = guidata(h);
opt.speed = opt.speed*sqrt(2);
guidata(h, opt);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cb_slower(h, eventdata)
if ~ishandle(h)
return
end
opt = guidata(h);
opt.speed = opt.speed/sqrt(2);
opt.speed = max(opt.speed, 1); % should not be smaller than 1
guidata(h, opt);
|
github
|
philippboehmsturm/antx-master
|
ft_topoplotCC.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/ft_topoplotCC.m
| 9,403 |
utf_8
|
cc237e56a89500a093d28a09a0104331
|
function cfg = ft_topoplotCC(cfg, freq)
% FT_TOPOPLOTCC plots the connections between significantly coherent
% sensor pairs
%
% Use as
% ft_topoplotCC(cfg, freq)
%
% The configuration should contain:
% cfg.feedback = string (default = 'textbar')
% cfg.layout = specification of the layout, see FT_PREPARE_LAYOUT
% cfg.foi = the frequency of interest which is to be plotted (default is the first frequency bin)
% cfg.widthparam = string, parameter to be used to control the line width
% cfg.alphaparam = string, parameter to be used to control the opacity
% cfg.colorparam = string, parameter to be used to control the line color
%
% The widthparam should be indicated in pixels, e.g. usefull numbers are 1
% and larger.
%
% The alphaparam should be indicated as opacity between 0 (fully transparent)
% and 1 (fully opaque).
%
% The default is to plot the connections as lines, but you can also use
% bidirectional arrows:
% cfg.arrowhead = none, stop, start, both (default = 'none')
% cfg.arrowsize = size of the arrow head (default = automatic)
% cfg.arrowoffset = amount that the arrow is shifted to the side (default = automatic)
% cfg.arrowlength = amount by which the length is reduced (default = 0.8)
%
% To facilitate data-handling and distributed computing with the peer-to-peer
% module, this function has the following option:
% cfg.inputfile = ...
% If you specify this option the input data will be read from a *.mat
% file on disk. This mat files should contain only a single variable named 'data',
% corresponding to the input structure. For this particular function, the input should be
% structured as a cell array.
%
% See also FT_PREPARE_LAYOUT, FT_MULTIPLOTCC
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_topoplotCC.m 3016 2011-03-01 19:09:40Z eelspa $
ft_defaults
% check if the input data is valid for this function
freq = ft_checkdata(freq, 'cmbrepresentation', 'sparse');
% check if the input configuration is valid for this function
cfg = ft_checkconfig(cfg, 'trackconfig', 'on');
cfg = ft_checkconfig(cfg, 'required', {'foi', 'layout'});
% set the defaults
if ~isfield(cfg, 'feedback'), cfg.feedback = 'text'; end
if ~isfield(cfg, 'alphaparam'), cfg.alphaparam = []; end
if ~isfield(cfg, 'widthparam'), cfg.widthparam = []; end
if ~isfield(cfg, 'colorparam'), cfg.colorparam = 'cohspctrm'; end
if ~isfield(cfg, 'newfigure'), cfg.newfigure = 'yes'; end
if ~isfield(cfg, 'arrowhead'), cfg.arrowhead = 'none'; end % none, stop, start, both
if ~isfield(cfg, 'arrowsize'), cfg.arrowsize = nan; end % length of the arrow head, should be in in figure units, i.e. the same units as the layout
if ~isfield(cfg, 'arrowoffset'), cfg.arrowoffset = nan; end % absolute, should be in in figure units, i.e. the same units as the layout
if ~isfield(cfg, 'arrowlength'), cfg.arrowlength = 0.8; end % relative to the complete line
lay = ft_prepare_layout(cfg, freq);
beglabel = freq.labelcmb(:,1);
endlabel = freq.labelcmb(:,2);
ncmb = size(freq.labelcmb,1);
% select the data to be used in the figure
fbin = nearest(freq.freq, cfg.foi);
if isfield(freq, cfg.widthparam)
widthparam = freq.(cfg.widthparam)(:,fbin);
else
widthparam = ones(ncmb,1);
end
if isfield(freq, cfg.alphaparam)
alphaparam = freq.(cfg.alphaparam)(:,fbin);
else
alphaparam = [];
end
if isfield(freq, cfg.colorparam)
colorparam = freq.(cfg.colorparam)(:,:,fbin);
else
colorparam = [];
end
if strcmp(cfg.newfigure, 'yes')
figure
end
hold on
axis equal
if isnan(cfg.arrowsize)
% use the size of the figure to estimate a decent number
siz = axis;
cfg.arrowsize = (siz(2) - siz(1))/50;
warning('using an arrowsize of %f', cfg.arrowsize);
end
if isnan(cfg.arrowoffset)
% use the size of the figure to estimate a decent number
siz = axis;
cfg.arrowoffset = (siz(2) - siz(1))/100;
warning('using an arrowoffset of %f', cfg.arrowoffset);
end
rgb = colormap;
if ~isempty(colorparam)
cmin = min(colorparam(:));
cmax = max(colorparam(:));
colorparam = (colorparam - cmin)./(cmax-cmin);
colorparam = round(colorparam * (size(rgb,1)-1) + 1);
end
if strcmp(cfg.newfigure, 'yes')
% also plot the position of the electrodes
ft_plot_vector(lay.pos(:,1), lay.pos(:,2), 'style','k.');
% also plot the outline, i.e. head shape or sulci
if isfield(lay, 'outline')
fprintf('solid lines indicate the outline, e.g. head shape or sulci\n');
for i=1:length(lay.outline)
if ~isempty(lay.outline{i})
X = lay.outline{i}(:,1);
Y = lay.outline{i}(:,2);
ft_plot_line(X, Y, 'color', 'k', 'linewidth', 1.5, 'linestyle', '-');
end
end
end
% also plot the mask, i.e. global outline for masking the topoplot
if isfield(lay, 'mask')
fprintf('dashed lines indicate the mask for topograpic interpolation\n');
for i=1:length(lay.mask)
if ~isempty(lay.mask{i})
X = lay.mask{i}(:,1);
Y = lay.mask{i}(:,2);
% the polygon representing the mask should be closed
X(end+1) = X(1);
Y(end+1) = Y(1);
ft_plot_line(X, Y, 'color', 'k', 'linewidth', 1.5, 'linestyle', '-');
end
end
end
end % if newfigure
% fix the limits for the axis
axis(axis);
ft_progress('init', cfg.feedback, 'plotting connections...');
for i=1:ncmb
if strcmp(beglabel{i}, endlabel{i})
% skip autocombinations
continue
end
ft_progress(i/ncmb, 'plotting connection %d from %d (%s -> %s)\n', i, ncmb, beglabel{i}, endlabel{i});
if widthparam(i)>0
begindx = strmatch(beglabel{i}, lay.label);
endindx = strmatch(endlabel{i}, lay.label);
xbeg = lay.pos(begindx,1);
ybeg = lay.pos(begindx,2);
xend = lay.pos(endindx,1);
yend = lay.pos(endindx,2);
if strcmp(cfg.arrowhead, 'none')
x = [xbeg xend]';
y = [ybeg yend]';
% h = line(x, y);
h = patch(x, y, 1);
else
arrowbeg = [xbeg ybeg];
arrowend = [xend yend];
center = (arrowbeg+arrowend)/2;
direction = (arrowend - arrowbeg);
direction = direction/norm(direction);
offset = [direction(2) -direction(1)];
arrowbeg = cfg.arrowlength * (arrowbeg-center) + center + cfg.arrowoffset * offset;
arrowend = cfg.arrowlength * (arrowend-center) + center + cfg.arrowoffset * offset;
h = arrow(arrowbeg, arrowend, 'Ends', cfg.arrowhead, 'length', 0.05);
end % if arrow
if ~isempty(widthparam)
set(h, 'LineWidth', widthparam(i));
end
if ~isempty(alphaparam)
set(h, 'EdgeAlpha', alphaparam(i));
set(h, 'FaceAlpha', alphaparam(i)); % for arrowheads
end
if ~isempty(colorparam)
set(h, 'EdgeColor', rgb(colorparam(i),:));
set(h, 'FaceColor', rgb(colorparam(i),:)); % for arrowheads
end
end
end
ft_progress('close');
% improve the fit in the axis
axis tight
% get the output cfg
cfg = ft_checkconfig(cfg, 'trackconfig', 'off', 'checksize', 'yes');
if nargout<1
clear cfg
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION for plotting arrows, see also fieldtrip/private/arrow
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function h = arrow(arrowbeg, arrowend, varargin)
ends = keyval('ends', varargin);
length = keyval('length', varargin); % the length of the arrow head, in figure units
color = [0 0 0]; % in RGB
direction = (arrowend - arrowbeg);
direction = direction/norm(direction);
offset = [direction(2) -direction(1)];
pnt1 = arrowbeg;
pnt2 = arrowend;
h = patch([pnt1(1) pnt2(1)], [pnt1(2) pnt2(2)], color);
switch ends
case 'stop'
pnt1 = arrowend - length*direction + 0.4*length*offset;
pnt2 = arrowend;
pnt3 = arrowend - length*direction - 0.4*length*offset;
h(end+1) = patch([pnt1(1) pnt2(1) pnt3(1)]', [pnt1(2) pnt2(2) pnt3(2)]', color);
case 'start'
pnt1 = arrowbeg + length*direction + 0.4*length*offset;
pnt2 = arrowbeg;
pnt3 = arrowbeg + length*direction - 0.4*length*offset;
h(end+1) = patch([pnt1(1) pnt2(1) pnt3(1)]', [pnt1(2) pnt2(2) pnt3(2)]', color);
case 'both'
pnt1 = arrowend - length*direction + 0.4*length*offset;
pnt2 = arrowend;
pnt3 = arrowend - length*direction - 0.4*length*offset;
h(end+1) = patch([pnt1(1) pnt2(1) pnt3(1)]', [pnt1(2) pnt2(2) pnt3(2)]', color);
pnt1 = arrowbeg + length*direction + 0.4*length*offset;
pnt2 = arrowbeg;
pnt3 = arrowbeg + length*direction - 0.4*length*offset;
h(end+1) = patch([pnt1(1) pnt2(1) pnt3(1)]', [pnt1(2) pnt2(2) pnt3(2)]', color);
case 'none'
% don't draw arrow heads
end
|
github
|
philippboehmsturm/antx-master
|
ft_struct2single.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/utilities/ft_struct2single.m
| 2,973 |
utf_8
|
b9e20af224d511cefc32a176b8d020d0
|
function [x] = ft_struct2single(x, maxdepth);
% FT_STRUCT2SINGLE converts all double precision numeric data in a structure
% into single precision, which takes up half the amount of memory compared
% to double precision. It will also convert plain matrices and cell-arrays.
%
% Use as
% x = ft_struct2single(x);
%
% Starting from Matlab 7.0, you can use single precision data in your
% computations, i.e. you do not have to convert back to double precision.
%
% Matlab version 6.5 and older only support single precision for storing
% data in memory or on disk, but do not allow computations on single
% precision data. After reading a single precision structure from file, you
% can convert it back with FT_STRUCT2DOUBLE.
%
% See also FT_STRUCT2DOUBLE
% Copyright (C) 2005, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_struct2single.m 3772 2011-07-04 15:19:01Z jansch $
if nargin<2
maxdepth = inf;
end
% convert the data, work recursively through the complete structure
x = convert(x, 0, maxdepth);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% this subfunction does the actual work
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [a] = convert(a, depth, maxdepth);
if depth>maxdepth
error('recursive depth exceeded');
end
switch class(a)
case 'struct'
% process all fields of the structure recursively
fna = fieldnames(a);
% process all elements of the array
for j=1:length(a(:))
% warning, this is a recursive call to traverse nested structures
for i=1:length(fna)
fn = fna{i};
ra = getfield(a(j), fn);
ra = convert(ra, depth+1, maxdepth);
a(j) = setfield(a(j), fn, ra);
end
end
case 'cell'
% process all elements of the cell-array recursively
% warning, this is a recursive call to traverse nested structures
for i=1:length(a(:))
a{i} = convert(a{i}, depth+1, maxdepth);
end
case {'double' 'int32' 'uint32' 'int16' 'uint16'}
% convert the values to single precision
if ~issparse(a)
a = single(a);
end
otherwise
warning_once(sprintf('not converting class %s', class(a)));
% do nothing
end
|
github
|
philippboehmsturm/antx-master
|
ft_checkconfig.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/utilities/ft_checkconfig.m
| 20,215 |
utf_8
|
27c3f11d00ec0a63a1a446f4b4c30121
|
function [cfg] = ft_checkconfig(cfg, varargin)
% FT_CHECKCONFIG checks the input cfg of the main FieldTrip functions.
%
% 1: It checks whether the cfg contains all the required options, it gives
% a warning when renamed or deprecated options are used, and it makes sure
% no forbidden options are used. If necessary and possible, this function
% will adjust the cfg to the input requirements. If the input cfg does NOT
% correspond to the requirements, this function gives an elaborate warning
% message.
%
% 2: It controls the relevant cfg options that are being passed on to other
% functions, by putting them into substructures or converting them into the
% required format.
%
% 3: It controls the output cfg (data.cfg) such that it only contains
% relevant and used fields. The size of fields in the output cfg is also
% controlled: fields exceeding a certain maximum size are emptied.
% This part of the functionality is still under construction!
%
% Use as
% [cfg] = ft_checkconfig(cfg, ...)
%
% The behaviour of checkconfig can be controlled by the following cfg options,
% which can be set as global fieldtrip defaults (see FT_DEFAULTS)
% cfg.checkconfig = 'pedantic', 'loose' or 'silent' (control the feedback behaviour of checkconfig)
% cfg.trackconfig = 'cleanup', 'report' or 'off'
% cfg.checksize = number in bytes, can be inf (set max size allowed for output cfg fields)
%
% Optional input arguments should be specified as key-value pairs and can include
% renamed = {'old', 'new'} % list the old and new option
% renamedval = {'opt', 'old', 'new'} % list option and old and new value
% required = {'opt1', 'opt2', etc.} % list the required options
% deprecated = {'opt1', 'opt2', etc.} % list the deprecated options
% unused = {'opt1', 'opt2', etc.} % list the unused options, these will be removed and a warning is issued
% forbidden = {'opt1', 'opt2', etc.} % list the forbidden options, these result in an error
% createsubcfg = {'subname', etc.} % list the names of the subcfg
% dataset2files = 'yes', 'no' % converts dataset into headerfile and datafile
% checksize = 'yes', 'no' % remove large fields from the cfg
% trackconfig = 'on', 'off' % start/end config tracking
%
% See also FT_CHECKDATA, FT_DEFAULTS
% Copyright (C) 2007-2008, Robert Oostenveld, Saskia Haegens
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_checkconfig.m 3653 2011-06-09 07:20:07Z jansch $
if isempty(cfg)
cfg = struct; % ensure that it is an empty struct, not empty double
end
global ft_default
if isempty(ft_default)
ft_default = struct;
end
fieldsused = fieldnames(ft_default);
for i=1:length(fieldsused)
fn = fieldsused{i};
if ~isfield(cfg, fn),
cfg.(fn) = ft_default.(fn);
end
end
renamed = keyval('renamed', varargin);
renamedval = keyval('renamedval', varargin);
required = keyval('required', varargin);
deprecated = keyval('deprecated', varargin);
unused = keyval('unused', varargin);
forbidden = keyval('forbidden', varargin);
createsubcfg = keyval('createsubcfg', varargin);
ckeckfilenames = keyval('dataset2files', varargin);
checksize = keyval('checksize', varargin); if isempty(checksize), checksize = 'off'; end
trackconfig = keyval('trackconfig', varargin);
if ~isempty(trackconfig) && strcmp(trackconfig, 'on')
% infer from the user configuration whether tracking should be enabled
if isfield(cfg, 'trackconfig') && (strcmp(cfg.trackconfig, 'report') || strcmp(cfg.trackconfig, 'cleanup'))
trackconfig = 'on'; % turn on configtracking if user requests report/cleanup
else
trackconfig = []; % disable configtracking if user doesn't request report/cleanup
end
end
% these should be cell arrays and not strings
if ischar(required), required = {required}; end
if ischar(deprecated), deprecated = {deprecated}; end
if ischar(unused), unused = {unused}; end
if ischar(forbidden), forbidden = {forbidden}; end
if isfield(cfg, 'checkconfig')
silent = strcmp(cfg.checkconfig, 'silent');
loose = strcmp(cfg.checkconfig, 'loose');
pedantic = strcmp(cfg.checkconfig, 'pedantic');
else
silent = false;
loose = true;
pedantic = false;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% rename old to new options, give warning
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isempty(renamed)
fieldsused = fieldnames(cfg);
if any(strcmp(renamed{1}, fieldsused))
cfg = setfield(cfg, renamed{2}, (getfield(cfg, renamed{1})));
cfg = rmfield(cfg, renamed{1});
if silent
% don't mention it
elseif loose
warning('use cfg.%s instead of cfg.%s', renamed{2}, renamed{1});
elseif pedantic
error(sprintf('use cfg.%s instead of cfg.%s', renamed{2}, renamed{1}));
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% rename old to new value, give warning
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isempty(renamedval) && isfield(cfg, renamedval{1})
if strcmpi(getfield(cfg, renamedval{1}), renamedval{2})
cfg = setfield(cfg, renamedval{1}, renamedval{3});
if silent
% don't mention it
elseif loose
warning('use cfg.%s=''%s'' instead of cfg.%s=''%s''', renamedval{1}, renamedval{3}, renamedval{1}, renamedval{2});
elseif pedantic
error(sprintf('use cfg.%s=''%s'' instead of cfg.%s=''%s''', renamedval{1}, renamedval{3}, renamedval{1}, renamedval{2}));
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% check for required fields, give error when missing
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isempty(required)
fieldsused = fieldnames(cfg);
[c, ia, ib] = setxor(required, fieldsused);
if ~isempty(ia)
error(sprintf('The field cfg.%s is required\n', required{ia}));
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% check for deprecated fields, give warning when present
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isempty(deprecated)
fieldsused = fieldnames(cfg);
if any(ismember(deprecated, fieldsused))
if silent
% don't mention it
elseif loose
warning('The option cfg.%s is deprecated, support is no longer guaranteed\n', deprecated{ismember(deprecated, fieldsused)});
elseif pedantic
error(sprintf('The option cfg.%s is deprecated, support is no longer guaranteed\n', deprecated{ismember(deprecated, fieldsused)}));
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% check for unused fields, give warning when present and remove them
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isempty(unused)
fieldsused = fieldnames(cfg);
if any(ismember(unused, fieldsused))
cfg = rmfield(cfg, unused(ismember(unused, fieldsused)));
if silent
% don't mention it
elseif loose
warning('The field cfg.%s is unused, it will be removed from your configuration\n', unused{ismember(unused, fieldsused)});
elseif pedantic
error(sprintf('The field cfg.%s is unused\n', unused{ismember(unused, fieldsused)}));
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% check for forbidden fields, give error when present
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isempty(forbidden)
fieldsused = fieldnames(cfg);
if any(ismember(forbidden, fieldsused))
cfg = rmfield(cfg, forbidden(ismember(forbidden, fieldsused)));
if silent
% don't mention it
elseif loose
warning('The field cfg.%s is forbidden, it will be removed from your configuration\n', forbidden{ismember(forbidden, fieldsused)});
elseif pedantic
error(sprintf('The field cfg.%s is forbidden\n', forbidden{ismember(forbidden, fieldsused)}));
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% createsubcfg
%
% This collects the optional arguments for some of the low-level
% functions and puts them in a separate substructure. This function is to
% ensure backward compatibility of end-user scripts, fieldtrip functions
% and documentation that do not use the nested detailled configuration
% but that use a flat configuration.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isempty(createsubcfg)
for j=1:length(createsubcfg)
subname = createsubcfg{j};
if isfield(cfg, subname)
% get the options that are already specified in the substructure
subcfg = getfield(cfg, subname);
else
% start with an empty substructure
subcfg = [];
end
% add all other relevant options to the substructure
switch subname
case 'preproc'
fieldname = {
'reref'
'refchannel'
'implicitref'
'detrend'
'bpfiltdir'
'bpfilter'
'bpfiltord'
'bpfilttype'
'bpfreq'
'bsfiltdir'
'bsfilter'
'bsfiltord'
'bsfilttype'
'bsfreq'
'demean'
'baselinewindow'
'denoise'
'dftfilter'
'dftfreq'
'hpfiltdir'
'hpfilter'
'hpfiltord'
'hpfilttype'
'hpfreq'
'lpfiltdir'
'lpfilter'
'lpfiltord'
'lpfilttype'
'lpfreq'
'medianfilter'
'medianfiltord'
'hilbert'
'derivative'
'rectify'
'boxcar'
'absdiff'
};
case 'grid'
fieldname = {
'xgrid'
'ygrid'
'zgrid'
'resolution'
'filter'
'leadfield'
'inside'
'outside'
'pos'
'dim'
'tight'
};
case 'dics'
fieldname = {
'feedback'
'fixedori'
'keepfilter'
'keepmom'
'lambda'
'normalize'
'normalizeparam'
'powmethod'
'projectnoise'
'reducerank'
'keepcsd'
'realfilter'
'subspace'
'keepsubspace'
};
case 'lcmv'
fieldname = {
'feedback'
'fixedori'
'keepfilter'
'keepmom'
'lambda'
'normalize'
'normalizeparam'
'powmethod'
'projectnoise'
'projectmom'
'reducerank'
'keepcov'
'subspace'
'keepsubspace'
};
case 'pcc'
fieldname = {
'feedback'
'keepfilter'
'keepmom'
'lambda'
'normalize'
'normalizeparam'
%'powmethod'
'projectnoise'
'reducerank'
'keepcsd'
'realfilter'
};
case {'mne', 'loreta', 'rv'}
fieldname = {
'feedback'
'lambda'
};
case 'music'
fieldname = {
'feedback'
'numcomponent'
};
case 'sam'
fieldname = {
'meansphereorigin'
'spinning'
'feedback'
'lambda'
'normalize'
'normalizeparam'
'reducerank'
};
case 'mvl'
fieldname = {};
case 'npsf'
% non-parametric spectral factorization -> csd2transfer
fieldname = {
'block'
'blockindx'
'channelcmb'
'feedback'
'numiteration'
'tol'
'sfmethod'
'svd'
};
otherwise
error('unexpected name of the subfunction');
fieldname = {};
end % switch subname
for i=1:length(fieldname)
if ~isfield(subcfg, fieldname{i}) && isfield(cfg, fieldname{i})
subcfg = setfield(subcfg, fieldname{i}, getfield(cfg, fieldname{i})); % set it in the subconfiguration
cfg = rmfield(cfg, fieldname{i}); % remove it from the main configuration
end
end
% copy the substructure back into the main configuration structure
cfg = setfield(cfg, subname, subcfg);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% ckeckfilenames, i.e. dataset2files
%
% Converts cfg.dataset into cfg.headerfile and cfg.datafile if neccessary.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isempty(ckeckfilenames) && strcmp(ckeckfilenames, 'yes')
% start with empty fields if they are not present
if ~isfield(cfg, 'dataset')
cfg.dataset = [];
end
if ~isfield(cfg, 'datafile')
cfg.datafile = [];
end
if ~isfield(cfg, 'headerfile')
cfg.headerfile = [];
end
if ~isempty(cfg.dataset)
if strcmp(cfg.dataset, 'gui');
[f, p] = uigetfile('*.*', 'Select a file');
if isequal(f, 0)
error('User pressed cancel');
else
d = fullfile(p, f);
end
cfg.dataset = d;
end
% ensure that the headerfile and datafile are defined, which are sometimes different than the name of the dataset
% this requires correct autodetection of the format
[cfg.dataset, cfg.headerfile, cfg.datafile] = dataset2files(cfg.dataset, []);
% fill dataformat if unspecified
if ~isfield(cfg,'dataformat') || isempty(cfg.dataformat)
cfg.dataformat = ft_filetype(cfg.datafile);
end
% fill dataformat if unspecified
if ~isfield(cfg,'headerformat') || isempty(cfg.headerformat)
cfg.headerformat = ft_filetype(cfg.headerfile);
end
elseif ~isempty(cfg.datafile) && isempty(cfg.headerfile);
% assume that the datafile also contains the header
cfg.headerfile = cfg.datafile;
elseif isempty(cfg.datafile) && ~isempty(cfg.headerfile);
% assume that the headerfile also contains the data
cfg.datafile = cfg.headerfile;
end
% remove empty fields (otherwise a subsequent check on required fields doesn't make any sense)
if isempty(cfg.dataset), cfg=rmfield(cfg, 'dataset'); end
if isempty(cfg.headerfile), cfg=rmfield(cfg, 'headerfile'); end
if isempty(cfg.datafile), cfg=rmfield(cfg, 'datafile'); end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% configtracking
%
% switch configuration tracking on/off
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isempty(trackconfig)
try
if strcmp(trackconfig, 'on') && isa(cfg, 'struct')
% turn ON configuration tracking
cfg = config(cfg);
% remember that configtracking has been turned on
cfg.trkcfgcount = 1;
elseif strcmp(trackconfig, 'on') && isa(cfg, 'config')
% remember how many times configtracking has been turned on
cfg.trkcfgcount = cfg.trkcfgcount+1; % count the 'ONs'
end
if strcmp(trackconfig, 'off') && isa(cfg, 'config')
% turn OFF configuration tracking, optionally give report and/or cleanup
cfg.trkcfgcount=cfg.trkcfgcount-1; % count(down) the 'OFFs'
if cfg.trkcfgcount==0 % only proceed when number of 'ONs' matches number of 'OFFs'
cfg=rmfield(cfg, 'trkcfgcount');
if strcmp(cfg.trackconfig, 'report') || strcmp(cfg.trackconfig, 'cleanup')
% gather information about the tracked results
r = access(cfg, 'reference');
o = access(cfg, 'original');
key = fieldnames(cfg);
key = key(:)';
ignorefields = {'checksize', 'trl', 'trlold', 'event', 'artifact', 'artfctdef', 'previous'}; % these fields should never be removed!
skipsel = match_str(key, ignorefields);
key(skipsel) = [];
used = zeros(size(key));
original = zeros(size(key));
for i=1:length(key)
used(i) = (r.(key{i})>0);
original(i) = (o.(key{i})>0);
end
if ~silent
% give report on screen
fprintf('\nThe following config fields were specified by YOU and were USED\n');
sel = find(used & original);
if numel(sel)
fprintf(' cfg.%s\n', key{sel});
else
fprintf(' <none>\n');
end
fprintf('\nThe following config fields were specified by YOU and were NOT USED\n');
sel = find(~used & original);
if numel(sel)
fprintf(' cfg.%s\n', key{sel});
else
fprintf(' <none>\n');
end
fprintf('\nThe following config fields were set to DEFAULTS and were USED\n');
sel = find(used & ~original);
if numel(sel)
fprintf(' cfg.%s\n', key{sel});
else
fprintf(' <none>\n');
end
fprintf('\nThe following config fields were set to DEFAULTS and were NOT USED\n');
sel = find(~used & ~original);
if numel(sel)
fprintf(' cfg.%s\n', key{sel});
else
fprintf(' <none>\n');
end
end % report
end % report/cleanup
if strcmp(cfg.trackconfig, 'cleanup')
% remove the unused options from the configuration
unusedkey = key(~used);
for i=1:length(unusedkey)
cfg = rmfield(cfg, unusedkey{i});
end
end
% convert the configuration back to a struct
cfg = struct(cfg);
end
end % off
catch
disp(lasterr);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% check the size of fields in the cfg, remove large fields
% the max allowed size should be specified in cfg.checksize (this can be
% set with ft_defaults)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if strcmp(checksize, 'yes') && ~isinf(cfg.checksize)
cfg = checksizefun(cfg, cfg.checksize);
end
function [cfg] = checksizefun(cfg, max_size)
ignorefields = {'checksize', 'trl', 'trlold', 'event', 'artifact', 'artfctdef', 'previous'}; % these fields should never be removed!
fieldsorig = fieldnames(cfg);
for i=1:numel(fieldsorig)
for k=1:numel(cfg)
if ~isstruct(cfg(k).(fieldsorig{i})) && ~any(strcmp(fieldsorig{i}, ignorefields))
% find large fields and remove them from the cfg, skip fields that should be ignored
temp = cfg(k).(fieldsorig{i});
s = whos('temp');
if s.bytes>max_size
cfg(k).(fieldsorig{i}) = 'empty - this was cleared by checkconfig';
end
%%% cfg(k).(fieldsorig{i})=s.bytes; % remember the size of each field for debugging purposes
elseif isstruct(cfg(k).(fieldsorig{i}));
% run recursively on subfields that are structs
cfg(k).(fieldsorig{i}) = checksizefun(cfg(k).(fieldsorig{i}), max_size);
elseif iscell(cfg(k).(fieldsorig{i})) && strcmp(fieldsorig{i}, 'previous')
% run recursively on 'previous' fields that are cells
for j=1:numel(cfg(k).(fieldsorig{i}))
cfg(k).(fieldsorig{i}){j} = checksizefun(cfg(k).(fieldsorig{i}){j}, max_size);
end
end
end
end
|
github
|
philippboehmsturm/antx-master
|
ft_determine_coordsys.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/utilities/ft_determine_coordsys.m
| 9,713 |
utf_8
|
8f08a860d0f42103b7c4b63fba2cbbeb
|
function [data] = ft_determine_coordsys(data, varargin)
% FT_DETERMINECOORDSYS plots a geometrical object, allowing you to perform a visual
% check on the coordinatesystem, the units and on the anatomical labels for the
% coordinate system axes.
%
% Use as
% [dataout] = ft_checkcoordsys(datain, varargin)
% where the input data structure can be
% - an anatomical MRI, which can be segmented
% - an electrode or gradiometer definition
% - a volume conduction model
% or most other FieldTrip structures that represent geometrical information.
%
% The optional key-value pairs are
% interactive = string, 'yes' or 'no' (default = 'yes')
%
% This function wil pop up a figure that allows you to check whether the
% alignment of the object relative to the coordinate system axes is correct
% and what the anatomical labels of the coordinate system axes are. You should
% switch on the 3D rotation option in the figure panel to rotate and see the
% figure from all angles. To change the anatomical labels of the coordinate
% system, you should press the corresponding keyboard button.
%
% See also FT_VOLUMEREALIGN, FT_VOLUMERESLICE
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_determine_coordsys.m 3732 2011-06-29 07:49:26Z jorhor $
dointeractive = ft_getopt(varargin, 'interactive', 'yes');
dtype = ft_datatype(data);
data = ft_convert_units(data);
unit = data.unit;
% the high-level data structures are detected with ft_datatype, but there are
% also some low-level data structures that need to be supproted here
if strcmp(dtype, 'unknown')
if isfield(data, 'fid')
dtype = 'headshape';
elseif ~strcmp(ft_voltype(data), 'unknown')
dtype = 'headmodel';
elseif ~strcmp(ft_senstype(data), 'unknown')
dtype = 'sens';
end
end
% determine the size of the "unit" sphere in the origin and the length of the axes
switch unit
case 'mm'
axmax = 150;
rbol = 5;
case 'cm'
axmax = 15;
rbol = 0.5;
case 'm'
axmax = 0.15;
rbol = 0.005;
otherwise
error('unknown units (%s)', unit);
end
if isfield(data, 'coordsys') && ~isempty(data.coordsys)
if length(data.coordsys)==3 && length(intersect(data.coordsys, 'rlasif'))==3
for i=1:3
switch data.coordsys(i)
case 'l'
label{i} = 'the left';
case 'r'
label{i} = 'the right';
case 'i'
label{i} = 'inferior';
case 's'
label{i} = 'superior';
case 'a'
label{i} = 'anterior';
case 'p'
label{i} = 'posterior';
otherwise
error('incorrect letter in the coordsys');
end % switch
end % for each of the three axes
elseif strcmpi(data.coordsys, 'itab') || strcmpi(data.coordsys, 'neuromag')
label{1} = 'the right';
label{2} = 'anterior';
label{3} = 'superior';
elseif strcmpi(data.coordsys, 'ctf') || strcmpi(data.coordsys, '4d') || strcmpi(data.coordsys, 'bti')
label{1} = 'anterior';
label{2} = 'the left';
label{3} = 'superior';
elseif strcmpi(data.coordsys, 'tal') || strcmpi(data.coordsys, 'mni') || strcmpi(data.coordsys, 'spm')
label{1} = 'the right';
label{2} = 'anterior';
label{3} = 'superior';
else
error('unsupported coordsys');
end
fprintf('The positive x-axis is pointing towards %s\n', label{1});
fprintf('The positive y-axis is pointing towards %s\n', label{2});
fprintf('The positive z-axis is pointing towards %s\n', label{3});
end
% create the labels that are to be plotted along the axes
if isfield(data, 'coordsys')
[labelx, labely, labelz] = xyz2label(data.coordsys);
else
[labelx, labely, labelz] = xyz2label('unknown');
end
% plot the geometrical object
% the plotting style depends on the data content
switch dtype
case 'volume'
if isfield(data, 'anatomy')
funparam = data.anatomy;
elseif isfield(data, 'gray')
funparam = data.gray;
else
error('don''t know which volumetric parameter to plot');
end
ft_plot_ortho(funparam, 'transform', data.transform, 'resolution', 1, 'style', 'intersect');
axis vis3d
view([110 36]);
case 'source'
ft_plot_mesh(data, 'edgecolor','none', 'facecolor', [0.6 0.8 0.6], 'facealpha', 0.6);
camlight;
case 'dip'
ft_plot_mesh(data, 'edgecolor','none', 'facecolor', 'none');
camlight;
case 'headshape'
ft_plot_headshape(data);
camlight;
case 'headmodel'
ft_plot_vol(data);
camlight;
case 'sens'
ft_plot_sens(data);
camlight;
case {'raw', 'timelock', 'freq', 'mvar', 'freqmvar', 'comp'}
% the data may contain a gradiometer or electrode definition
if isfield(data, 'grad')
ft_plot_sens(data.grad);
elseif isfield(data, 'elec')
ft_plot_sens(data.elec);
end
case 'unknown'
end % switch dtype{k}
% get the xyz-axes
xdat = [-axmax 0 0; axmax 0 0];
ydat = [0 -axmax 0; 0 axmax 0];
zdat = [0 0 -axmax; 0 0 axmax];
% get the xyz-axes dotted
xdatdot = (-axmax:(axmax/15):axmax);
xdatdot = xdatdot(1:floor(numel(xdatdot)/2)*2);
xdatdot = reshape(xdatdot, [2 numel(xdatdot)/2]);
n = size(xdatdot,2);
ydatdot = [zeros(2,n) xdatdot zeros(2,n)];
zdatdot = [zeros(2,2*n) xdatdot];
xdatdot = [xdatdot zeros(2,2*n)];
% plot axes
hl = line(xdat, ydat, zdat);
set(hl(1), 'linewidth', 1, 'color', 'r');
set(hl(2), 'linewidth', 1, 'color', 'g');
set(hl(3), 'linewidth', 1, 'color', 'b');
hld = line(xdatdot, ydatdot, zdatdot);
for k = 1:n
set(hld(k ), 'linewidth', 3, 'color', 'r');
set(hld(k+n*1), 'linewidth', 3, 'color', 'g');
set(hld(k+n*2), 'linewidth', 3, 'color', 'b');
end
% create the ball at the origin
[O.pnt, O.tri] = icosahedron42;
O.pnt = O.pnt.*rbol;
ft_plot_mesh(O, 'edgecolor', 'none');
% add the labels to the axis
text(xdat(1,1),ydat(1,1),zdat(1,1),labelx{1},'color','y','fontsize',15,'linewidth',2);
text(xdat(1,2),ydat(1,2),zdat(1,2),labely{1},'color','y','fontsize',15,'linewidth',2);
text(xdat(1,3),ydat(1,3),zdat(1,3),labelz{1},'color','y','fontsize',15,'linewidth',2);
text(xdat(2,1),ydat(2,1),zdat(2,1),labelx{2},'color','y','fontsize',15,'linewidth',2);
text(xdat(2,2),ydat(2,2),zdat(2,2),labely{2},'color','y','fontsize',15,'linewidth',2);
text(xdat(2,3),ydat(2,3),zdat(2,3),labelz{2},'color','y','fontsize',15,'linewidth',2);
if dointeractive,
if ~isfield(data, 'coordsys') || isempty(data.coordsys)
% default is yes
value = smartinput('Do you want to change the anatomical labels for the axes [Y, n]? ', 'y');
else
% default is no
value = smartinput('Do you want to change the anatomical labels for the axes [y, N]? ', 'n');
end
if strcmpi(value, 'n')
return
end
% interactively determine orientation
orientation = ' ';
while ~any(strcmp(orientation(1), {'r', 'l', 'a', 'p', 's', 'i'}))
orientation(1) = smartinput('What is the anatomical label for the positive X-axis [r, l, a, p, s, i]? ', '');
end
while ~any(strcmp(orientation(2), {'r', 'l', 'a', 'p', 's', 'i'}))
orientation(2) = smartinput('What is the anatomical label for the positive Y-axis [r, l, a, p, s, i]? ', '');
end
while ~any(strcmp(orientation(3), {'r', 'l', 'a', 'p', 's', 'i'}))
orientation(3) = smartinput('What is the anatomical label for the positive Z-axis [r, l, a, p, s, i]? ', '');
end
% interactively determine origin
origin = ' ';
while ~any(strcmp(origin, {'a', 'i', 'n'}))
origin = input('Is the origin of the coordinate system at the a(nterior commissure), i(nterauricular), n(ot a landmark)? ', 's');
end
if origin=='a' && strcmp(orientation, 'ras')
coordsys = 'spm';
elseif origin=='i' && strcmp(orientation, 'als')
coordsys = 'ctf';
elseif origin=='i' && strcmp(orientation, 'ras')
coordsys = 'neuromag'; % also used for itab
else
% just use the orientation
coordsys = orientation;
end
data.coordsys = coordsys;
end % if interactive
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION to go from aplrsi to better interpretable format
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [labelx, labely, labelz] = xyz2label(str)
if ~isempty(str) && ~strcmp(str, 'unknown')
% the first part is important for th eorientations
% the second part optionally contains information on the origin
strx = tokenize(str, '_');
switch lower(strx{1})
case {'ras' 'itab' 'neuromag'}
labelx = {'-X (left)' '+X (right)' };
labely = {'-Y (posterior)' '+Y (anterior)'};
labelz = {'-Z (inferior)' '+Z (superior)'};
case {'als' 'ctf' '4d', 'bti'}
labelx = {'-X (posterior)' '+X (anterior)'};
labely = {'-Y (right)' '+Y (left)'};
labelz = {'-Z (inferior)' '+Z (superior)'};
otherwise
error('unknown coordsys');
end
else
labelx = {'-X (unknown)' '+X (unknown)'};
labely = {'-Y (unknown)' '+Y (unknown)'};
labelz = {'-Z (unknown)' '+Z (unknown)'};
end
|
github
|
philippboehmsturm/antx-master
|
ft_hastoolbox.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/utilities/ft_hastoolbox.m
| 15,262 |
utf_8
|
614a00df8ff0166ef4b5ad254779bc35
|
function [status] = ft_hastoolbox(toolbox, autoadd, silent)
% FT_HASTOOLBOX tests whether an external toolbox is installed. Optionally
% it will try to determine the path to the toolbox and install it
% automatically.
%
% Use as
% [status] = ft_hastoolbox(toolbox, autoadd, silent)
%
% autoadd = 0 means that it will not be added
% autoadd = 1 means that give an error if it cannot be added
% autoadd = 2 means that give a warning if it cannot be added
% autoadd = 3 means that it remains silent if it cannot be added
%
% silent = 0 means that it will give some feedback about adding the toolbox
% silent = 1 means that it will not give feedback
% Copyright (C) 2005-2010, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_hastoolbox.m 3872 2011-07-19 14:23:15Z tilsan $
% this function is called many times in FieldTrip and associated toolboxes
% use efficient handling if the same toolbox has been investigated before
persistent previous previouspath
if ~isequal(previouspath, path)
previous = [];
end
if isempty(previous)
previous = struct;
elseif isfield(previous, fixname(toolbox))
status = previous.(fixname(toolbox));
return
end
% this points the user to the website where he/she can download the toolbox
url = {
'AFNI' 'see http://afni.nimh.nih.gov'
'DSS' 'see http://www.cis.hut.fi/projects/dss'
'EEGLAB' 'see http://www.sccn.ucsd.edu/eeglab'
'NWAY' 'see http://www.models.kvl.dk/source/nwaytoolbox'
'SPM99' 'see http://www.fil.ion.ucl.ac.uk/spm'
'SPM2' 'see http://www.fil.ion.ucl.ac.uk/spm'
'SPM5' 'see http://www.fil.ion.ucl.ac.uk/spm'
'SPM8' 'see http://www.fil.ion.ucl.ac.uk/spm'
'MEG-PD' 'see http://www.kolumbus.fi/kuutela/programs/meg-pd'
'MEG-CALC' 'this is a commercial toolbox from Neuromag, see http://www.neuromag.com'
'BIOSIG' 'see http://biosig.sourceforge.net'
'EEG' 'see http://eeg.sourceforge.net'
'EEGSF' 'see http://eeg.sourceforge.net' % alternative name
'MRI' 'see http://eeg.sourceforge.net' % alternative name
'NEUROSHARE' 'see http://www.neuroshare.org'
'BESA' 'see http://www.megis.de, or contact Karsten Hoechstetter'
'EEPROBE' 'see http://www.ant-neuro.com, or contact Maarten van der Velde'
'YOKOGAWA' 'see http://www.yokogawa.co.jp, or contact Nobuhiko Takahashi'
'YOKOGAWA_MEG_READER' 'contact Masayuki dot Mochiduki at jp.yokogawa.com'
'BEOWULF' 'see http://oostenveld.net, or contact Robert Oostenveld'
'MENTAT' 'see http://oostenveld.net, or contact Robert Oostenveld'
'SON2' 'see http://www.kcl.ac.uk/depsta/biomedical/cfnr/lidierth.html, or contact Malcolm Lidierth'
'4D-VERSION' 'contact Christian Wienbruch'
'SIGNAL' 'see http://www.mathworks.com/products/signal'
'OPTIM' 'see http://www.mathworks.com/products/optim'
'IMAGE' 'see http://www.mathworks.com/products/image'
'SPLINES' 'see http://www.mathworks.com/products/splines'
'FASTICA' 'see http://www.cis.hut.fi/projects/ica/fastica'
'BRAINSTORM' 'see http://neuroimage.ucs.edu/brainstorm'
'FILEIO' 'see http://www.ru.nl/neuroimaging/fieldtrip'
'FORWINV' 'see http://www.ru.nl/neuroimaging/fieldtrip'
'PLOTTING' 'see http://www.ru.nl/neuroimaging/fieldtrip'
'DENOISE' 'see http://lumiere.ens.fr/Audition/adc/meg, or contact Alain de Cheveigne'
'BCI2000' 'see http://bci2000.org'
'NLXNETCOM' 'see http://www.neuralynx.com'
'DIPOLI' 'see ftp://ftp.fcdonders.nl/pub/fieldtrip/external'
'MNE' 'see http://www.nmr.mgh.harvard.edu/martinos/userInfo/data/sofMNE.php'
'TCP_UDP_IP' 'see http://www.mathworks.com/matlabcentral/fileexchange/345, or contact Peter Rydes?ter'
'BEMCP' 'contact Christophe Phillips'
'OPENMEEG' 'see http://gforge.inria.fr/projects/openmeeg and http://gforge.inria.fr/frs/?group_id=435'
'PRTOOLS' 'see http://www.prtools.org'
'ITAB' 'contact Stefania Della Penna'
'BSMART' 'see http://www.brain-smart.org'
'PEER' 'see http://fieldtrip.fcdonders.nl/development/peer'
'FREESURFER' 'see http://surfer.nmr.mgh.harvard.edu/fswiki'
'SIMBIO' 'see https://www.mrt.uni-jena.de/simbio/index.php/Main_Page'
'FNS' 'see http://hhvn.nmsu.edu/wiki/index.php/FNS'
'GIFTI' 'see http://www.artefact.tk/software/matlab/gifti'
'XML4MAT' 'see http://www.mathworks.com/matlabcentral/fileexchange/6268-xml4mat-v2-0'
'SQDPROJECT' 'see http://www.isr.umd.edu/Labs/CSSL/simonlab'
'BCT' 'see http://www.brain-connectivity-toolbox.net/'
};
if nargin<2
% default is not to add the path automatically
autoadd = 0;
end
if nargin<3
% default is not to be silent
silent = 0;
end
% determine whether the toolbox is installed
toolbox = upper(toolbox);
switch toolbox
case 'AFNI'
status = (exist('BrikLoad') && exist('BrikInfo'));
case 'DSS'
status = exist('denss', 'file') && exist('dss_create_state', 'file');
case 'EEGLAB'
status = exist('runica', 'file');
case 'NWAY'
status = exist('parafac', 'file');
case 'SPM'
status = exist('spm.m'); % any version of SPM is fine
case 'SPM99'
status = exist('spm.m') && strcmp(spm('ver'),'SPM99');
case 'SPM2'
status = exist('spm.m') && strcmp(spm('ver'),'SPM2');
case 'SPM5'
status = exist('spm.m') && strcmp(spm('ver'),'SPM5');
case 'SPM8'
status = exist('spm.m') && strncmp(spm('ver'),'SPM8', 4);
case 'MEG-PD'
status = (exist('rawdata') && exist('channames'));
case 'MEG-CALC'
status = (exist('megmodel') && exist('megfield') && exist('megtrans'));
case 'BIOSIG'
status = (exist('sopen') && exist('sread'));
case 'EEG'
status = (exist('ctf_read_res4') && exist('ctf_read_meg4'));
case 'EEGSF' % alternative name
status = (exist('ctf_read_res4') && exist('ctf_read_meg4'));
case 'MRI' % other functions in the mri section
status = (exist('avw_hdr_read') && exist('avw_img_read'));
case 'NEUROSHARE'
status = (exist('ns_OpenFile') && exist('ns_SetLibrary') && exist('ns_GetAnalogData'));
case 'BESA'
status = (exist('readBESAtfc') && exist('readBESAswf'));
case 'EEPROBE'
status = (exist('read_eep_avr') && exist('read_eep_cnt'));
case 'YOKOGAWA'
status = (exist('hasyokogawa') && hasyokogawa('16bitBeta6'));
case 'YOKOGAWA16BITBETA3'
status = (exist('hasyokogawa') && hasyokogawa('16bitBeta3'));
case 'YOKOGAWA16BITBETA6'
status = (exist('hasyokogawa') && hasyokogawa('16bitBeta6'));
case 'YOKOGAWA_MEG_READER'
status = (exist('hasyokogawa') && hasyokogawa('1.4'));
case 'BEOWULF'
status = (exist('evalwulf') && exist('evalwulf') && exist('evalwulf'));
case 'MENTAT'
status = (exist('pcompile') && exist('pfor') && exist('peval'));
case 'SON2'
status = (exist('SONFileHeader') && exist('SONChanList') && exist('SONGetChannel'));
case '4D-VERSION'
status = (exist('read4d') && exist('read4dhdr'));
case {'STATS', 'STATISTICS'}
status = license('checkout', 'statistics_toolbox'); % also check the availability of a toolbox license
case {'OPTIM', 'OPTIMIZATION'}
status = license('checkout', 'optimization_toolbox'); % also check the availability of a toolbox license
case {'SPLINES', 'CURVE_FITTING'}
status = license('checkout', 'curve_fitting_toolbox'); % also check the availability of a toolbox license
case 'SIGNAL'
status = license('checkout', 'signal_toolbox'); % also check the availability of a toolbox license
case 'IMAGE'
status = license('checkout', 'image_toolbox'); % also check the availability of a toolbox license
case 'DCT'
status = license('checkout', 'distrib_computing_toolbox'); % also check the availability of a toolbox license
case 'FASTICA'
status = exist('fastica', 'file');
case 'BRAINSTORM'
status = exist('bem_xfer');
case 'FILEIO'
status = (exist('ft_read_header') && exist('ft_read_data') && exist('ft_read_event') && exist('ft_read_sens'));
case 'FORMWARD'
status = (exist('ft_compute_leadfield') && exist('ft_prepare_vol_sens'));
case 'DENOISE'
status = (exist('tsr') && exist('sns'));
case 'CTF'
status = (exist('getCTFBalanceCoefs') && exist('getCTFdata'));
case 'BCI2000'
status = exist('load_bcidat');
case 'NLXNETCOM'
status = (exist('MatlabNetComClient') && exist('NlxConnectToServer') && exist('NlxGetNewCSCData'));
case 'DIPOLI'
status = exist('dipoli.m', 'file');
case 'MNE'
status = (exist('fiff_read_meas_info', 'file') && exist('fiff_setup_read_raw', 'file'));
case 'TCP_UDP_IP'
status = (exist('pnet', 'file') && exist('pnet_getvar', 'file') && exist('pnet_putvar', 'file'));
case 'BEMCP'
status = (exist('bem_Cij_cog', 'file') && exist('bem_Cij_lin', 'file') && exist('bem_Cij_cst', 'file'));
case 'OPENMEEG'
status = exist('openmeeg.m', 'file');
case 'PLOTTING'
status = (exist('ft_plot_topo', 'file') && exist('ft_plot_mesh', 'file') && exist('ft_plot_matrix', 'file'));
case 'PRTOOLS'
status = (exist('prversion', 'file') && exist('dataset', 'file') && exist('svc', 'file'));
case 'ITAB'
status = (exist('lcReadHeader', 'file') && exist('lcReadData', 'file'));
case 'BSMART'
status = exist('bsmart');
case 'PEER'
status = exist('peerslave', 'file') && exist('peermaster', 'file');
case 'CONNECTIVITY'
status = exist('ft_connectivity_corr', 'file') && exist('ft_connectivity_granger', 'file');
case 'FREESURFER'
status = exist('MRIread', 'file') && exist('vox2ras_0to1', 'file');
case 'FNS'
status = exist('elecsfwd', 'file') && exist('img_get_gray', 'file');
case 'SIMBIO'
status = exist('ipm_linux_opt_Venant', 'file');
case 'GIFTI'
status = exist('gifti', 'file');
case 'XML4MAT'
status = exist('xml2struct.m', 'file') && exist('xml2whos.m', 'file');
case 'SQDPROJECT'
status = exist('sqdread.m', 'file') && exist('sqdwrite.m', 'file');
case 'BCT'
status = exist('macaque71.mat', 'file') && exist('motif4funct_wei.m', 'file');
otherwise
if ~silent, warning('cannot determine whether the %s toolbox is present', toolbox); end
status = 0;
end
% it should be a boolean value
status = (status~=0);
% try to determine the path of the requested toolbox
if autoadd>0 && ~status
% for core fieldtrip modules
prefix = fileparts(which('ft_defaults'));
if ~status
status = myaddpath(fullfile(prefix, lower(toolbox)), silent);
end
% for external fieldtrip modules
prefix = fullfile(fileparts(which('ft_defaults')), 'external');
if ~status
status = myaddpath(fullfile(prefix, lower(toolbox)), silent);
licensefile = [lower(toolbox) '_license'];
if status && exist(licensefile, 'file')
% this will execute openmeeg_license and mne_license
% which display the license on screen for three seconds
feval(licensefile);
end
end
% for linux computers in the F.C. Donders Centre
prefix = '/home/common/matlab';
if ~status && (strcmp(computer, 'GLNX86') || strcmp(computer, 'GLNXA64'))
status = myaddpath(fullfile(prefix, lower(toolbox)), silent);
end
% for windows computers in the F.C. Donders Centre
prefix = 'h:\common\matlab';
if ~status && (strcmp(computer, 'PCWIN') || strcmp(computer, 'PCWIN64'))
status = myaddpath(fullfile(prefix, lower(toolbox)), silent);
end
% use the matlab subdirectory in your homedirectory, this works on unix and mac
prefix = [getenv('HOME') '/matlab'];
if ~status
status = myaddpath(fullfile(prefix, lower(toolbox)), silent);
end
if ~status
% the toolbox is not on the path and cannot be added
sel = find(strcmp(url(:,1), toolbox));
if ~isempty(sel)
msg = sprintf('the %s toolbox is not installed, %s', toolbox, url{sel, 2});
else
msg = sprintf('the %s toolbox is not installed', toolbox);
end
if autoadd==1
error(msg);
elseif autoadd==2
warning(msg);
else
% fail silently
end
end
end
% this function is called many times in FieldTrip and associated toolboxes
% use efficient handling if the same toolbox has been investigated before
if status
previous.(fixname(toolbox)) = status;
end
% remember the previous path, allows us to determine on the next call
% whether the path has been modified outise of this function
previouspath = path;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function status = myaddpath(toolbox, silent)
if exist(toolbox, 'dir')
if ~silent,
ws = warning('backtrace', 'off');
warning('adding %s toolbox to your Matlab path', toolbox);
warning(ws); % return to the previous warning level
end
addpath(toolbox);
status = 1;
else
status = 0;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function out = fixname(toolbox)
out = lower(toolbox);
out(out=='-') = '_'; % fix dashes
out(out==' ') = '_'; % fix spaces
out(out=='/') = '_'; % fix forward slashes
out(out=='\') = '_'; % fix backward slashes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function status = hasfunction(funname, toolbox)
try
% call the function without any input arguments, which probably is inapropriate
feval(funname);
% it might be that the function without any input already works fine
status = true;
catch
% either the function returned an error, or the function is not available
% availability is influenced by the function being present and by having a
% license for the function, i.e. in a concurrent licensing setting it might
% be that all toolbox licenses are in use
m = lasterror;
if strcmp(m.identifier, 'MATLAB:license:checkouterror')
if nargin>1
warning('the %s toolbox is available, but you don''t have a license for it', toolbox);
else
warning('the function ''%s'' is available, but you don''t have a license for it', funname);
end
status = false;
elseif strcmp(m.identifier, 'MATLAB:UndefinedFunction')
status = false;
else
% the function seems to be available and it gave an unknown error,
% which is to be expected with inappropriate input arguments
status = true;
end
end
|
github
|
philippboehmsturm/antx-master
|
ft_checkdata.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/utilities/ft_checkdata.m
| 58,801 |
utf_8
|
8d543f06e04e77fc4583d7f265baf5e4
|
function [data] = ft_checkdata(data, varargin)
% FT_CHECKDATA checks the input data of the main FieldTrip functions, e.g. whether
% the type of data strucure corresponds with the required data. If neccessary
% and possible, this function will adjust the data structure to the input
% requirements (e.g. change dimord, average over trials, convert inside from
% index into logical).
%
% If the input data does NOT correspond to the requirements, this function
% is supposed to give a elaborate warning message and if applicable point
% the user to external documentation (link to website).
%
% Use as
% [data] = ft_checkdata(data, ...)
%
% Optional input arguments should be specified as key-value pairs and can include
% feedback = yes, no
% datatype = raw, freq, timelock, comp, spike, source, volume, dip
% dimord = any combination of time, freq, chan, refchan, rpt, subj, chancmb, rpttap, pos
% senstype = ctf151, ctf275, ctf151_planar, ctf275_planar, neuromag122, neuromag306, bti148, bti248, bti248_planar, magnetometer, electrode
% inside = logical, index
% ismeg = yes, no
% hastrials = yes, no
% hasunits = yes, no
% hassampleinfo = yes, no, ifmakessense
% hascumtapcnt = yes, no (only applies to freq data)
% hasdim = yes, no
% hasdof = yes, no
% cmbrepresentation = sparse, full (applies to covariance and cross-spectral density)
%
% For some options you can specify multiple values, e.g.
% [data] = ft_checkdata(data, 'senstype', {'ctf151', 'ctf275'}), e.g. in megrealign
% [data] = ft_checkdata(data, 'datatype', {'timelock', 'freq'}), e.g. in sourceanalysis
% Copyright (C) 2007-2009, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 Publhasoffsetic License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_checkdata.m 3880 2011-07-20 09:39:40Z jansch $
% in case of an error this function could use dbstack for more detailled
% user feedback
%
% this function should replace/encapsulate
% fixdimord
% fixinside
% fixprecision
% fixvolume
% data2raw
% raw2data
% grid2transform
% transform2grid
% fourier2crsspctrm
% freq2cumtapcnt
% sensortype
% time2offset
% offset2time
%
% other potential uses for this function:
% time -> offset in freqanalysis
% average over trials
% csd as matrix
% get the optional input arguments
feedback = keyval('feedback', varargin); if isempty(feedback), feedback = 'no'; end
dtype = keyval('datatype', varargin); % should not conflict with the ft_datatype function
dimord = keyval('dimord', varargin);
stype = keyval('senstype', varargin); % senstype is a function name which should not be masked
ismeg = keyval('ismeg', varargin);
inside = keyval('inside', varargin); % can be logical or index
hastrials = keyval('hastrials', varargin);
hasunits = keyval('hasunits', varargin);
hassampleinfo = keyval('hassampleinfo', varargin); if isempty(hassampleinfo), hassampleinfo = 'no'; end
hasdimord = keyval('hasdimord', varargin); if isempty(hasdimord), hasdimord = 'no'; end
hasdim = keyval('hasdim', varargin);
hascumtapcnt = keyval('hascumtapcnt', varargin);
hasdof = keyval('hasdof', varargin); if isempty(hasdof), hasdof = 'no'; end
haspow = keyval('haspow', varargin); if isempty(haspow), haspow = 'no'; end
cmbrepresentation = keyval('cmbrepresentation', varargin);
channelcmb = keyval('channelcmb', varargin);
sourcedimord = keyval('sourcedimord', varargin);
sourcerepresentation = keyval('sourcerepresentation', varargin);
% check whether people are using deprecated stuff
depHastrialdef = keyval('hastrialdef', varargin);
if (~isempty(depHastrialdef))
warning_once('ft_checkdata option ''hastrialdef'' is deprecated; use ''hassampleinfo'' instead');
hassampleinfo = depHastrialdef;
end
if (~isempty(keyval('hasoffset', varargin)))
warning_once('ft_checkdata option ''hasoffset'' has been removed and will be ignored');
end
% determine the type of input data
% this can be raw, freq, timelock, comp, spike, source, volume, dip
israw = ft_datatype(data, 'raw');
isfreq = ft_datatype(data, 'freq');
istimelock = ft_datatype(data, 'timelock');
iscomp = ft_datatype(data, 'comp');
isspike = ft_datatype(data, 'spike');
isvolume = ft_datatype(data, 'volume');
issource = ft_datatype(data, 'source');
isdip = ft_datatype(data, 'dip');
ismvar = ft_datatype(data, 'mvar');
isfreqmvar = ft_datatype(data, 'freqmvar');
ischan = ft_datatype(data, 'chan');
% FIXME use the istrue function on ismeg and hasxxx options
if ~isequal(feedback, 'no')
if israw
nchan = length(data.label);
ntrial = length(data.trial);
fprintf('the input is raw data with %d channels and %d trials\n', nchan, ntrial);
elseif isfreq
nchan = length(data.label);
nfreq = length(data.freq);
if isfield(data, 'time'), ntime = num2str(length(data.time)); else ntime = 'no'; end
fprintf('the input is freq data with %d channels, %d frequencybins and %s timebins\n', nchan, nfreq, ntime);
elseif istimelock
nchan = length(data.label);
ntime = length(data.time);
fprintf('the input is timelock data with %d channels and %d timebins\n', nchan, ntime);
elseif iscomp
ncomp = length(data.label);
nchan = length(data.topolabel);
fprintf('the input is component data with %d components and %d original channels\n', ncomp, nchan);
elseif isspike
nchan = length(data.label);
fprintf('the input is spike data\n');
elseif isvolume
fprintf('the input is volume data with dimensions [%d %d %d]\n', data.dim(1), data.dim(2), data.dim(3));
elseif issource
nsource = size(data.pos, 1);
fprintf('the input is source data with %d positions\n', nsource);
elseif isdip
fprintf('the input is dipole data\n');
elseif ismvar
fprintf('the input is mvar data\n');
elseif isfreqmvar
fprintf('the input is freqmvar data\n');
end
end % give feedback
if issource && isvolume
% it should be either one or the other: the choice here is to
% represent it as volume description since that is simpler to handle
% the conversion is done by remove the grid positions
data = rmfield(data, 'pos');
issource = false;
end
% the ft_datatype_XXX functions ensures the consistency of the XXX datatype
% and provides a detailled description of the dataformat and its history
if israw
data = ft_datatype_raw(data);
elseif isfreq
data = ft_datatype_freq(data);
elseif istimelock
data = ft_datatype_timelock(data);
elseif iscomp
data = ft_datatype_comp(data);
elseif isspike
data = ft_datatype_spike(data);
elseif isvolume
data = ft_datatype_volume(data);
elseif issource
data = ft_datatype_source(data);
elseif isdip
data = ft_datatype_dip(data);
elseif ismvar || isfreqmvar
data = ft_datatype_mvar(data);
end
if ~isempty(dtype)
if ~isa(dtype, 'cell')
dtype = {dtype};
end
okflag = 0;
for i=1:length(dtype)
% check that the data matches with one or more of the required ft_datatypes
switch dtype{i}
case 'raw'
okflag = okflag + israw;
case 'freq'
okflag = okflag + isfreq;
case 'timelock'
okflag = okflag + istimelock;
case 'comp'
okflag = okflag + iscomp;
case 'spike'
okflag = okflag + isspike;
case 'volume'
okflag = okflag + isvolume;
case 'source'
okflag = okflag + issource;
case 'dip'
okflag = okflag + isdip;
case 'mvar'
okflag = okflag + ismvar;
case 'freqmvar'
okflag = okflag + isfreqmvar;
end % switch dtype
end % for dtype
if ~okflag
% try to convert the data
for iCell = 1:length(dtype)
if isequal(dtype(iCell), {'source'}) && isvolume
data = volume2source(data);
isvolume = 0;
issource = 1;
okflag = 1;
elseif isequal(dtype(iCell), {'volume'}) && issource
data = source2volume(data);
isvolume = 1;
issource = 0;
okflag = 1;
elseif isequal(dtype(iCell), {'raw'}) && issource
data = data2raw(data);
issource = 0;
israw = 1;
okflag = 1;
elseif isequal(dtype(iCell), {'raw'}) && istimelock
data = timelock2raw(data);
istimelock = 0;
israw = 1;
okflag = 1;
elseif isequal(dtype(iCell), {'timelock'}) && israw
data = raw2timelock(data);
israw = 0;
istimelock = 1;
okflag = 1;
elseif isequal(dtype(iCell), {'raw'}) && isfreq
data = freq2raw(data);
isfreq = 0;
israw = 1;
okflag = 1;
elseif isequal(dtype(iCell), {'raw'}) && iscomp
data = comp2raw(data);
iscomp = 0;
israw = 1;
okflag = 1;
elseif isequal(dtype(iCell), {'timelock'}) && iscomp
data = comp2raw(data);
data = raw2timelock(data);
iscomp = 0;
istimelock = 1;
okflag = 1;
elseif isequal(dtype(iCell), {'timelock'}) && ischan
data = chan2timelock(data);
ischan = 0;
istimelock = 1;
okflag = 1;
elseif isequal(dtype(iCell), {'freq'}) && ischan
data = chan2freq(data);
ischan = 0;
isfreq = 1;
okflag = 1;
end
end % for iCell
end % if okflag
if ~okflag
% construct an error message
if length(dtype)>1
str = sprintf('%s, ', dtype{1:(end-2)});
str = sprintf('%s%s or %s', str, dtype{end-1}, dtype{end});
else
str = dtype{1};
end
str = sprintf('This function requires %s data as input.', str);
error(str);
end % if okflag
end
if ~isempty(dimord)
if ~isa(dimord, 'cell')
dimord = {dimord};
end
if isfield(data, 'dimord')
okflag = any(strcmp(data.dimord, dimord));
else
okflag = 0;
end
if ~okflag
% construct an error message
if length(dimord)>1
str = sprintf('%s, ', dimord{1:(end-2)});
str = sprintf('%s%s or %s', str, dimord{end-1}, dimord{end});
else
str = dimord{1};
end
str = sprintf('This function requires data with a dimord of %s.', str);
error(str);
end % if okflag
end
if ~isempty(stype)
if ~isa(stype, 'cell')
stype = {stype};
end
if isfield(data, 'grad') || isfield(data, 'elec')
if any(strcmp(ft_senstype(data), stype));
okflag = 1;
else
okflag = 0;
end
else
okflag = 0;
end
if ~okflag
% construct an error message
if length(stype)>1
str = sprintf('%s, ', stype{1:(end-2)});
str = sprintf('%s%s or %s', str, stype{end-1}, stype{end});
else
str = stype{1};
end
str = sprintf('This function requires %s data as input, but you are giving %s data.', str, ft_senstype(data));
error(str);
end % if okflag
end
if ~isempty(ismeg)
if isequal(ismeg, 'yes')
okflag = isfield(data, 'grad');
elseif isequal(ismeg, 'no')
okflag = ~isfield(data, 'grad');
end
if ~okflag && isequal(ismeg, 'yes')
error('This function requires MEG data with a ''grad'' field');
elseif ~okflag && isequal(ismeg, 'no')
error('This function should not be given MEG data with a ''grad'' field');
end % if okflag
end
if ~isempty(inside)
% TODO absorb the fixinside function into this code
data = fixinside(data, inside);
okflag = isfield(data, 'inside');
if ~okflag
% construct an error message
error('This function requires data with an ''inside'' field.');
end % if okflag
end
%if isvolume
% % ensure consistent dimensions of the volumetric data
% % reshape each of the volumes that is found into a 3D array
% param = parameterselection('all', data);
% dim = data.dim;
% for i=1:length(param)
% tmp = getsubfield(data, param{i});
% tmp = reshape(tmp, dim);
% data = setsubfield(data, param{i}, tmp);
% end
%end
if isequal(hasunits, 'yes') && ~isfield(data, 'units')
% calling convert_units with only the input data adds the units without converting
data = ft_convert_units(data);
end
if issource || isvolume,
% the following section is to make a dimord-consistent representation of
% volume and source data, taking trials, time and frequency into account
if isequal(hasdimord, 'yes') && (~isfield(data, 'dimord') || ~strcmp(data.dimord,sourcedimord))
% determine the size of the data
if isfield(data, 'dimord'),
dimtok = tokenize(data.dimord, '_');
if ~isempty(strmatch('time', dimtok)), Ntime = length(data.time); else Ntime = 1; end
if ~isempty(strmatch('freq', dimtok)), Nfreq = length(data.freq); else Nfreq = 1; end
else
Nfreq = 1;
Ntime = 1;
end
%convert old style source representation into new style
if isfield(data, 'avg') && isfield(data.avg, 'mom') && (isfield(data, 'freq') || isfield(data, 'frequency')) && strcmp(sourcedimord, 'rpt_pos'),
%frequency domain source representation convert to single trial power
Npos = size(data.pos,1);
Nrpt = size(data.cumtapcnt,1);
tmpmom = zeros(Npos, size(data.avg.mom{data.inside(1)},2));
tmpmom(data.inside,:) = cat(1,data.avg.mom{data.inside});
tmppow = zeros(Npos, Nrpt);
tapcnt = [0;cumsum(data.cumtapcnt)];
for k = 1:Nrpt
Ntap = tapcnt(k+1)-tapcnt(k);
tmppow(data.inside,k) = sum(abs(tmpmom(data.inside,(tapcnt(k)+1):tapcnt(k+1))).^2,2)./Ntap;
end
data.pow = tmppow';
data = rmfield(data, 'avg');
if strcmp(inside, 'logical'),
data = fixinside(data, 'logical');
data.inside = repmat(data.inside(:)',[Nrpt 1]);
end
elseif isfield(data, 'avg') && isfield(data.avg, 'mom') && (isfield(data, 'freq') || isfield(data, 'frequency')) && strcmp(sourcedimord, 'rpttap_pos'),
%frequency domain source representation convert to single taper fourier coefficients
Npos = size(data.pos,1);
Nrpt = sum(data.cumtapcnt);
data.fourierspctrm = complex(zeros(Nrpt, Npos), zeros(Nrpt, Npos));
data.fourierspctrm(:, data.inside) = transpose(cat(1, data.avg.mom{data.inside}));
data = rmfield(data, 'avg');
elseif isfield(data, 'avg') && isfield(data.avg, 'mom') && isfield(data, 'time') && strcmp(sourcedimord, 'pos_time'),
Npos = size(data.pos,1);
Nrpt = 1;
tmpmom = zeros(Npos, size(data.avg.mom{data.inside(1)},2));
tmpmom(data.inside,:) = cat(1,data.avg.mom{data.inside});
data.mom = tmpmom;
if isfield(data.avg, 'noise'),
tmpnoise = data.avg.noise(:);
data.noise = tmpnoise(:,ones(1,size(tmpmom,2)));
end
data = rmfield(data, 'avg');
Ntime = length(data.time);
elseif isfield(data, 'trial') && isfield(data.trial(1), 'mom') && isfield(data, 'time') && strcmp(sourcedimord, 'rpt_pos_time'),
Npos = size(data.pos,1);
Nrpt = length(data.trial);
Ntime = length(data.time);
tmpmom = zeros(Nrpt, Npos, Ntime);
for k = 1:Nrpt
tmpmom(k,data.inside,:) = cat(1,data.trial(k).mom{data.inside});
end
data = rmfield(data, 'trial');
data.mom = tmpmom;
elseif isfield(data, 'trial') && isstruct(data.trial)
Nrpt = length(data.trial);
else
Nrpt = 1;
end
% start with an initial specification of the dimord and dim
if (~isfield(data, 'dim') || ~isfield(data, 'dimord'))
if issource
% at least it should have a Nx3 pos
data.dim = size(data.pos, 1);
data.dimord = 'pos';
elseif isvolume
% at least it should have a 1x3 dim
data.dim = data.dim;
data.dimord = 'dim1_dim2_dim3';
end
end
% add the additional dimensions
if Nfreq>1
data.dimord = [data.dimord '_freq'];
data.dim = [data.dim Nfreq];
end
if Ntime>1
data.dimord = [data.dimord '_time'];
data.dim = [data.dim Ntime];
end
if Nrpt>1 && strcmp(sourcedimord, 'rpt_pos'),
data.dimord = ['rpt_' data.dimord];
data.dim = [Nrpt data.dim ];
elseif Nrpt>1 && strcmp(sourcedimord, 'rpttap_pos'),
data.dimord = ['rpttap_' data.dimord];
data.dim = [Nrpt data.dim ];
end
% the nested trial structure is not compatible with dimord
if isfield(data, 'trial') && isstruct(data.trial)
param = fieldnames(data.trial);
for i=1:length(param)
if isa(data.trial(1).(param{i}), 'cell')
concat = cell(data.dim(1), prod(data.dim(2:end)));
else
concat = zeros(data.dim(1), prod(data.dim(2:end)));
end
for j=1:length(data.trial)
tmp = data.trial(j).(param{i});
concat(j,:) = tmp(:);
end % for each trial
data.trial = rmfield(data.trial, param{i});
data.(param{i}) = reshape(concat, data.dim);
end % for each param
data = rmfield(data, 'trial');
end
end
% ensure consistent dimensions of the source reconstructed data
% reshape each of the source reconstructed parameters
if issource && isfield(data, 'dim') && prod(data.dim)==size(data.pos,1)
dim = [prod(data.dim) 1];
elseif issource && any(~cellfun('isempty',strfind(fieldnames(data), 'dimord')))
dim = [size(data.pos,1) 1]; %sparsely represented source structure new style
elseif isfield(data, 'dim'),
dim = [data.dim 1];
elseif issource
dim = [size(data.pos,1) 1];
elseif isfield(data, 'dimord'),
%HACK
dimtok = tokenize(data.dimord, '_');
for i=1:length(dimtok)
if strcmp(dimtok(i), 'pos')
dim(1,i) = size(getsubfield(data,dimtok{i}),1);
elseif strcmp(dimtok(i), 'rpt')
dim(1,i) = nan;
else
dim(1,i) = length(getsubfield(data,dimtok{i}));
end
end
i = find(isnan(dim));
if ~isempty(i)
n = fieldnames(data);
for ii=1:length(n)
numels(1,ii) = numel(getfield(data,n{ii}));
end
nrpt = numels./prod(dim(setdiff(1:length(dim),i)));
nrpt = nrpt(nrpt==round(nrpt));
dim(i) = max(nrpt);
end
if numel(dim)==1, dim(1,2) = 1; end;
end
% these fields should not be reshaped
exclude = {'cfg' 'fwhm' 'leadfield' 'q' 'rough'};
if ~strcmp(inside, 'logical')
% also exclude the inside/outside from being reshaped
exclude = cat(2, exclude, {'inside' 'outside'});
end
param = setdiff(parameterselection('all', data), exclude);
for i=1:length(param)
if any(param{i}=='.')
% the parameter is nested in a substructure, which can have multiple elements (e.g. source.trial(1).pow, source.trial(2).pow, ...)
% loop over the substructure array and reshape for every element
tok = tokenize(param{i}, '.');
sub1 = tok{1}; % i.e. this would be 'trial'
sub2 = tok{2}; % i.e. this would be 'pow'
tmp1 = getfield(data, sub1);
for j=1:numel(tmp1)
tmp2 = getfield(tmp1(j), sub2);
tmp2 = reshape(tmp2, dim);
tmp1(j) = setfield(tmp1(j), sub2, tmp2);
end
data = setfield(data, sub1, tmp1);
else
tmp = getfield(data, param{i});
tmp = reshape(tmp, dim);
data = setfield(data, param{i}, tmp);
end
end
end
if isequal(hastrials, 'yes')
okflag = isfield(data, 'trial');
if ~okflag
error('This function requires data with a ''trial'' field');
end % if okflag
end
if isequal(hassampleinfo, 'yes') || isequal(hassampleinfo, 'ifmakessense')
data = fixsampleinfo(data);
end
if isequal(hasdim, 'yes') && ~isfield(data, 'dim')
data.dim = pos2dim(data.pos);
elseif isequal(hasdim, 'no') && isfield(data, 'dim')
data = rmfield(data, 'dim');
end % if hasdim
if isequal(hascumtapcnt, 'yes') && ~isfield(data, 'cumtapcnt')
error('This function requires data with a ''cumtapcnt'' field');
elseif isequal(hascumtapcnt, 'no') && isfield(data, 'cumtapcnt')
data = rmfield(data, 'cumtapcnt');
end % if hascumtapcnt
if isequal(hasdof, 'yes') && ~isfield(data, 'hasdof')
error('This function requires data with a ''dof'' field');
elseif isequal(hasdof, 'no') && isfield(data, 'hasdof')
data = rmfield(data, 'cumtapcnt');
end % if hasdof
if ~isempty(cmbrepresentation)
if istimelock
data = fixcov(data, cmbrepresentation);
elseif isfreq
data = fixcsd(data, cmbrepresentation, channelcmb);
elseif isfreqmvar
data = fixcsd(data, cmbrepresentation, channelcmb);
else
error('This function requires data with a covariance, coherence or cross-spectrum');
end
end % cmbrepresentation
if issource && ~isempty(sourcerepresentation)
data = fixsource(data, 'type', sourcerepresentation);
end
if issource && ~strcmp(haspow, 'no')
data = fixsource(data, 'type', sourcerepresentation, 'haspow', haspow);
end
if isfield(data, 'grad')
% ensure that the gradiometer balancing is specified
if ~isfield(data.grad, 'balance') || ~isfield(data.grad.balance, 'current')
data.grad.balance.current = 'none';
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% represent the covariance matrix in a particular manner
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function data = fixcov(data, desired)
if isfield(data, 'cov') && ~isfield(data, 'labelcmb')
current = 'full';
elseif isfield(data, 'cov') && isfield(data, 'labelcmb')
current = 'sparse';
else
error('Could not determine the current representation of the covariance matrix');
end
if isequal(current, desired)
% nothing to do
elseif strcmp(current, 'full') && strcmp(desired, 'sparse')
% FIXME should be implemented
error('not yet implemented');
elseif strcmp(current, 'sparse') && strcmp(desired, 'full')
% FIXME should be implemented
error('not yet implemented');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% represent the cross-spectral density matrix in a particular manner
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [data] = fixcsd(data, desired, channelcmb)
% FIXCSD converts univariate frequency domain data (fourierspctrm) into a bivariate
% representation (crsspctrm), or changes the representation of bivariate frequency
% domain data (sparse/full/sparsewithpow, sparsewithpow only works for crsspctrm or
% fourierspctrm)
% Copyright (C) 2010, Jan-Mathijs Schoffelen, Robert Oostenveld
if isfield(data, 'crsspctrm') && isfield(data, 'powspctrm')
current = 'sparsewithpow';
elseif isfield(data, 'powspctrm')
current = 'sparsewithpow';
elseif isfield(data, 'fourierspctrm') && ~isfield(data, 'labelcmb')
current = 'fourier';
elseif ~isfield(data, 'labelcmb')
current = 'full';
elseif isfield(data, 'labelcmb')
current = 'sparse';
else
error('Could not determine the current representation of the %s matrix', param);
end
% first go from univariate fourier to the required bivariate representation
if strcmp(current, 'fourier') && strcmp(desired, 'fourier')
% nothing to do
elseif strcmp(current, 'fourier') && strcmp(desired, 'sparsewithpow')
dimtok = tokenize(data.dimord, '_');
if ~isempty(strmatch('rpttap', dimtok)),
nrpt = size(data.cumtapcnt,1);
flag = 0;
else
nrpt = 1;
flag = 1;
end
if ~isempty(strmatch('freq', dimtok)), nfrq=length(data.freq); else nfrq = 1; end
if ~isempty(strmatch('time', dimtok)), ntim=length(data.time); else ntim = 1; end
fastflag = all(data.cumtapcnt(:)==data.cumtapcnt(1));
%create auto-spectra
nchan = length(data.label);
if fastflag
% all trials have the same amount of tapers
powspctrm = zeros(nrpt,nchan,nfrq,ntim);
ntap = data.cumtapcnt(1);
for p = 1:ntap
powspctrm = powspctrm + abs(data.fourierspctrm(p:ntap:end,:,:,:,:)).^2;
end
powspctrm = powspctrm./ntap;
else
% different amount of tapers
powspctrm = zeros(nrpt,nchan,nfrq,ntim)+i.*zeros(nrpt,nchan,nfrq,ntim);
sumtapcnt = [0;cumsum(data.cumtapcnt(:))];
for p = 1:nrpt
indx = (sumtapcnt(p)+1):sumtapcnt(p+1);
tmpdat = data.fourierspctrm(indx,:,:,:);
powspctrm(p,:,:,:) = (sum(tmpdat.*conj(tmpdat),1))./data.cumtapcnt(p);
end
end
%create cross-spectra
if ~isempty(channelcmb),
ncmb = size(channelcmb,1);
cmbindx = zeros(ncmb,2);
labelcmb = cell(ncmb,2);
for k = 1:ncmb
ch1 = find(strcmp(data.label, channelcmb(k,1)));
ch2 = find(strcmp(data.label, channelcmb(k,2)));
if ~isempty(ch1) && ~isempty(ch2),
cmbindx(k,:) = [ch1 ch2];
labelcmb(k,:) = data.label([ch1 ch2])';
end
end
crsspctrm = zeros(nrpt,ncmb,nfrq,ntim)+i.*zeros(nrpt,ncmb,nfrq,ntim);
if fastflag
for p = 1:ntap
tmpdat1 = data.fourierspctrm(p:ntap:end,cmbindx(:,1),:,:,:);
tmpdat2 = data.fourierspctrm(p:ntap:end,cmbindx(:,2),:,:,:);
crsspctrm = crsspctrm + tmpdat1.*conj(tmpdat2);
end
crsspctrm = crsspctrm./ntap;
else
for p = 1:nrpt
indx = (sumtapcnt(p)+1):sumtapcnt(p+1);
tmpdat1 = data.fourierspctrm(indx,cmbindx(:,1),:,:);
tmpdat2 = data.fourierspctrm(indx,cmbindx(:,2),:,:);
crsspctrm(p,:,:,:) = (sum(tmpdat1.*conj(tmpdat2),1))./data.cumtapcnt(p);
end
end
data.crsspctrm = crsspctrm;
data.labelcmb = labelcmb;
end
data.powspctrm = powspctrm;
data = rmfield(data, 'fourierspctrm');
if ntim>1,
data.dimord = 'chan_freq_time';
else
data.dimord = 'chan_freq';
end
if nrpt>1,
data.dimord = ['rpt_',data.dimord];
end
if flag, siz = size(data.crsspctrm); data.crsspctrm = reshape(data.crsspctrm, siz(2:end)); end
elseif strcmp(current, 'fourier') && strcmp(desired, 'sparse')
if isempty(channelcmb), error('no channel combinations are specified'); end
dimtok = tokenize(data.dimord, '_');
if ~isempty(strmatch('rpttap', dimtok)),
nrpt = size(data.cumtapcnt,1);
flag = 0;
else
nrpt = 1;
flag = 1;
end
if ~isempty(strmatch('freq', dimtok)), nfrq=length(data.freq); else nfrq = 1; end
if ~isempty(strmatch('time', dimtok)), ntim=length(data.time); else ntim = 1; end
ncmb = size(channelcmb,1);
cmbindx = zeros(ncmb,2);
labelcmb = cell(ncmb,2);
for k = 1:ncmb
ch1 = find(strcmp(data.label, channelcmb(k,1)));
ch2 = find(strcmp(data.label, channelcmb(k,2)));
if ~isempty(ch1) && ~isempty(ch2),
cmbindx(k,:) = [ch1 ch2];
labelcmb(k,:) = data.label([ch1 ch2])';
end
end
sumtapcnt = [0;cumsum(data.cumtapcnt(:))];
fastflag = all(data.cumtapcnt(:)==data.cumtapcnt(1));
if fastflag && nrpt>1
ntap = data.cumtapcnt(1);
% compute running sum across tapers
siz = [size(data.fourierspctrm) 1];
for p = 1:ntap
indx = p:ntap:nrpt*ntap;
if p==1.
tmpc = zeros(numel(indx), size(cmbindx,1), siz(3), siz(4)) + ...
1i.*zeros(numel(indx), size(cmbindx,1), siz(3), siz(4));
end
for k = 1:size(cmbindx,1)
tmpc(:,k,:,:) = data.fourierspctrm(indx,cmbindx(k,1),:,:).* ...
conj(data.fourierspctrm(indx,cmbindx(k,2),:,:));
end
if p==1
crsspctrm = tmpc;
else
crsspctrm = tmpc + crsspctrm;
end
end
crsspctrm = crsspctrm./ntap;
else
crsspctrm = zeros(nrpt, ncmb, nfrq, ntim);
for p = 1:nrpt
indx = (sumtapcnt(p)+1):sumtapcnt(p+1);
tmpdat1 = data.fourierspctrm(indx,cmbindx(:,1),:,:);
tmpdat2 = data.fourierspctrm(indx,cmbindx(:,2),:,:);
crsspctrm(p,:,:,:) = (sum(tmpdat1.*conj(tmpdat2),1))./data.cumtapcnt(p);
end
end
data.crsspctrm = crsspctrm;
data.labelcmb = labelcmb;
data = rmfield(data, 'fourierspctrm');
data = rmfield(data, 'label');
if ntim>1,
data.dimord = 'chan_freq_time';
else
data.dimord = 'chan_freq';
end
if nrpt>1,
data.dimord = ['rpt_',data.dimord];
end
if flag, siz = size(data.crsspctrm); data.crsspctrm = reshape(data.crsspctrm, siz(2:end)); end
elseif strcmp(current, 'fourier') && strcmp(desired, 'full')
% this is how it is currently and the desired functionality of prepare_freq_matrices
dimtok = tokenize(data.dimord, '_');
if ~isempty(strmatch('rpttap', dimtok)),
nrpt = size(data.cumtapcnt, 1);
flag = 0;
else
nrpt = 1;
flag = 1;
end
if ~isempty(strmatch('rpttap',dimtok)), nrpt=size(data.cumtapcnt, 1); else nrpt = 1; end
if ~isempty(strmatch('freq', dimtok)), nfrq=length(data.freq); else nfrq = 1; end
if ~isempty(strmatch('time', dimtok)), ntim=length(data.time); else ntim = 1; end
if any(data.cumtapcnt(1,:) ~= data.cumtapcnt(1,1)), error('this only works when all frequencies have the same number of tapers'); end
nchan = length(data.label);
crsspctrm = zeros(nrpt,nchan,nchan,nfrq,ntim);
sumtapcnt = [0;cumsum(data.cumtapcnt(:,1))];
for k = 1:ntim
for m = 1:nfrq
for p = 1:nrpt
%FIXME speed this up in the case that all trials have equal number of tapers
indx = (sumtapcnt(p)+1):sumtapcnt(p+1);
tmpdat = transpose(data.fourierspctrm(indx,:,m,k));
crsspctrm(p,:,:,m,k) = (tmpdat*tmpdat')./data.cumtapcnt(p);
clear tmpdat;
end
end
end
data.crsspctrm = crsspctrm;
data = rmfield(data, 'fourierspctrm');
if ntim>1,
data.dimord = 'chan_chan_freq_time';
else
data.dimord = 'chan_chan_freq';
end
if nrpt>1,
data.dimord = ['rpt_',data.dimord];
end
% remove first singleton dimension
if flag || nrpt==1, siz = size(data.crsspctrm); data.crsspctrm = reshape(data.crsspctrm, siz(2:end)); end
elseif strcmp(current, 'fourier') && strcmp(desired, 'fullfast'),
dimtok = tokenize(data.dimord, '_');
nrpt = size(data.fourierspctrm, 1);
nchn = numel(data.label);
nfrq = numel(data.freq);
if ~isempty(strmatch('time', dimtok)), ntim=numel(data.time); else ntim = 1; end
data.fourierspctrm = reshape(data.fourierspctrm, [nrpt nchn nfrq*ntim]);
data.fourierspctrm(~isfinite(data.fourierspctrm)) = 0;
crsspctrm = complex(zeros(nchn,nchn,nfrq*ntim));
for k = 1:nfrq*ntim
tmp = transpose(data.fourierspctrm(:,:,k));
n = sum(tmp~=0,2);
crsspctrm(:,:,k) = tmp*tmp'./n(1);
end
data = rmfield(data, 'fourierspctrm');
data.crsspctrm = reshape(crsspctrm, [nchn nchn nfrq ntim]);
if isfield(data, 'time'),
data.dimord = 'chan_chan_freq_time';
else
data.dimord = 'chan_chan_freq';
end
if isfield(data, 'trialinfo'), data = rmfield(data, 'trialinfo'); end;
if isfield(data, 'sampleinfo'), data = rmfield(data, 'sampleinfo'); end;
if isfield(data, 'cumsumcnt'), data = rmfield(data, 'cumsumcnt'); end;
if isfield(data, 'cumtapcnt'), data = rmfield(data, 'cumtapcnt'); end;
end % convert to the requested bivariate representation
% from one bivariate representation to another
if isequal(current, desired)
% nothing to do
elseif (strcmp(current, 'full') && strcmp(desired, 'fourier')) || ...
(strcmp(current, 'sparse') && strcmp(desired, 'fourier')) || ...
(strcmp(current, 'sparsewithpow') && strcmp(desired, 'fourier'))
% this is not possible
error('converting the cross-spectrum into a Fourier representation is not possible');
elseif strcmp(current, 'full') && strcmp(desired, 'sparsewithpow')
error('not yet implemented');
elseif strcmp(current, 'sparse') && strcmp(desired, 'sparsewithpow')
% convert back to crsspctrm/powspctrm representation: useful for plotting functions etc
indx = labelcmb2indx(data.labelcmb);
autoindx = indx(indx(:,1)==indx(:,2), 1);
cmbindx = setdiff([1:size(indx,1)]', autoindx);
if strcmp(data.dimord(1:3), 'rpt')
data.powspctrm = data.crsspctrm(:, autoindx, :, :);
data.crsspctrm = data.crsspctrm(:, cmbindx, :, :);
else
data.powspctrm = data.crsspctrm(autoindx, :, :);
data.crsspctrm = data.crsspctrm(cmbindx, :, :);
end
data.label = data.labelcmb(autoindx,1);
data.labelcmb = data.labelcmb(cmbindx, :);
if isempty(cmbindx)
data = rmfield(data, 'crsspctrm');
data = rmfield(data, 'labelcmb');
end
elseif strcmp(current, 'full') && strcmp(desired, 'sparse')
dimtok = tokenize(data.dimord, '_');
if ~isempty(strmatch('rpt', dimtok)), nrpt=size(data.cumtapcnt,1); else nrpt = 1; end
if ~isempty(strmatch('freq', dimtok)), nfrq=numel(data.freq); else nfrq = 1; end
if ~isempty(strmatch('time', dimtok)), ntim=numel(data.time); else ntim = 1; end
nchan = length(data.label);
ncmb = nchan*nchan;
labelcmb = cell(ncmb, 2);
cmbindx = zeros(nchan, nchan);
k = 1;
for j=1:nchan
for m=1:nchan
labelcmb{k, 1} = data.label{m};
labelcmb{k, 2} = data.label{j};
cmbindx(m,j) = k;
k = k+1;
end
end
% reshape all possible fields
fn = fieldnames(data);
for ii=1:numel(fn)
if numel(data.(fn{ii})) == nrpt*ncmb*nfrq*ntim;
if nrpt>1,
data.(fn{ii}) = reshape(data.(fn{ii}), nrpt, ncmb, nfrq, ntim);
else
data.(fn{ii}) = reshape(data.(fn{ii}), ncmb, nfrq, ntim);
end
end
end
% remove obsolete fields
data = rmfield(data, 'label');
try, data = rmfield(data, 'dof'); end
% replace updated fields
data.labelcmb = labelcmb;
if ntim>1,
data.dimord = 'chancmb_freq_time';
else
data.dimord = 'chancmb_freq';
end
if nrpt>1,
data.dimord = ['rpt_',data.dimord];
end
elseif strcmp(current, 'sparsewithpow') && strcmp(desired, 'sparse')
% this representation for sparse data contains autospectra
% as e.g. {'A' 'A'} in labelcmb
if isfield(data, 'crsspctrm'),
dimtok = tokenize(data.dimord, '_');
catdim = match_str(dimtok, {'chan' 'chancmb'});
data.crsspctrm = cat(catdim, data.powspctrm, data.crsspctrm);
data.labelcmb = [data.label(:) data.label(:); data.labelcmb];
data = rmfield(data, 'powspctrm');
else
data.crsspctrm = data.powspctrm;
data.labelcmb = [data.label(:) data.label(:)];
data = rmfield(data, 'powspctrm');
end
data = rmfield(data, 'label');
elseif strcmp(current, 'sparse') && strcmp(desired, 'full')
dimtok = tokenize(data.dimord, '_');
if ~isempty(strmatch('rpt', dimtok)), nrpt=size(data.cumtapcnt,1); else nrpt = 1; end
if ~isempty(strmatch('freq', dimtok)), nfrq=numel(data.freq); else nfrq = 1; end
if ~isempty(strmatch('time', dimtok)), ntim=numel(data.time); else ntim = 1; end
if ~isfield(data, 'label')
% ensure that the bivariate spectral factorization results can be
% processed. FIXME this is experimental and will not work if the user
% did something weird before
for k = 1:numel(data.labelcmb)
tmp = tokenize(data.labelcmb{k}, '[');
data.labelcmb{k} = tmp{1};
end
data.label = unique(data.labelcmb(:));
end
nchan = length(data.label);
ncmb = size(data.labelcmb,1);
cmbindx = zeros(nchan,nchan);
for k = 1:size(data.labelcmb,1)
ch1 = find(strcmp(data.label, data.labelcmb(k,1)));
ch2 = find(strcmp(data.label, data.labelcmb(k,2)));
if ~isempty(ch1) && ~isempty(ch2),
cmbindx(ch1,ch2) = k;
end
end
complete = all(cmbindx(:)~=0);
fn = fieldnames(data);
for ii=1:numel(fn)
if numel(data.(fn{ii})) == nrpt*ncmb*nfrq*ntim;
if nrpt==1,
data.(fn{ii}) = reshape(data.(fn{ii}), [nrpt ncmb nfrq ntim]);
end
tmpall = nan(nrpt,nchan,nchan,nfrq,ntim);
for j = 1:nrpt
for k = 1:ntim
for m = 1:nfrq
tmpdat = nan(nchan,nchan);
indx = find(cmbindx);
if ~complete
% this realizes the missing combinations to be represented as the
% conjugate of the corresponding combination across the diagonal
tmpdat(indx) = reshape(data.(fn{ii})(j,cmbindx(indx),m,k),[numel(indx) 1]);
tmpdat = ctranspose(tmpdat);
end
tmpdat(indx) = reshape(data.(fn{ii})(j,cmbindx(indx),m,k),[numel(indx) 1]);
tmpall(j,:,:,m,k) = tmpdat;
end % for m
end % for k
end % for j
% replace the data in the old representation with the new representation
if nrpt>1,
data.(fn{ii}) = tmpall;
else
data.(fn{ii}) = reshape(tmpall, [nchan nchan nfrq ntim]);
end
end % if numel
end % for ii
% remove obsolete fields
try, data = rmfield(data, 'powspctrm'); end
try, data = rmfield(data, 'labelcmb'); end
try, data = rmfield(data, 'dof'); end
if ntim>1,
data.dimord = 'chan_chan_freq_time';
else
data.dimord = 'chan_chan_freq';
end
if nrpt>1,
data.dimord = ['rpt_',data.dimord];
end
elseif strcmp(current, 'sparse') && strcmp(desired, 'fullfast')
dimtok = tokenize(data.dimord, '_');
if ~isempty(strmatch('rpt', dimtok)), nrpt=size(data.cumtapcnt,1); else nrpt = 1; end
if ~isempty(strmatch('freq', dimtok)), nfrq=numel(data.freq); else nfrq = 1; end
if ~isempty(strmatch('time', dimtok)), ntim=numel(data.time); else ntim = 1; end
if ~isfield(data, 'label')
data.label = unique(data.labelcmb(:));
end
nchan = length(data.label);
ncmb = size(data.labelcmb,1);
cmbindx = zeros(nchan,nchan);
for k = 1:size(data.labelcmb,1)
ch1 = find(strcmp(data.label, data.labelcmb(k,1)));
ch2 = find(strcmp(data.label, data.labelcmb(k,2)));
if ~isempty(ch1) && ~isempty(ch2),
cmbindx(ch1,ch2) = k;
end
end
complete = all(cmbindx(:)~=0);
fn = fieldnames(data);
for ii=1:numel(fn)
if numel(data.(fn{ii})) == nrpt*ncmb*nfrq*ntim;
if nrpt==1,
data.(fn{ii}) = reshape(data.(fn{ii}), [nrpt ncmb nfrq ntim]);
end
tmpall = nan(nchan,nchan,nfrq,ntim);
for k = 1:ntim
for m = 1:nfrq
tmpdat = nan(nchan,nchan);
indx = find(cmbindx);
if ~complete
% this realizes the missing combinations to be represented as the
% conjugate of the corresponding combination across the diagonal
tmpdat(indx) = reshape(nanmean(data.(fn{ii})(:,cmbindx(indx),m,k)),[numel(indx) 1]);
tmpdat = ctranspose(tmpdat);
end
tmpdat(indx) = reshape(nanmean(data.(fn{ii})(:,cmbindx(indx),m,k)),[numel(indx) 1]);
tmpall(:,:,m,k) = tmpdat;
end % for m
end % for k
% replace the data in the old representation with the new representation
if nrpt>1,
data.(fn{ii}) = tmpall;
else
data.(fn{ii}) = reshape(tmpall, [nchan nchan nfrq ntim]);
end
end % if numel
end % for ii
% remove obsolete fields
try, data = rmfield(data, 'powspctrm'); end
try, data = rmfield(data, 'labelcmb'); end
try, data = rmfield(data, 'dof'); end
if ntim>1,
data.dimord = 'chan_chan_freq_time';
else
data.dimord = 'chan_chan_freq';
end
elseif strcmp(current, 'sparsewithpow') && strcmp(desired, 'full')
% this is how is currently done in prepare_freq_matrices
data = ft_checkdata(data, 'cmbrepresentation', 'sparse');
data = ft_checkdata(data, 'cmbrepresentation', 'full');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert to new source representation
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [output] = fixsource(input, varargin)
% FIXSOURCE converts old style source structures into new style source structures and the
% other way around
%
% Use as:
% fixsource(input, type)
% where input is a source structure,
%
% Typically, old style source structures contain
% avg.XXX or trial.XXX fields
%
% The new style source structure contains:
% source.pos
% source.dim (optional, if the list of positions describes a 3D volume
% source.XXX the old style subfields in avg/trial
% source.XXXdimord string how to interpret the respective XXX field:
% e.g. source.leadfield = cell(1,Npos), source.leadfielddimord = '{pos}_chan_ori'
% source.mom = cell(1,Npos), source.momdimord = '{pos}_ori_rpttap'
type = keyval('type', varargin);
haspow = keyval('haspow', varargin);
if isempty(type), type = 'old'; end
if isempty(haspow), haspow = 'no'; end
fnames = fieldnames(input);
tmp = cell2mat(strfind(fnames, 'dimord')); %get dimord like fields
if any(tmp>1),
current = 'new';
elseif any(tmp==1),
%don't know what to do yet data is JM's own invention
current = 'old';
else
current = 'old';
end
if strcmp(current, type),
%do nothing
output = input;
%return
elseif strcmp(current, 'old') && strcmp(type, 'new'),
%go from old to new
if isfield(input, 'avg'),
stuff = getfield(input, 'avg');
output = rmfield(input, 'avg');
elseif isfield(input, 'trial'),
stuff = getfield(input, 'trial');
output = rmfield(input, 'trial');
else
%this could occur later in the pipeline, e.g. when doing group statistics using individual subject
%descriptive statistics
error('the input does not contain an avg or trial field');
end
%-------------------------------------------------
%remove and rename the specified fields if present
removefields = {'xgrid';'ygrid';'zgrid';'method'};
renamefields = {'frequency' 'freq'; 'csdlabel' 'orilabel'};
fnames = fieldnames(output);
for k = 1:numel(fnames)
ix = strmatch(fnames{k}, removefields);
if ~isempty(ix),
output = rmfield(output, fnames{k});
end
ix = strmatch(fnames{k}, renamefields(:,1), 'exact');
if ~isempty(ix),
output = setfield(output, renamefields{ix,2}, ...
getfield(output, renamefields{ix,1}));
output = rmfield(output, fnames{k});
end
end
%----------------------------------------------------------------------
%put the stuff originally in avg or trial one level up in the structure
fnames = fieldnames(stuff(1));
npos = size(input.pos,1);
nrpt = numel(stuff);
for k = 1:numel(fnames)
if nrpt>1,
%multiple trials
%(or subjects FIXME not yet implemented, nor tested)
tmp = getfield(stuff(1), fnames{k});
siz = size(tmp);
if isfield(input, 'cumtapcnt') && strcmp(fnames{k}, 'mom')
%pcc based mom is orixrpttap
%tranpose to keep manageable
for kk = 1:numel(input.inside)
indx = input.inside(kk);
tmp{indx} = permute(tmp{indx}, [2 1 3]);
end
nrpttap = sum(input.cumtapcnt);
sizvox = [size(tmp{input.inside(1)}) 1];
sizvox = [nrpttap sizvox(2:end)];
elseif strcmp(fnames{k}, 'mom'),
%this is then probably not a frequency based mom
nrpttap = numel(stuff);
sizvox = [size(tmp{input.inside(1)}) 1];
sizvox = [nrpttap sizvox];
elseif iscell(tmp)
nrpttap = numel(stuff);
sizvox = [size(tmp{input.inside(1)}) 1];
sizvox = [nrpttap sizvox];
end
if siz(1) ~= npos && siz(2) ==npos,
tmp = transpose(tmp);
end
if iscell(tmp)
%allocate memory for cell-array
tmpall = cell(npos,1);
for n = 1:numel(input.inside)
tmpall{input.inside(n)} = zeros(sizvox);
end
else
%allocate memory for matrix
tmpall = zeros([npos nrpt siz(2:end)]);
end
cnt = 0;
for m = 1:nrpt
tmp = getfield(stuff(m), fnames{k});
siz = size(tmp);
if siz(1) ~= npos && siz(2) ==npos,
tmp = transpose(tmp);
end
if ~iscell(tmp),
tmpall(:,m,:,:,:) = tmp;
else
for n = 1:numel(input.inside)
indx = input.inside(n);
tmpdat = tmp{indx};
if isfield(input, 'cumtapcnt') && strcmp(fnames{k}, 'mom'),
if n==1, siz1 = size(tmpdat,2); end
else
if n==1, siz1 = 1; end
end
tmpall{indx}(cnt+[1:siz1],:,:,:,:) = tmpdat;
if n==numel(input.inside), cnt = cnt + siz1; end
end
end
end
output = setfield(output, fnames{k}, tmpall);
newdimord = createdimord(output, fnames{k}, 1);
if ~isempty(newdimord)
output = setfield(output, [fnames{k},'dimord'], newdimord);
end
else
tmp = getfield(stuff, fnames{k});
siz = size(tmp);
if isfield(input, 'cumtapcnt') && strcmp(fnames{k}, 'mom')
%pcc based mom is orixrpttap
%tranpose to keep manageable
for kk = 1:numel(input.inside)
indx = input.inside(kk);
tmp{indx} = permute(tmp{indx}, [2 1 3]);
end
end
if siz(1) ~= npos && siz(2) ==npos,
tmp = transpose(tmp);
end
output = setfield(output, fnames{k}, tmp);
newdimord = createdimord(output, fnames{k});
if ~isempty(newdimord)
output = setfield(output, [fnames{k},'dimord'], newdimord);
end
end
end
if isfield(output, 'csdlabel')
output = setfield(output, 'orilabel', getfield(output, 'csdlabel'));
output = rmfield(output, 'csdlabel');
end
if isfield(output, 'leadfield')
% add dimord to leadfield as well. since the leadfield is not in
% the original .avg or .trial field it has not yet been taken care of
output.leadfielddimord = createdimord(output, 'leadfield');
end
if isfield(output, 'ori')
% convert cell-array ori into matrix
ori = zeros(3,npos) + nan;
try,
ori(:,output.inside) = cat(2, output.ori{output.inside});
catch
%when oris are in wrong orientation (row rather than column)
for k = 1:numel(output.inside)
ori(:,output.inside(k)) = output.ori{output.inside(k)}';
end
end
output.ori = ori;
end
current = 'new';
elseif strcmp(current, 'new') && strcmp(type, 'old')
%go from new to old
error('not implemented yet');
end
if strcmp(current, 'new') && strcmp(haspow, 'yes'),
%----------------------------------------------
%convert mom into pow if requested and possible
convert = 0;
if isfield(output, 'mom') && size(output.mom{output.inside(1)},2)==1,
convert = 1;
else
warning('conversion from mom to pow is not possible, either because there is no mom in the data, or because the dimension of mom>1. in that case call ft_sourcedescriptives first with cfg.projectmom');
end
if isfield(output, 'cumtapcnt')
convert = 1 & convert;
else
warning('conversion from mom to pow will not be done, because cumtapcnt is missing');
end
if convert,
npos = size(output.pos,1);
nrpt = size(output.cumtapcnt,1);
tmpmom = cat(2,output.mom{output.inside});
tmppow = zeros(npos, nrpt);
tapcnt = [0;cumsum(output.cumtapcnt(:))];
for k = 1:nrpt
ntap = tapcnt(k+1)-tapcnt(k);
tmppow(output.inside,k) = sum(abs(tmpmom((tapcnt(k)+1):tapcnt(k+1),:)).^2,1)./ntap;
end
output.pow = tmppow;
output.powdimord = ['pos_rpt_freq'];
end
elseif strcmp(current, 'old') && strcmp(haspow, 'yes')
warning('construction of single trial power estimates is not implemented here using old style source representation');
end
%--------------------------------------------------------
function [dimord] = createdimord(output, fname, rptflag);
if nargin==2, rptflag = 0; end
tmp = getfield(output, fname);
dimord = '';
dimnum = 1;
hasori = isfield(output, 'ori'); %if not, this is probably singleton and not relevant at the end
if iscell(tmp) && (size(output.pos,1)==size(tmp,dimnum) || size(output.pos,1)==size(tmp,2))
dimord = [dimord,'{pos}'];
dimnum = dimnum + 1;
elseif ~iscell(tmp) && size(output.pos,1)==size(tmp,dimnum)
dimord = [dimord,'pos'];
dimnum = dimnum + 1;
end
switch fname
case 'cov'
if hasori, dimord = [dimord,'_ori_ori']; end;
case 'csd'
if hasori, dimord = [dimord,'_ori_ori']; end;
case 'csdlabel'
dimord = dimord;
case 'filter'
dimord = [dimord,'_ori_chan'];
case 'leadfield'
%if hasori,
dimord = [dimord,'_chan_ori'];
%else
% dimord = [dimord,'_chan'];
%end
case 'mom'
if isfield(output, 'cumtapcnt') && sum(output.cumtapcnt)==size(tmp{output.inside(1)},1)
if hasori,
dimord = [dimord,'_rpttap_ori'];
else
dimord = [dimord,'_rpttap'];
end
elseif isfield(output, 'time')
if rptflag,
dimord = [dimord,'_rpt'];
dimnum = dimnum + 1;
end
if numel(output.time)==size(tmp{output.inside(1)},dimnum)
dimord = [dimord,'_ori_time'];
end
end
if isfield(output, 'freq') && numel(output.freq)>1,
dimord = [dimord,'_freq'];
end
case 'nai'
if isfield(output, 'freq') && numel(output.freq)==size(tmp,dimnum)
dimord = [dimord,'_freq'];
end
case 'noise'
if isfield(output, 'freq') && numel(output.freq)==size(tmp,dimnum)
dimord = [dimord,'_freq'];
end
case 'noisecsd'
if hasori, dimord = [dimord,'_ori_ori']; end
case 'ori'
dimord = '';
case 'pow'
if isfield(output, 'cumtapcnt') && size(output.cumtapcnt,1)==size(tmp,dimnum)
dimord = [dimord,'_rpt'];
dimnum = dimnum + 1;
end
if isfield(output, 'freq') && numel(output.freq)>1 && numel(output.freq)==size(tmp,dimnum)
dimord = [dimord,'_freq'];
dimnum = dimnum+1;
end
if isfield(output, 'time') && numel(output.time)>1 && numel(output.time)==size(tmp,dimnum)
dimord = [dimord,'_time'];
dimnum = dimnum+1;
end
otherwise
warning('skipping unknown fieldname %s', fname);
%error(sprintf('unknown fieldname %s', fname));
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert between datatypes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function data = comp2raw(data)
% just remove the component topographies
data = rmfield(data, 'topo');
data = rmfield(data, 'topolabel');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert between datatypes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function data = volume2source(data)
if isfield(data, 'dimord')
% it is a modern source description
else
% it is an old-fashioned source description
xgrid = 1:data.dim(1);
ygrid = 1:data.dim(2);
zgrid = 1:data.dim(3);
[x y z] = ndgrid(xgrid, ygrid, zgrid);
data.pos = warp_apply(data.transform, [x(:) y(:) z(:)]);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert between datatypes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function data = source2volume(data)
if isfield(data, 'dimord')
% it is a modern source description
%this part depends on the assumption that the list of positions is describing a full 3D volume in
%an ordered way which allows for the extraction of a transformation matrix
%i.e. slice by slice
try,
if isfield(data, 'dim'),
data.dim = pos2dim(data.pos, data.dim);
else
data.dim = pos2dim(data);
end
catch
end
end
if isfield(data, 'dim') && length(data.dim)>=3,
% it is an old-fashioned source description, or the source describes a regular 3D volume in pos
xgrid = 1:data.dim(1);
ygrid = 1:data.dim(2);
zgrid = 1:data.dim(3);
[x y z] = ndgrid(xgrid, ygrid, zgrid);
ind = [x(:) y(:) z(:)]; % these are the positions expressed in voxel indices along each of the three axes
pos = data.pos; % these are the positions expressed in head coordinates
% represent the positions in a manner that is compatible with the homogeneous matrix multiplication,
% i.e. pos = H * ind
ind = ind'; ind(4,:) = 1;
pos = pos'; pos(4,:) = 1;
% recompute the homogeneous transformation matrix
data.transform = pos / ind;
end
% remove the unwanted fields
if isfield(data, 'pos'), data = rmfield(data, 'pos'); end
if isfield(data, 'xgrid'), data = rmfield(data, 'xgrid'); end
if isfield(data, 'ygrid'), data = rmfield(data, 'ygrid'); end
if isfield(data, 'zgrid'), data = rmfield(data, 'zgrid'); end
% make inside a volume
data = fixinside(data, 'logical');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert between datatypes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function data = freq2raw(freq)
if strcmp(freq.dimord, 'rpt_chan_freq_time')
dat = freq.powspctrm;
elseif strcmp(freq.dimord, 'rpttap_chan_freq_time')
warning('converting fourier representation into raw data format. this is experimental code');
dat = freq.fourierspctrm;
else
error('this only works for dimord=''rpt_chan_freq_time''');
end
nrpt = size(dat,1);
nchan = size(dat,2);
nfreq = size(dat,3);
ntime = size(dat,4);
data = [];
% create the channel labels like "MLP11@12Hz""
k = 0;
for i=1:nfreq
for j=1:nchan
k = k+1;
data.label{k} = sprintf('%s@%dHz', freq.label{j}, freq.freq(i));
end
end
% reshape and copy the data as if it were timecourses only
for i=1:nrpt
data.time{i} = freq.time;
data.trial{i} = reshape(dat(i,:,:,:), nchan*nfreq, ntime);
if any(isnan(data.trial{i}(1,:))),
tmp = data.trial{i}(1,:);
begsmp = find(isfinite(tmp),1, 'first');
endsmp = find(isfinite(tmp),1, 'last' );
data.trial{i} = data.trial{i}(:, begsmp:endsmp);
data.time{i} = data.time{i}(begsmp:endsmp);
end
end
nsmp = cellfun('size',data.time,2);
seln = find(nsmp>1,1, 'first');
data.fsample = 1/(data.time{seln}(2)-data.time{seln}(1));
if isfield(freq, 'trialinfo'), data.trialinfo = freq.trialinfo; end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert between datatypes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [data] = raw2timelock(data)
nsmp = cellfun('size',data.time,2);
data = ft_checkdata(data, 'hassampleinfo', 'yes');
ntrial = numel(data.trial);
nchan = numel(data.label);
if ntrial==1
data.time = data.time{1};
data.avg = data.trial{1};
data = rmfield(data, 'trial');
data.dimord = 'chan_time';
else
% determine the location of the trials relative to the resulting combined time axis
begtime = cellfun(@min, data.time);
endtime = cellfun(@max, data.time);
begsmp = round((begtime - min(begtime)) * data.fsample) + 1;
endsmp = round((endtime - min(begtime)) * data.fsample) + 1;
% create a combined time axis and concatenate all trials
tmptime = min(begtime):(1/data.fsample):max(endtime);
tmptrial = zeros(ntrial, nchan, length(tmptime)) + nan;
for i=1:ntrial
tmptrial(i,:,begsmp(i):endsmp(i)) = data.trial{i};
end
% update the sampleinfo
begpad = begsmp - min(begsmp);
endpad = max(endsmp) - endsmp;
if isfield(data, 'sampleinfo')
data.sampleinfo = data.sampleinfo + [-begpad(:) endpad(:)];
end
% construct the output timelocked data
% data.avg = reshape(nanmean(tmptrial, 1), nchan, length(tmptime));
% data.var = reshape(nanvar (tmptrial, [], 1), nchan, length(tmptime))
% data.dof = reshape(sum(~isnan(tmptrial), 1), nchan, length(tmptime));
data.trial = tmptrial;
data.time = tmptime;
data.dimord = 'rpt_chan_time';
data = rmfield(data, 'fsample'); % fsample in timelock data is obsolete
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert between datatypes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [data] = timelock2raw(data)
try
nsmp = cellfun('size',data.time,2);
catch
nsmp = size(data.time,2);
end
switch data.dimord
case 'chan_time'
data.trial{1} = data.avg;
data.time = {data.time};
data = rmfield(data, 'avg');
seln = find(nsmp>1,1, 'first');
data.fsample = 1/(data.time{seln}(2)-data.time{seln}(1));
case 'rpt_chan_time'
tmptrial = {};
tmptime = {};
ntrial = size(data.trial,1);
nchan = size(data.trial,2);
ntime = size(data.trial,3);
for i=1:ntrial
tmptrial{i} = reshape(data.trial(i,:,:), [nchan, ntime]);
tmptime{i} = data.time;
end
data = rmfield(data, 'trial');
data.trial = tmptrial;
data.time = tmptime;
seln = find(nsmp>1,1, 'first');
data.fsample = 1/(data.time{seln}(2)-data.time{seln}(1));
case 'subj_chan_time'
tmptrial = {};
tmptime = {};
ntrial = size(data.individual,1);
nchan = size(data.individual,2);
ntime = size(data.individual,3);
for i=1:ntrial
tmptrial{i} = reshape(data.individual(i,:,:), [nchan, ntime]);
tmptime{i} = data.time;
end
data = rmfield(data, 'individual');
data.trial = tmptrial;
data.time = tmptime;
seln = find(nsmp>1,1, 'first');
data.fsample = 1/(data.time{seln}(2)-data.time{seln}(1));
otherwise
error('unsupported dimord');
end
% remove the unwanted fields
if isfield(data, 'avg'), data = rmfield(data, 'avg'); end
if isfield(data, 'var'), data = rmfield(data, 'var'); end
if isfield(data, 'cov'), data = rmfield(data, 'cov'); end
if isfield(data, 'dimord'), data = rmfield(data, 'dimord'); end
if isfield(data, 'numsamples'), data = rmfield(data, 'numsamples'); end
if isfield(data, 'dof'), data = rmfield(data, 'dof'); end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert between datatypes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [data] = chan2freq(data)
data.dimord = [data.dimord '_freq'];
data.freq = nan;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert between datatypes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [data] = chan2timelock(data)
data.dimord = [data.dimord '_time'];
data.time = nan;
|
github
|
philippboehmsturm/antx-master
|
nearest.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/utilities/nearest.m
| 2,220 |
utf_8
|
2bb829a5040b8b57693d43dee7d42f08
|
function [i] = nearest(array, val)
% NEAREST return the index of an array nearest to a scalar
%
% [indx] = nearest(array, val)
% Copyright (C) 2002, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: nearest.m 2865 2011-02-12 19:24:57Z roboos $
mbreal(array);
mbreal(val);
mbvector(array);
mbscalar(val);
% ensure that it is a column vector
array = array(:);
if isnan(val)
error('incorrect value')
end
if val>max(array)
% return the last occurence of the nearest number
[dum, i] = max(flipud(array));
i = length(array) + 1 - i;
else
% return the first occurence of the nearest number
[mindist, i] = min(abs(array(:) - val));
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function mbreal(a)
if ~isreal(a)
error('Argument to mbreal must be real');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function mbscalar(a)
if ~all(size(a)==1)
error('Argument to mbscalar must be scalar');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function mbvector(a)
if ndims(a) > 2 | (size(a, 1) > 1 & size(a, 2) > 1)
error('Argument to mbvector must be a vector');
end
|
github
|
philippboehmsturm/antx-master
|
ft_checkopt.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/utilities/ft_checkopt.m
| 2,880 |
utf_8
|
e5dcf5f9eda8bcdbe4e14c446ec47697
|
function opt = ft_checkopt(opt, key, allowedtype, allowedval)
% FT_CHECKOPT does a validity test on the types and values of a configuration
% structure or cell-array with key-value pairs.
%
% Use as
% opt = ft_checkopt(opt, key, allowedtype, allowedval)
%
% For allowedtype you can specify a string or a cell-array with multiple
% strings. All the default MATLAB types can be specified, for example
% 'double'
% 'logical'
% 'char'
% 'single'
% 'float'
% 'int16'
% 'cell'
% 'struct'
% 'function_handle'
% Furthermore, the following custom types can be specified
% 'doublescalar'
% 'doublevector'
% 'doublematrix'
% 'charcell'
%
% For allowedval you can specify a single value or a cell-array
% with multiple values.
%
% This function will give an error or it returns the input configuration
% structure or cell-array without modifications. Any match on allowedtype and
% any match on allowedval is sufficient to let this function pass.
%
% See also FT_GETOPT, FT_SETOPT
% Copyright (C) 2011, Robert Oostenveld
%
% $Id: ft_checkopt.m 2922 2011-02-21 21:47:27Z roboos $
if nargin<3
allowedtype = {};
end
if ~iscell(allowedtype)
allowedtype = {allowedtype};
end
if nargin<4
allowedval = {};
end
if ~iscell(allowedval)
allowedval = {allowedval};
end
% get the value that belongs to this key
val = ft_getopt(opt, key);
% check that the type of the option is allowed
ok = isempty(allowedtype);
for i=1:length(allowedtype)
switch allowedtype{i}
case 'empty'
ok = isempty(val);
case 'doublescalar'
ok = isa(val, 'double') && all(size(val)==1);
case 'doublevector'
ok = isa(val, 'double') && sum(size(val)>1)==1;
case 'doublematrix'
ok = isa(val, 'double') && sum(size(val)>1)>1;
case 'charcell'
ok = isa(val, 'cell') && all(cellfun(@ischar, val(:)));
otherwise
ok = isa(val, allowedtype{i});
end
if ok
% no reason to do additional checks
break
end
end % for allowedtype
if ~ok
if length(allowedtype)==1
error('the type of the option "%s" is invalid, it should be "%s" instead of "%s"', key, allowedtype{1}, class(val));
else
error('the type of the option "%s" is invalid, it should be any of %s instead of "%s"', key, printcell(allowedtype), class(val));
end
end
% check that the type of the option is allowed
ok = isempty(allowedval);
for i=1:length(allowedval)
ok = isequal(val, allowedval{i});
if ok
% no reason to do additional checks
break
end
end % for allowedtype
if ~ok
error('the value of the option "%s" is invalid', key);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function s = printcell(c)
if ~isempty(c)
s = sprintf('%s, ', c{:});
s = sprintf('{%s}', s(1:end-2));
else
s = '{}';
end
|
github
|
philippboehmsturm/antx-master
|
ft_struct2double.m
|
.m
|
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/utilities/ft_struct2double.m
| 2,907 |
utf_8
|
80254f0d01f62d7443be4f8c21f36ded
|
function [x] = ft_struct2double(x, maxdepth);
% FT_STRUCT2DOUBLE converts all single precision numeric data in a structure
% into double precision. It will also convert plain matrices and
% cell-arrays.
%
% Use as
% x = ft_struct2double(x);
%
% Starting from Matlab 7.0, you can use single precision data in your
% computations, i.e. you do not have to convert back to double precision.
%
% Matlab version 6.5 and older only support single precision for storing
% data in memory or on disk, but do not allow computations on single
% precision data. Therefore you should converted your data from single to
% double precision after reading from file.
%
% See also FT_STRUCT2SINGLE
% Copyright (C) 2005, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip 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.
%
% FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_struct2double.m 3213 2011-03-24 22:37:01Z jansch $
if nargin<2
maxdepth = inf;
end
% convert the data, work recursively through the complete structure
x = convert(x, 0, maxdepth);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% this subfunction does the actual work
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [a] = convert(a, depth, maxdepth);
if depth>maxdepth
error('recursive depth exceeded');
end
switch class(a)
case 'struct'
% process all fields of the structure recursively
fna = fieldnames(a);
% process all elements of the array
for j=1:length(a(:))
% warning, this is a recursive call to traverse nested structures
for i=1:length(fna)
fn = fna{i};
ra = getfield(a(j), fn);
ra = convert(ra, depth+1, maxdepth);
a(j) = setfield(a(j), fn, ra);
end
end
case 'cell'
% process all elements of the cell-array recursively
% warning, this is a recursive call to traverse nested structures
for i=1:length(a(:))
a{i} = convert(a{i}, depth+1, maxdepth);
end
case {'single' 'int32' 'uint32' 'int16' 'uint16'}
% convert the values to double precision
a = double(a);
case 'double'
% keep as it is
otherwise
warning_once(sprintf('not converting class %s', class(a)));
% do nothing
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.