├── BANetworkROIs_v4.txt ├── NGNetworkROIs_area_definition_v2.txt ├── NGNetworkROIs_to_BA.m ├── NGNetworkROIs_v4.txt ├── README.md ├── README.txt ├── brain.png ├── brain2.png ├── brain_coords.txt ├── brain_coords2.txt ├── cm17.mat ├── cm18.mat ├── compare_volumes_loreta_script.m ├── convertleadfieldtofieldtrip.m ├── cortex.mat ├── eegplugin_roiconnect.m ├── libs ├── Daniele_ARMA │ ├── EXample1.m │ ├── Example2.m │ ├── Geweke_f.m │ ├── InstModelfilter.m │ ├── MVARfilter.m │ ├── block_fdMVAR.m │ ├── choldiag.m │ ├── idMVAR.m │ ├── iss_AR.m │ ├── iss_MA.m │ ├── iss_SGC.m │ ├── parcovar.m │ ├── ss2iss.m │ └── varma2iss.m ├── brainstorm │ ├── bst_bsxfun.m │ ├── tess_smooth.m │ └── tess_vertconn.m ├── export_fig │ ├── .gitignore │ ├── LICENSE │ ├── README.md │ ├── append_pdfs.m │ ├── copyfig.m │ ├── crop_borders.m │ ├── eps2pdf.m │ ├── export_fig.m │ ├── fix_lines.m │ ├── ghostscript.m │ ├── im2gif.m │ ├── isolate_axes.m │ ├── pdf2eps.m │ ├── pdftops.m │ ├── print2array.m │ ├── print2eps.m │ ├── read_write_entire_textfile.m │ ├── user_string.m │ └── using_hg2.m ├── haufe │ ├── allplots_cortex_BS.m │ ├── allplots_cortex_nyhead.m │ ├── autocov_to_var2.m │ ├── autocov_to_var3.m │ ├── cm17.mat │ ├── compute_roi_connectivity_140321.m │ ├── cs2coh.m │ ├── cs2psd.m │ ├── data2cs_event.m │ ├── data2sctrgc.m │ ├── data2sctrgcmim.m │ ├── data2spwctrgc.m │ ├── est_DTF.m │ ├── est_PDC.m │ ├── lcmv.m │ ├── mkfilt_eloreta_v2.m │ ├── roi_mim2.m │ ├── showsurface3.m │ └── showvc_prog_plain2.m ├── jurhar │ ├── bispectral_TD_est.m │ ├── combine_sn.m │ ├── mk_delay.m │ ├── mk_series.m │ └── segment_data.m ├── mvgc_v1.0 │ ├── C │ │ └── genvar_mex.c │ ├── GPL_v3.txt │ ├── core │ │ ├── autocov_to_cpsd.m │ │ ├── autocov_to_var.m │ │ ├── autocov_xform.m │ │ ├── cpsd_to_autocov.m │ │ ├── cpsd_to_var.m │ │ ├── cpsd_xform.m │ │ ├── tsdata_to_autocov.m │ │ ├── tsdata_to_cpsd.m │ │ ├── tsdata_to_infocrit.m │ │ ├── tsdata_to_var.m │ │ ├── var_to_autocov.m │ │ ├── var_to_cpsd.m │ │ ├── var_to_tsdata.m │ │ └── var_to_tsdata_nonstat.m │ ├── demo │ │ ├── mvgc_demo.m │ │ ├── mvgc_demo_GCCA.m │ │ ├── mvgc_demo_bootstrap.m │ │ ├── mvgc_demo_nonstationary.m │ │ ├── mvgc_demo_permtest.m │ │ ├── mvgc_demo_stats.m │ │ ├── mvgc_demo_test1.m │ │ ├── var5_test.m │ │ └── var9_test.m │ ├── docs │ │ ├── html │ │ │ ├── GCCA_tsdata_to_mvgc.html │ │ │ ├── GCCA_tsdata_to_pwcgc.html │ │ │ ├── GCCA_tsdata_to_smvgc.html │ │ │ ├── autocov_to_cpsd.html │ │ │ ├── autocov_to_mvgc.html │ │ │ ├── autocov_to_pwcgc.html │ │ │ ├── autocov_to_smvgc.html │ │ │ ├── autocov_to_spwcgc.html │ │ │ ├── autocov_to_var.html │ │ │ ├── autocov_xform.html │ │ │ ├── bfft.html │ │ │ ├── bifft.html │ │ │ ├── bootstrap_tsdata_to_mvgc.html │ │ │ ├── bootstrap_tsdata_to_pwcgc.html │ │ │ ├── bootstrap_tsdata_to_smvgc.html │ │ │ ├── bootstrap_tsdata_to_spwcgc.html │ │ │ ├── chi2cdf.html │ │ │ ├── chi2inv.html │ │ │ ├── consistency.html │ │ │ ├── cov2corr.html │ │ │ ├── cpsd_to_autocov.html │ │ │ ├── cpsd_to_var.html │ │ │ ├── cpsd_xform.html │ │ │ ├── demean.html │ │ │ ├── dlyap.html │ │ │ ├── dlyap_aitr.html │ │ │ ├── empirical_cdf.html │ │ │ ├── empirical_cdfi.html │ │ │ ├── empirical_confint.html │ │ │ ├── empirical_cval.html │ │ │ ├── empirical_pval.html │ │ │ ├── empirical_var_to_mvgc.html │ │ │ ├── empirical_var_to_pwcgc.html │ │ │ ├── empirical_var_to_smvgc.html │ │ │ ├── empirical_var_to_spwcgc.html │ │ │ ├── eq_ac2cpsd.png │ │ │ ├── eq_aitr.png │ │ │ ├── eq_cpsd2ac.png │ │ │ ├── eq_dlyap.png │ │ │ ├── eq_mvgc.png │ │ │ ├── eq_mvgc_pwc.png │ │ │ ├── eq_smvgc.png │ │ │ ├── eq_smvgc_int.png │ │ │ ├── eq_smvgc_pwc.png │ │ │ ├── eq_smvgc_uncond.png │ │ │ ├── eq_var.png │ │ │ ├── eq_varnn.png │ │ │ ├── eq_vma.png │ │ │ ├── eq_yweqs.png │ │ │ ├── fexists.html │ │ │ ├── gamcdf.html │ │ │ ├── gaminv.html │ │ │ ├── gampdf.html │ │ │ ├── genvar.html │ │ │ ├── get_crand.html │ │ │ ├── get_hostname.html │ │ │ ├── get_urand.html │ │ │ ├── helpon.html │ │ │ ├── helptoc.xml │ │ │ ├── ii_Sigma.png │ │ │ ├── ii_acseq.png │ │ │ ├── ii_dlyapre.png │ │ │ ├── ii_inej.png │ │ │ ├── ii_nu.png │ │ │ ├── infocrit.html │ │ │ ├── isbad.html │ │ │ ├── isint.html │ │ │ ├── isposdef.html │ │ │ ├── lyapslv.html │ │ │ ├── make_legacy.html │ │ │ ├── maxabs.html │ │ │ ├── mvdetrend.html │ │ │ ├── mvdiff.html │ │ │ ├── mvgc_adf.html │ │ │ ├── mvgc_cdf.html │ │ │ ├── mvgc_cdfi.html │ │ │ ├── mvgc_confint.html │ │ │ ├── mvgc_cval.html │ │ │ ├── mvgc_demo.html │ │ │ ├── mvgc_demo_GCCA.html │ │ │ ├── mvgc_demo_bootstrap.html │ │ │ ├── mvgc_demo_nonstationary.html │ │ │ ├── mvgc_demo_permtest.html │ │ │ ├── mvgc_demo_stats.html │ │ │ ├── mvgc_kpss.html │ │ │ ├── mvgc_makemex.html │ │ │ ├── mvgc_pval.html │ │ │ ├── mvgc_schema.html │ │ │ ├── mvgcfuncref.html │ │ │ ├── mvgchelp.html │ │ │ ├── mvgcrelnotes.html │ │ │ ├── mvgcschema.png │ │ │ ├── permtest_tsdata_to_mvgc.html │ │ │ ├── permtest_tsdata_to_pwcgc.html │ │ │ ├── permtest_tsdata_to_smvgc.html │ │ │ ├── permtest_tsdata_to_spwcgc.html │ │ │ ├── plot_autocov.html │ │ │ ├── plot_confints.html │ │ │ ├── plot_cpsd.html │ │ │ ├── plot_pw.html │ │ │ ├── plot_spw.html │ │ │ ├── plot_tsdata.html │ │ │ ├── plot_varcoeffs.html │ │ │ ├── ptic.html │ │ │ ├── ptoc.html │ │ │ ├── quads.html │ │ │ ├── quadsr.html │ │ │ ├── rng_restore.html │ │ │ ├── rng_save.html │ │ │ ├── rng_seed.html │ │ │ ├── rsquared.html │ │ │ ├── secs2hms.html │ │ │ ├── sfreqs.html │ │ │ ├── significance.html │ │ │ ├── smvgc_to_mvgc.html │ │ │ ├── startup.html │ │ │ ├── timestr.html │ │ │ ├── trfun2var.html │ │ │ ├── tsdata_to_autocov.html │ │ │ ├── tsdata_to_autocov_debias.html │ │ │ ├── tsdata_to_cpsd.html │ │ │ ├── tsdata_to_infocrit.html │ │ │ ├── tsdata_to_var.html │ │ │ ├── var2trfun.html │ │ │ ├── var5_test.html │ │ │ ├── var5test.png │ │ │ ├── var9_test.html │ │ │ ├── var9test.png │ │ │ ├── var_decay.html │ │ │ ├── var_info.html │ │ │ ├── var_normalise.html │ │ │ ├── var_specrad.html │ │ │ ├── var_to_autocov.html │ │ │ ├── var_to_cpsd.html │ │ │ ├── var_to_tsdata.html │ │ │ ├── var_to_tsdata_nonstat.html │ │ │ ├── warn_if.html │ │ │ ├── warn_supp.html │ │ │ ├── warn_test.html │ │ │ └── whiteness.html │ │ ├── info.xml │ │ ├── mvgc_preprint.pdf │ │ ├── mvgc_schema.m │ │ ├── mvgcfuncref.m │ │ ├── mvgchelp.m │ │ └── mvgcrelnotes.m │ ├── experimental │ │ ├── mvgc_adf.m │ │ ├── mvgc_kpss.m │ │ └── tsdata_to_autocov_debias.m │ ├── gc │ │ ├── GCCA_compat │ │ │ ├── GCCA_tsdata_to_mvgc.m │ │ │ ├── GCCA_tsdata_to_pwcgc.m │ │ │ └── GCCA_tsdata_to_smvgc.m │ │ ├── autocov_to_mvgc.m │ │ ├── autocov_to_pwcgc.m │ │ ├── autocov_to_smvgc.m │ │ ├── autocov_to_spwcgc_bak.m │ │ ├── smvgc_to_mvgc.m │ │ └── subsample │ │ │ ├── bootstrap_tsdata_to_mvgc.m │ │ │ ├── bootstrap_tsdata_to_pwcgc.m │ │ │ ├── bootstrap_tsdata_to_smvgc.m │ │ │ ├── bootstrap_tsdata_to_spwcgc.m │ │ │ ├── bootstrap_tsdata_to_trpwcgc.m │ │ │ ├── bootstrap_tsdata_to_trspwcgc.m │ │ │ ├── bootstrap_tsdata_to_trspwcgc2.m │ │ │ ├── empirical_var_to_mvgc.m │ │ │ ├── empirical_var_to_pwcgc.m │ │ │ ├── empirical_var_to_smvgc.m │ │ │ ├── empirical_var_to_spwcgc.m │ │ │ ├── permtest_tsdata_to_mvgc.m │ │ │ ├── permtest_tsdata_to_pwcgc.m │ │ │ ├── permtest_tsdata_to_smvgc.m │ │ │ └── permtest_tsdata_to_spwcgc.m │ ├── license.txt │ ├── mex │ │ ├── genvar_mex.mexa64 │ │ ├── genvar_mex.mexmaci64 │ │ └── genvar_mex.mexw64 │ ├── startup.m │ ├── stats │ │ ├── consistency.m │ │ ├── demean.m │ │ ├── empirical_cdf.m │ │ ├── empirical_cdfi.m │ │ ├── empirical_confint.m │ │ ├── empirical_cval.m │ │ ├── empirical_pval.m │ │ ├── infocrit.m │ │ ├── mvgc_cdf.m │ │ ├── mvgc_cdfi.m │ │ ├── mvgc_confint.m │ │ ├── mvgc_cval.m │ │ ├── mvgc_pval.m │ │ ├── rsquared.m │ │ ├── significance.m │ │ └── whiteness.m │ └── utils │ │ ├── bfft.m │ │ ├── bifft.m │ │ ├── control │ │ ├── dlyap.m │ │ └── lyapslv.m │ │ ├── cov2corr.m │ │ ├── dlyap_aitr.m │ │ ├── fexists.m │ │ ├── genvar.m │ │ ├── get_crand.m │ │ ├── get_hostname.m │ │ ├── get_urand.m │ │ ├── helpon.m │ │ ├── isbad.m │ │ ├── isint.m │ │ ├── isposdef.m │ │ ├── legacy │ │ ├── make_legacy.m │ │ ├── randi │ │ │ └── randi.m │ │ └── rng │ │ │ └── rng.m │ │ ├── maxabs.m │ │ ├── mvdetrend.m │ │ ├── mvdiff.m │ │ ├── mvgc_makemex.m │ │ ├── plot_autocov.m │ │ ├── plot_confints.m │ │ ├── plot_cpsd.m │ │ ├── plot_pw.m │ │ ├── plot_spw.m │ │ ├── plot_tsdata.m │ │ ├── plot_varcoeffs.m │ │ ├── ptic.m │ │ ├── ptoc.m │ │ ├── quads.m │ │ ├── quadsr.m │ │ ├── rng_restore.m │ │ ├── rng_save.m │ │ ├── rng_seed.m │ │ ├── secs2hms.m │ │ ├── sfreqs.m │ │ ├── stats │ │ ├── chi2cdf.m │ │ ├── chi2inv.m │ │ ├── gamcdf.m │ │ ├── gaminv.m │ │ └── gampdf.m │ │ ├── timestr.m │ │ ├── trfun2var.m │ │ ├── var2trfun.m │ │ ├── var_decay.m │ │ ├── var_info.m │ │ ├── var_normalise.m │ │ ├── var_specrad.m │ │ ├── warn_if.m │ │ ├── warn_supp.m │ │ └── warn_test.m ├── nolte │ ├── colormap_interpol.m │ ├── data2bs_event.m │ ├── data2bs_threenorm.m │ └── data2bs_univar.m ├── pellegrini │ ├── fp_data2bs_event_uni.m │ └── fp_fft_coeffs.m └── ssgc_v1.0 │ ├── README.txt │ ├── ar2iss.m │ ├── ar_IC.m │ ├── ar_gen.m │ ├── ar_rand.m │ ├── arsid_OLS.m │ ├── cov_rand.m │ ├── cov_rand1.m │ ├── iss_AR.m │ ├── iss_GC.m │ ├── iss_MA.m │ ├── iss_PWGC.m │ ├── iss_SGC.m │ ├── iss_SPWGC.m │ ├── iss_cpsd.m │ ├── iss_ds.m │ ├── iss_gen.m │ ├── iss_rand.m │ ├── parcovar.m │ ├── s4sid_CCA.m │ ├── specnorm.m │ ├── ss2iss.m │ └── ssgc_demo.m ├── newscripts ├── process_ds001787.m └── roi_connectivity_brainstorm_eloreta_ori.m ├── patchline.m ├── plotconnectivity.m ├── pop_roi_activity.m ├── pop_roi_connect.m ├── pop_roi_connectplot.m ├── pop_roi_statsplot.m ├── pop_toggleroiandica.m ├── private └── getatlaslist.m ├── raw_example └── NDARAA948VFH │ └── raw.set ├── resources ├── FC_MIM_cortex_left.jpg ├── FC_MIM_cortex_right.jpg ├── FC_MIM_cortex_seed49_left.jpg ├── FC_MIM_cortex_seed50_right.jpg ├── FC_MIM_matrix.png ├── FC_MIM_matrix_groupedhems.png ├── FC_MIM_matrix_groupedhems_left.jpg ├── FC_MIM_matrix_left.jpg ├── FC_MIM_matrix_left.png ├── FC_MIM_matrix_lefthem_left.jpg ├── FC_MIM_matrix_right.jpg ├── FC_MIM_matrix_righthem_right.jpg ├── power_barplot_left.jpg ├── power_barplot_right.jpg ├── power_cortex_left.jpg └── power_cortex_right.jpg ├── roi_activity.m ├── roi_connect.m ├── roi_connect_compare.m ├── roi_connstats.m ├── roi_csnetworkact.m ├── roi_definenetwork.m ├── roi_getact.m ├── roi_getpower.m ├── roi_lookupregions.m ├── roi_neighbor.m ├── roi_network.m ├── roi_networkplot.m ├── roi_pac.m ├── roi_plotnetwork.m ├── roi_sourceplot.m ├── roi_tde.m ├── simulate_sources.m ├── simulations └── sim_tde_bispec.m ├── test_pipes ├── cmp_roi_selection.m ├── pipeline_connectivity.m ├── test_brainplots_dkatlas.m ├── test_brainplots_loretaatlas.m ├── test_flex_epochlength.m ├── test_fooof.m ├── test_largebarplot_dkatlas.m ├── test_matrixplots_brainregions.m ├── test_matrixplots_dkatlas.m ├── test_matrixplots_loretaatlas.m ├── test_mim_stats.m ├── test_pac.m ├── test_roi_selection.m ├── test_snippets_connectivity.m ├── test_tde.m └── test_zeropadding.m └── utils ├── calc_pac.m ├── data2bs_pac.m ├── data2cs_event_shuf.m ├── get_connect_mat.m ├── get_labels.m ├── replace_underscores.m ├── rm_components.m ├── roi_mim2_v2.m ├── shuffle_BS.m └── shuffle_CS.m /BANetworkROIs_v4.txt: -------------------------------------------------------------------------------- 1 | Cingulo_opercular_network DNM Salience_network Executive_network Working_memory_network Dorsal_attention_network 2 | 13L 23L 13L 8L 6R 17R 3 | 42L 31L 24L 9L 8R 18R 4 | 8L 39L 32L 10L 9R 19R 5 | 9L 24L 33L 46L 7R 7R 6 | 10L 25L 13R 3L 39R 8R 7 | ThalamusL 32L 24R 5L 40R 17L 8 | 13R 33L 32R 7L 6L 18L 9 | 42R 23R 33R 39L 8L 19L 10 | 8R 31R 40L 9L 7L 11 | 9R 39R 8R 7L 8L 12 | 10R 24R 9R 39L 13 | ThaRamusR 25R 10R 40L 14 | 39R 32R 46R 15 | 40R 33R 3R 16 | 39L 5R 17 | 40L 7R 18 | 39R 19 | 40R 20 | -------------------------------------------------------------------------------- /NGNetworkROIs_area_definition_v2.txt: -------------------------------------------------------------------------------- 1 | Augular_gyrus_L Prefrontal_cortex_L Post_cingulate_cortex_L Insular_cortex_L Dorsal_anterior_cingulate_cortex_L Dorso_lateral_prefrontal_cortex_L Parietal_lobe_L Frontal_midline_cortex_L Frontal_operculum_L Dorsal_anterior_prefrontal_cortex_L Thalamus_L Right_anterior_inferior_parietal_lobe_L Posterior_partietal_cortex_L Frontal_eye_field_L Intraparietal_sulcus_region_L Visual_cortex_L Augular_gyrus_R Prefrontal_cortex_R Post_cingulate_cortex_R Insular_cortex_R Dorsal_anterior_cingulate_cortex_R Dorso_lateral_prefrontal_cortex_R Parietal_lobe_R Frontal_midline_cortex_R Frontal_operculum_R Dorsal_anterior_prefrontal_cortex_R Thalamus_R Right_anterior_inferior_parietal_lobe_R Posterior_partietal_cortex_R Frontal_eye_field_R Intraparietal_sulcus_region_R Visual_cortex_R 2 | 39L 24L 23L 13L 24L 8L 3L 6L 42L 8L ThalamusL 39L 7L 8L 7L 17L 39R 24R 23R 13R 24R 8R 3R 6R 42R 8R ThaRamusR 39R 7R 8R 7R 17R 3 | 25L 31L 32L 9L 5L 8L 9L 40L 39L 18L 25R 31R 32R 9R 5R 8R 9R 40R 39R 18R 4 | 32L 33L 10L 7L 9L 10L 40L 19L 32R 33R 10R 7R 9R 10R 40R 19R 5 | 33L 46L 39L 33R 46R 39R 6 | 40L 40R -------------------------------------------------------------------------------- /NGNetworkROIs_to_BA.m: -------------------------------------------------------------------------------- 1 | clear 2 | allAreas = readtable('NGNetworkROIs_area_definition_v2.txt', 'delimiter', char(9)); 3 | networks = readtable('NGNetworkROIs_v4.txt', 'delimiter', char(9)); 4 | networksNew = networks; 5 | networksNew(2:end,:) = []; 6 | 7 | networkNames = fieldnames(networks); 8 | allAreasNames = fieldnames(allAreas); 9 | allAreasNames = allAreasNames(1:end-3); 10 | for iNet = 1:length(networkNames)-3 11 | 12 | count = 1; 13 | areas = networks.(networkNames{iNet}); 14 | addAreaList = {}; 15 | 16 | % get the list of areas 17 | for iArea = 1:length(areas) 18 | areaNameTmp = areas{iArea}; 19 | 20 | if ~isempty(areaNameTmp) 21 | if areaNameTmp(end) ~= 'L' && areaNameTmp(end) ~= 'R' 22 | areaNameTmp1 = [ areaNameTmp '_R' ]; 23 | areaNameTmp2 = [ areaNameTmp '_L' ]; 24 | colPos1 = strmatch(areaNameTmp1, allAreasNames, 'exact'); 25 | colPos2 = strmatch(areaNameTmp2, allAreasNames, 'exact'); 26 | addAreaList = { addAreaList{:} allAreas{:,colPos1}{:} allAreas{:,colPos2}{:} }; 27 | else 28 | colPos = strmatch(areaNameTmp, allAreasNames, 'exact'); 29 | addAreaList = { addAreaList{:} allAreas{:,colPos}{:} }; 30 | end 31 | end 32 | end 33 | 34 | % write the list of areas 35 | addAreaList(cellfun(@isempty, addAreaList)) = []; 36 | for iArea = 1:length(addAreaList) 37 | networksNew(iArea,iNet) = { addAreaList{iArea} }; 38 | end 39 | end 40 | writetable(networksNew, 'BANetworkROIs_v4.txt', 'delimiter', char(9)); 41 | -------------------------------------------------------------------------------- /NGNetworkROIs_v4.txt: -------------------------------------------------------------------------------- 1 | Cingulo_opercular_network DNM Salience_network Executive_network Working_memory_network Dorsal_attention_network 2 | Insular_cortex_L Post_cingulate_cortex_L Insular_cortex_L Dorso_lateral_prefrontal_cortex_L Frontal_midline_cortex_R Visual_cortex_R 3 | Frontal_operculum_L Augular_gyrus_L Dorsal_anterior_cingulate_cortex_L Parietal_lobe_L Posterior_partietal_cortex_R Intraparietal_sulcus_region_R 4 | Dorsal_anterior_prefrontal_cortex_L Prefrontal_cortex_L Insular_cortex_R Dorso_lateral_prefrontal_cortex_R Frontal_eye_field_R 5 | Thalamus_L Post_cingulate_cortex_R Dorsal_anterior_cingulate_cortex_R Parietal_lobe_R Frontal_midline_cortex_L Visual_cortex_L 6 | Insular_cortex_R Augular_gyrus_R Posterior_partietal_cortex_L Intraparietal_sulcus_region_L 7 | Frontal_operculum_R Prefrontal_cortex_R Frontal_eye_field_L 8 | Dorsal_anterior_prefrontal_cortex_R 9 | Thalamus_R 10 | Right_anterior_inferior_parietal_lobe -------------------------------------------------------------------------------- /README.txt: -------------------------------------------------------------------------------- 1 | Open questions 2 | 3 | 1. For Brainstorm, did you use Freesurfer on the selected subject and extract 4 | the head model for this specific subject? How did you align the electrodes 5 | to the head model. I do not believe the scanned location of the electrodes 6 | were available. 7 | 8 | 2. What is the advantage of using a surface Atlas such as Desikan-Killiany 9 | compared to a volumetric one (since you are using Loreta anyway). 10 | 11 | 3. Do the function work for continuous data? 12 | 13 | 4. OK to do eLoreta on a mesh instead of a volume? 14 | 15 | 5. What about the additional connectivity measures in one of the function 16 | -------------------------------------------------------------------------------- /brain.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/brain.png -------------------------------------------------------------------------------- /brain2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/brain2.png -------------------------------------------------------------------------------- /brain_coords.txt: -------------------------------------------------------------------------------- 1 | Augular_gyrus Prefrontal_cortex Post_cingulate_cortex Insular_cortex Dorsal_anterior_cingulate_cortex Dorso_lateral_prefrontal_cortex Parietal_lobe Frontal_midline_cortex Frontal_operculum Dorsal_anterior_prefrontal_cortex Thalamus Right_anterior_inferior_parietal_lobe Posterior_partietal_cortex Frontal_eye_field Intraparietal_sulcus_region Visual_cortex 2 | x 0.65 0.1 0.45 0.3 0.17 0.15 0.7 0.3 0.25 0.18 0.5 0.7 0.8 0.3 0.7 0.85 3 | y 0.65 0.6 0.7 0.52 0.65 0.75 0.8 0.8 0.57 0.8 0.35 0.6 0.7 0.9 0.8 0.35 4 | deep 0 0 1 1 1 0 0 0 0 0 1 0 0 0 0 0 -------------------------------------------------------------------------------- /brain_coords2.txt: -------------------------------------------------------------------------------- 1 | Augular_gyrus_L Prefrontal_cortex_L Post_cingulate_cortex_L Insular_cortex_L Dorsal_anterior_cingulate_cortex_L Dorso_lateral_prefrontal_cortex_L Parietal_lobe_L Frontal_midline_cortex_L Frontal_operculum_L Dorsal_anterior_prefrontal_cortex_L Thalamus_L Right_anterior_inferior_parietal_lobe_L Posterior_partietal_cortex_L Frontal_eye_field_L Intraparietal_sulcus_region_L Visual_cortex_L Augular_gyrus_R Prefrontal_cortex_R Post_cingulate_cortex_R Insular_cortex_R Dorsal_anterior_cingulate_cortex_R Dorso_lateral_prefrontal_cortex_R Parietal_lobe_R Frontal_midline_cortex_R Frontal_operculum_R Dorsal_anterior_prefrontal_cortex_R Thalamus_R Right_anterior_inferior_parietal_lobe_R Posterior_partietal_cortex_R Frontal_eye_field_R Intraparietal_sulcus_region_R Visual_cortex_R 2 | x 0.65 0.1 0.45 0.3 0.17 0.15 0.7 0.3 0.25 0.18 0.5 0.7 0.8 0.3 0.7 0.85 0.65 0.1 0.45 0.3 0.17 0.15 0.7 0.3 0.25 0.18 0.5 0.7 0.8 0.3 0.7 0.85 3 | y 0.65 0.6 0.7 0.52 0.65 0.75 0.8 0.8 0.57 0.8 0.35 0.6 0.7 0.9 0.8 0.35 1.35 1.4 1.3 1.48 1.35 1.25 1.2 1.2 1.43 1.2 1.65 1.4 1.3 1.1 1.2 1.65 4 | deep 0 0 1 1 1 0 0 0 0 0 1 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 1 0 0 0 0 0 -------------------------------------------------------------------------------- /cm17.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/cm17.mat -------------------------------------------------------------------------------- /cm18.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/cm18.mat -------------------------------------------------------------------------------- /compare_volumes_loreta_script.m: -------------------------------------------------------------------------------- 1 | filename1 = '/data/matlab/eeglab/plugins/dipfit/standard_BEM/standard_vol.mat'; 2 | p = fileparts(which('ft_defaults.m')); 3 | filename2 = fullfile(p, 'template','atlas','afni','TTatlas+tlrc.HEAD'); 4 | 5 | % PUT BREAKPOINT LINE 44 of plot3dmeshalign (which will load and align the 6 | % AFNI model 7 | plot3dmeshalign(filename1, filename2, [], [1 0 0], [0 0 1], {'Thalamus'}); 8 | 9 | % then copy and paste the code below 10 | filename2 = 'LORETA-Talairach-BAs.mat'; 11 | tmp = load('-mat', filename2); 12 | 13 | indRm = []; 14 | for iVert = 1:length(tmp.Vertices) 15 | if min(sqrt(sum(bsxfun(@minus, pos2(:,:), tmp.Vertices(iVert,:)).^2,2))) > 20 16 | indRm = [indRm iVert]; 17 | end 18 | end 19 | tmp.Vertices(indRm,:) = []; 20 | figure; h = plot3(pos2(:,1),pos2(:,2),pos2(:,3), '.', 'color', color2); 21 | hold on; plot3(tmp.Vertices(:,1),tmp.Vertices(:,2), tmp.Vertices(:,3), '.', 'color', color1); 22 | axis equal; 23 | xlabel('x') 24 | ylabel('y') 25 | zlabel('z') 26 | 27 | pos3 = [-3 -4; 28 | -3 -11; 29 | -3 -18; 30 | -10 -4; 31 | -10 -11; 32 | -10 -18; 33 | -10 -25; 34 | -17 -11; 35 | -17 -18; 36 | -17 -25; 37 | -17 -32; 38 | -24 -25; 39 | -24 -32]; 40 | pos3 = [ pos3; -pos3(:,1)+1 pos3(:,2)]; 41 | pos3 = [ [pos3 ones(size(pos3,1),1)*1];[pos3 ones(size(pos3,1),1)*8];[pos3 ones(size(pos3,1),1)*15] ]; 42 | hold on; h = plot3(pos3(:,1),pos3(:,2), pos3(:,3), '.', 'color', 'g'); 43 | set(h, 'MarkerSize', 20) 44 | 45 | % Add to Loreta source model 46 | cortex = load('-mat', 'LORETA-Talairach-BAs.mat'); 47 | cortex.Vertices = [ cortex.Vertices; pos3]; 48 | cortex.Atlas.Scouts(end+1).Label = 'ThalamusL'; 49 | cortex.Atlas.Scouts(end).Vertices = [2395:2395+size(pos3,1)/2-1]; 50 | cortex.Atlas.Scouts(end+1).Label = 'ThalamusR'; 51 | cortex.Atlas.Scouts(end).Vertices = [2395+size(pos3,1)/2:size(cortex.Vertices,1)]; 52 | save('-mat', 'LORETA-Talairach-BAs.mat', '-struct', 'cortex'); 53 | -------------------------------------------------------------------------------- /convertleadfieldtofieldtrip.m: -------------------------------------------------------------------------------- 1 | % convert leadfield Matrix so it can be used in Fieldtrip 2 | 3 | function sourcemodel = convertleadfieldtofieldtrip(lf, varargin) 4 | 5 | if nargin < 2 6 | help convertleadfieldtofieldtrip; 7 | return; 8 | end 9 | 10 | g = finputcheck(varargin, { 'unit' 'string' {} ''; 11 | 'inside' 'string' {} ''; 12 | 'pos' 'real' {} []; 13 | 'label' 'cell' {} {}; 14 | 15 | 'unit' 'string' {} 'mm' }, 'convertleadfieldtofieldtrip'); 16 | if ischar(g), error(g); end 17 | 18 | if isfield(lf, 'Vertices') 19 | sourcemodel.pos = lf.Vertices; 20 | else 21 | sourcemodel.pos = g.pos(:,1:3); 22 | end 23 | if isempty(sourcemodel.pos) 24 | error('Position of vertices must be present either in the Leadfield Matrix structure or provided as additional argument'); 25 | end 26 | % leadfield 27 | if isfield(lf, 'LFM') 28 | sourcemodel.pos = sourcemodel.pos(1:end/3,:); % duplicated positions 29 | 30 | sourcemodel.leadfield = cell(size(sourcemodel.pos,1),1); 31 | nChans = size(lf.LFM,1); 32 | nChans = 32; 33 | 34 | lf.LFM = reshape(lf.LFM, size(lf.LFM,1), size(lf.LFM,2)/3, 3); 35 | for iPos = 1:length(sourcemodel.leadfield) 36 | sourcemodel.leadfield{iPos} = squeeze(lf.LFM(1:nChans,iPos,:)); 37 | end 38 | end 39 | 40 | 41 | % units 42 | if isempty(g.unit) 43 | if max(sourcemodel.pos(:,1)) > 50 44 | sourcemodel.unit = 'mm'; 45 | elseif max(sourcemodel.pos(:,1)) > 5 46 | sourcemodel.unit = 'cm'; 47 | else 48 | sourcemodel.unit = 'm'; 49 | end 50 | fprintf('Assuming unit in %s based on vertices coordinates\n', sourcemodel.unit); 51 | end 52 | 53 | % inside 54 | if isempty(g.inside) 55 | sourcemodel.inside = ones(size(sourcemodel.pos,1),1) > 0; 56 | fprintf('Assuming all vertices are contained within the head model\n', sourcemodel.unit); 57 | end 58 | 59 | % electrode labels 60 | if ~isempty(g.label) 61 | sourcemodel.label = g.label; 62 | else 63 | for iChan = 1:nChans 64 | sourcemodel.label{iChan} = sprintf('E%d', iChan); 65 | end 66 | end 67 | 68 | % dim ord 69 | sourcemodel.leadfielddimord = '{pos}_chan_ori'; 70 | return 71 | 72 | % test 73 | cfg = []; 74 | dataPre = eeglab2fieldtrip(EEG, 'preprocessing', 'dipfit'); 75 | cfg.method = 'eloreta'; 76 | cfg.sourcemodel = sourcemodel; 77 | %cfg.headmodel = vol.vol; 78 | source = ft_sourceanalysis(cfg, dataPre); % compute the source 79 | 80 | 81 | -------------------------------------------------------------------------------- /cortex.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/cortex.mat -------------------------------------------------------------------------------- /libs/Daniele_ARMA/Geweke_f.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/libs/Daniele_ARMA/Geweke_f.m -------------------------------------------------------------------------------- /libs/Daniele_ARMA/InstModelfilter.m: -------------------------------------------------------------------------------- 1 | %% realization of the instantaneous model : U = L*W 2 | %%% OUTPUT 3 | % U: N*M matrix of filtered noises 4 | 5 | % INPUT 6 | % N data length 7 | % C: input covariance matrix (may be interpreted as Su or Sw, see above) 8 | % B0: M*M matrix of instantaneous effects (when relevant) 9 | 10 | % when flag='StrictlyCausal': 11 | % given Su, applies Cholesky decomposition to find L and Sw 12 | % then generates U = L*W, for a realization of gaussian W of variance Sw 13 | 14 | % when flag='ExtendedGauss': 15 | % given Sw and B(0), computes L=[I-B(0)]^(-1) 16 | % then generates U = L*W, for a realization of gaussian W of variance Sw 17 | 18 | % when flag='ExtendedNonGauss': 19 | % given Swand B(0), computes L=[I-B(0)]^(-1) 20 | % then generates U = L*W, for a realization of nongaussian W of variance Sw 21 | 22 | 23 | function U=InstModelfilter(N,C,flag,B0) 24 | 25 | error(nargchk(3,4,nargin));%min and max input arguments 26 | 27 | 28 | M=size(C,1); 29 | 30 | 31 | switch flag 32 | case {'StrictlyCausal'} % C is Su 33 | [L,Sw]=choldiag(C); 34 | W = randn(M,N); % W independent and gaussian 35 | for m=1:M % This normalizes W to have the appropriate variance (and zero mean) 36 | W(m,:)=sqrt(Sw(m,m))*(W(m,:)-mean(W(m,:)))/std(W(m,:)); 37 | end 38 | U=L*W; 39 | 40 | case {'ExtendedGauss'} % C is Sw 41 | invL=eye(M)-B0; 42 | if det(invL)==0, error('B0 is not invertible, ill-conditioned problem!'), end; 43 | L=inv(invL); 44 | W = randn(M,N); % W independent and gaussian 45 | for m=1:M % This normalizes W to have the appropriate variance (and zero mean) 46 | W(m,:)=sqrt(C(m,m))*(W(m,:)-mean(W(m,:)))/std(W(m,:)); 47 | end 48 | U=L*W; 49 | 50 | case {'ExtendedNonGauss'} % C is Sw 51 | invL=eye(M)-B0; 52 | if det(invL)==0, error('B0 is not invertible, ill-conditioned problem!'), end; 53 | L=inv(invL); 54 | %note: here we generate W independent but non-Gaussian 55 | % Nonlinearity exponent, selected to lie in [0.5, 0.8] or [1.2, 2.0]. (<1 gives subgaussian, >1 gives supergaussian) 56 | q = rand(M,1)*1.1+0.5; 57 | ind = find(q>0.8); 58 | q(ind) = q(ind)+0.4; 59 | % This generates the disturbance variables, which are mutually independent, and non-gaussian 60 | W = randn(M,N); 61 | W = sign(W).*(abs(W).^(q*ones(1,N))); 62 | % This normalizes the disturbance variables to have the appropriate scales 63 | W = W./( ( sqrt(mean((W').^2)') ./ sqrt(diag(C)) )*ones(1,N) ); 64 | U=L*W; 65 | 66 | end 67 | -------------------------------------------------------------------------------- /libs/Daniele_ARMA/MVARfilter.m: -------------------------------------------------------------------------------- 1 | %% FILTER A VECTOR NOISE WITH A SPECIFIED STRICTLY CAUSAL MVAR MODEL: Y(n)=A(1)Y(n-1)+...+A(p)Y(n-p)+U(n) 2 | 3 | %%% INPUT 4 | % A=[A(1)...A(p)]: M*pM matrix of the MVAR model coefficients (strictly causal model) 5 | % U: M*N matrix of innovations 6 | 7 | %%% OUTPUT 8 | % Y: M*N matrix of simulated time series 9 | 10 | function [Y]=MVARfilter(A,U) 11 | 12 | N=length(U); 13 | M=size(A,1); 14 | p=size(A,2)/M; 15 | 16 | % Y(n)=A(1)Y(n-1)+...+A(p)Y(n-p)+U(n) 17 | Y=zeros(M,N); 18 | for n=1:N 19 | for k=1:p 20 | if n-k<=0, break; end; % if n<=p, stop when k>=n 21 | Y(:,n)=Y(:,n) + ( A(:,(k-1)*M+(1:M)) * Y(:,n-k) ); 22 | end 23 | Y(:,n)=Y(:,n)+U(:,n); 24 | end 25 | -------------------------------------------------------------------------------- /libs/Daniele_ARMA/choldiag.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/libs/Daniele_ARMA/choldiag.m -------------------------------------------------------------------------------- /libs/Daniele_ARMA/idMVAR.m: -------------------------------------------------------------------------------- 1 | %% IDENTIFICATION OF STRICTLY CAUSAL MVAR MODEL: Y(n)=A(1)Y(n-1)+...+A(p)Y(n-p)+U(n) 2 | % makes use of autocovariance method (vector least squares) 3 | 4 | %%% input: 5 | % Y, M*N matrix of time series (each time series is in a row) 6 | % p, model order 7 | % Mode, determines estimation algorithm (0:builtin least squares, else other methods [see mvar.m from biosig package]) 8 | 9 | %%% output: 10 | % Am=[A(1)...A(p)], M*pM matrix of the estimated MVAR model coefficients 11 | % S, estimated M*M input covariance matrix 12 | % Yp, estimated time series 13 | % Up, estimated residuals 14 | % Z, observation matrix (often optional, useful e.g. for resampling) 15 | 16 | 17 | function [Am,S,Yp,Up,Z,Yb]=idMVAR(Y,p,Mode) 18 | 19 | % error(nargchk(1,3,nargin)); 20 | % if nargin < 3, Mode=0; end % default use least squares estimate 21 | % if nargin < 2, p=10; end % default model order 22 | 23 | [M,N]=size(Y); 24 | 25 | %% IDENTIFICATION 26 | Z=NaN*ones(p*M,N-p); % observation matrix 27 | for j=1:p 28 | for i=1:M 29 | Z((j-1)*M+i,1:N-p)=Y(i, p+1-j:N-j); 30 | end 31 | end 32 | 33 | if Mode==0 34 | Yb=NaN*ones(M,N-p); % Ybar 35 | for i=1:M 36 | Yb(i,1:N-p)=Y(i,p+1:N); 37 | end 38 | Am=Yb/Z; % least squares! 39 | % fprintf('using least squares\n'); 40 | else 41 | Am = mvar(Y', p, Mode); % estimates from biosig code 42 | % fprintf(['using biosig ' int2str(Mode) ' mode\n']); 43 | end 44 | 45 | Yp=Am*Z; 46 | Yp=[NaN*ones(M,p) Yp]; % Vector of predicted data 47 | 48 | Up=Y-Yp; Up=Up(:,p+1:N); % residuals of strictly causal model 49 | S=cov(Up'); 50 | 51 | 52 | -------------------------------------------------------------------------------- /libs/Daniele_ARMA/iss_AR.m: -------------------------------------------------------------------------------- 1 | function B = iss_AR(A,C,K,z) 2 | 3 | % Compute autoregressive representation (inverse transfer function) for a state 4 | % space model in innovations form (eq. 5 in the reference article). 5 | % 6 | % A,C,K - innovations form state space parameters 7 | % z - a vector of points on the unit circle in the complex plane 8 | % 9 | % B - inverse transfer function 10 | 11 | [m,m1] = size(A); assert(m1 == m); 12 | [n,m1] = size(C); assert(m1 == m); 13 | [m1,n1] = size(K); assert(n1 == n && m1 == m); 14 | z = z(:); 15 | 16 | h = length(z); 17 | In = eye(n); 18 | Im = eye(m); 19 | BB = A-K*C; 20 | B = zeros(n,n,h); 21 | for k = 1:h 22 | B(:,:,k) = In - C*((z(k)*Im-BB)\K); % eq. 5 23 | end 24 | -------------------------------------------------------------------------------- /libs/Daniele_ARMA/iss_MA.m: -------------------------------------------------------------------------------- 1 | function H = iss_MA(A,C,K,z) 2 | 3 | % Compute moving-average representation (transfer function) for a state space 4 | % model in innovations form (eq. 4 in the reference article). 5 | % 6 | % A,C,K - innovations form state space parameters 7 | % z - a vector of points on the unit circle in the complex plane 8 | % 9 | % H - transfer function 10 | 11 | [m,m1] = size(A); assert(m1 == m); 12 | [n,m1] = size(C); assert(m1 == m); 13 | [m1,n1] = size(K); assert(n1 == n && m1 == m); 14 | z = z(:); 15 | 16 | h = length(z); 17 | In = eye(n); 18 | Im = eye(m); 19 | H = zeros(n,n,h); 20 | for k = 1:h 21 | H(:,:,k) = In + C*((z(k)*Im-A)\K); % eq. 4 22 | end 23 | -------------------------------------------------------------------------------- /libs/Daniele_ARMA/parcovar.m: -------------------------------------------------------------------------------- 1 | function PV = parcovar(V,i,k) 2 | 3 | % Compute partial covariance PV = V(i,i) - V(i,k) * V(k,k)^{-1} * V(k,i); used 4 | % in spectral GC calculations (see eqs. 11 and 12-15 in the reference article). 5 | % 6 | % V - a (symmetric, positive-definite) covariance matrix 7 | % i,k - non-overlapping multi-indices (vectors of integers) 8 | % 9 | % PV - partial covariance matrix 10 | 11 | if isscalar(k) 12 | W = sqrt(V(k,k))\V(k,i); % for 1-dim target no matrix division required 13 | else 14 | opts.LT = true; % we can use the more efficient linsolve (rather than rdivide) 15 | W = linsolve(chol(V(k,k),'lower'),V(k,i),opts); % here, since we know the Cholesky factor is lower triangular 16 | end 17 | PV = V(i,i)-W'*W; 18 | -------------------------------------------------------------------------------- /libs/Daniele_ARMA/varma2iss.m: -------------------------------------------------------------------------------- 1 | %% VARMA with B0 term to (Innovations form) State Space parameters 2 | % computes innovations form parameters for a state space model from VARMA 3 | % parameters using Aoki's method - this version allows for zero-lag MA coefficients 4 | 5 | function [A,C,K,R,lambda0] = varma2iss(Am,Bm,V,B0) 6 | 7 | % INPUT: VARMA parameters Am, Bm, V=cov(U) 8 | % OUTPUT: innovations form SS parameters A, C, K, R 9 | 10 | %%%%% internal test 11 | %variables to be passed are Am, Bm, B0, V=Su 12 | % clear; close all; clc; 13 | % Am=[0.9 0 0 0.5; 0 0.6 0.2 0]; 14 | % Bm=[0.5 0; 0 0.5]; B0=Bm./5; 15 | % V=eye(2); 16 | % 17 | M = size(Am,1); %dimension of observed process 18 | p=floor(size(Am,2)/M); %number of AR lags 19 | q=floor(size(Bm,2)/M); %number of MA lags 20 | 21 | L=M*(p+q); % dimension of state process (SS order) 22 | 23 | C=[Am Bm]; 24 | R=B0*V*B0'; 25 | 26 | Ip=eye(M*p); 27 | Iq=eye(M*q); 28 | A11=[Am;Ip(1:end-M,:)]; 29 | 30 | if q==0 31 | A=A11; 32 | K=[eye(M); zeros(M*(p-1),M)]; 33 | else 34 | A12=[Bm;zeros(M*(p-1),M*q)]; 35 | A21=zeros(M*q,M*p); 36 | A22=[zeros(M,M*q); Iq(1:end-M,:)]; 37 | A=[A11 A12; A21 A22]; 38 | 39 | K=[eye(M); zeros(M*(p-1),M); inv(B0); zeros(M*(q-1),M)]; 40 | end 41 | 42 | 43 | % determine the variance of the process lambda0=E[Yn Yn'] 44 | O=dlyap(A,K*R*K'); 45 | lambda0=C*O*C'+R; 46 | 47 | end 48 | 49 | 50 | -------------------------------------------------------------------------------- /libs/brainstorm/tess_vertconn.m: -------------------------------------------------------------------------------- 1 | function VertConn = tess_vertconn(Vertices, Faces) 2 | % TESS_VERTCONN: Computes vertices connectivity. 3 | % 4 | % INPUT: 5 | % - Vertices : Mx3 double matrix 6 | % - Faces : Nx3 double matrix 7 | % OUTPUT: 8 | % - VertConn: Connectivity sparse matrix with dimension nVertices x nVertices. 9 | % It has 1 at (i,j) when vertices i and j are connected. 10 | 11 | % @============================================================================= 12 | % This function is part of the Brainstorm software: 13 | % https://neuroimage.usc.edu/brainstorm 14 | % 15 | % Copyright (c)2000-2019 University of Southern California & McGill University 16 | % This software is distributed under the terms of the GNU General Public License 17 | % as published by the Free Software Foundation. Further details on the GPLv3 18 | % license can be found at http://www.gnu.org/copyleft/gpl.html. 19 | % 20 | % FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE 21 | % UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY 22 | % WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF 23 | % MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY 24 | % LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE. 25 | % 26 | % For more information type "brainstorm license" at command prompt. 27 | % =============================================================================@ 28 | % 29 | % Authors: Anand Joshi, Dimitrios Pantazis, November 2007 30 | % Francois Tadel, 2008-2010 31 | 32 | % Check matrices orientation 33 | if (size(Vertices, 2) ~= 3) || (size(Faces, 2) ~= 3) 34 | error('Faces and Vertices must have 3 columns (X,Y,Z).'); 35 | end 36 | 37 | % Disable the stupid warnings in old Matlab versions 38 | warning('off', 'MATLAB:conversionToLogical'); 39 | 40 | % Build connectivity matric 41 | rowno = double([Faces(:,1); Faces(:,1); Faces(:,2); Faces(:,2); Faces(:,3); Faces(:,3)]); 42 | colno = double([Faces(:,2); Faces(:,3); Faces(:,1); Faces(:,3); Faces(:,1); Faces(:,2)]); 43 | data = ones(size(rowno)); 44 | n = size(Vertices,1); 45 | VertConn = logical(sparse(rowno, colno, data, n, n)); 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /libs/export_fig/.gitignore: -------------------------------------------------------------------------------- 1 | /.ignore 2 | *.txt 3 | *.asv 4 | *~ 5 | *.mex* 6 | -------------------------------------------------------------------------------- /libs/export_fig/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2014, Oliver J. Woodford 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, this 8 | list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright notice, 11 | this list of conditions and the following disclaimer in the documentation 12 | and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the {organization} nor the names of its 15 | contributors may be used to endorse or promote products derived from 16 | this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 22 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 23 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 24 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 25 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 26 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /libs/export_fig/append_pdfs.m: -------------------------------------------------------------------------------- 1 | %APPEND_PDFS Appends/concatenates multiple PDF files 2 | % 3 | % Example: 4 | % append_pdfs(output, input1, input2, ...) 5 | % append_pdfs(output, input_list{:}) 6 | % append_pdfs test.pdf temp1.pdf temp2.pdf 7 | % 8 | % This function appends multiple PDF files to an existing PDF file, or 9 | % concatenates them into a PDF file if the output file doesn't yet exist. 10 | % 11 | % This function requires that you have ghostscript installed on your 12 | % system. Ghostscript can be downloaded from: http://www.ghostscript.com 13 | % 14 | % IN: 15 | % output - string of output file name (including the extension, .pdf). 16 | % If it exists it is appended to; if not, it is created. 17 | % input1 - string of an input file name (including the extension, .pdf). 18 | % All input files are appended in order. 19 | % input_list - cell array list of input file name strings. All input 20 | % files are appended in order. 21 | 22 | % Copyright: Oliver Woodford, 2011 23 | 24 | % Thanks to Reinhard Knoll for pointing out that appending multiple pdfs in 25 | % one go is much faster than appending them one at a time. 26 | 27 | % Thanks to Michael Teo for reporting the issue of a too long command line. 28 | % Issue resolved on 5/5/2011, by passing gs a command file. 29 | 30 | % Thanks to Martin Wittmann for pointing out the quality issue when 31 | % appending multiple bitmaps. 32 | % Issue resolved (to best of my ability) 1/6/2011, using the prepress 33 | % setting 34 | 35 | function append_pdfs(varargin) 36 | % Are we appending or creating a new file 37 | append = exist(varargin{1}, 'file') == 2; 38 | if append 39 | output = [tempname '.pdf']; 40 | else 41 | output = varargin{1}; 42 | varargin = varargin(2:end); 43 | end 44 | % Create the command file 45 | cmdfile = [tempname '.txt']; 46 | fh = fopen(cmdfile, 'w'); 47 | fprintf(fh, '-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="%s" -f', output); 48 | fprintf(fh, ' "%s"', varargin{:}); 49 | fclose(fh); 50 | % Call ghostscript 51 | ghostscript(['@"' cmdfile '"']); 52 | % Delete the command file 53 | delete(cmdfile); 54 | % Rename the file if needed 55 | if append 56 | movefile(output, varargin{1}); 57 | end 58 | end 59 | -------------------------------------------------------------------------------- /libs/export_fig/copyfig.m: -------------------------------------------------------------------------------- 1 | %COPYFIG Create a copy of a figure, without changing the figure 2 | % 3 | % Examples: 4 | % fh_new = copyfig(fh_old) 5 | % 6 | % This function will create a copy of a figure, but not change the figure, 7 | % as copyobj sometimes does, e.g. by changing legends. 8 | % 9 | % IN: 10 | % fh_old - The handle of the figure to be copied. Default: gcf. 11 | % 12 | % OUT: 13 | % fh_new - The handle of the created figure. 14 | 15 | % Copyright (C) Oliver Woodford 2012 16 | 17 | function fh = copyfig(fh) 18 | % Set the default 19 | if nargin == 0 20 | fh = gcf; 21 | end 22 | % Is there a legend? 23 | if isempty(findall(fh, 'Type', 'axes', 'Tag', 'legend')) 24 | % Safe to copy using copyobj 25 | fh = copyobj(fh, 0); 26 | else 27 | % copyobj will change the figure, so save and then load it instead 28 | tmp_nam = [tempname '.fig']; 29 | hgsave(fh, tmp_nam); 30 | fh = hgload(tmp_nam); 31 | delete(tmp_nam); 32 | end 33 | end 34 | -------------------------------------------------------------------------------- /libs/export_fig/crop_borders.m: -------------------------------------------------------------------------------- 1 | %CROP_BORDERS Crop the borders of an image or stack of images 2 | % 3 | % [B, v] = crop_borders(A, bcol, [padding]) 4 | % 5 | %IN: 6 | % A - HxWxCxN stack of images. 7 | % bcol - Cx1 background colour vector. 8 | % padding - scalar indicating how many pixels padding to have. Default: 0. 9 | % 10 | %OUT: 11 | % B - JxKxCxN cropped stack of images. 12 | % v - 1x4 vector of start and end indices for first two dimensions, s.t. 13 | % B = A(v(1):v(2),v(3):v(4),:,:). 14 | 15 | function [A, v] = crop_borders(A, bcol, padding) 16 | if nargin < 3 17 | padding = 0; 18 | end 19 | [h, w, c, n] = size(A); 20 | if isscalar(bcol) 21 | bcol = bcol(ones(c, 1)); 22 | end 23 | bail = false; 24 | for l = 1:w 25 | for a = 1:c 26 | if ~all(col(A(:,l,a,:)) == bcol(a)) 27 | bail = true; 28 | break; 29 | end 30 | end 31 | if bail 32 | break; 33 | end 34 | end 35 | bcol = A(ceil(end/2),w,:,1); 36 | bail = false; 37 | for r = w:-1:l 38 | for a = 1:c 39 | if ~all(col(A(:,r,a,:)) == bcol(a)) 40 | bail = true; 41 | break; 42 | end 43 | end 44 | if bail 45 | break; 46 | end 47 | end 48 | bcol = A(1,ceil(end/2),:,1); 49 | bail = false; 50 | for t = 1:h 51 | for a = 1:c 52 | if ~all(col(A(t,:,a,:)) == bcol(a)) 53 | bail = true; 54 | break; 55 | end 56 | end 57 | if bail 58 | break; 59 | end 60 | end 61 | bcol = A(h,ceil(end/2),:,1); 62 | bail = false; 63 | for b = h:-1:t 64 | for a = 1:c 65 | if ~all(col(A(b,:,a,:)) == bcol(a)) 66 | bail = true; 67 | break; 68 | end 69 | end 70 | if bail 71 | break; 72 | end 73 | end 74 | % Crop the background, leaving one boundary pixel to avoid bleeding on resize 75 | v = [max(t-padding, 1) min(b+padding, h) max(l-padding, 1) min(r+padding, w)]; 76 | A = A(v(1):v(2),v(3):v(4),:,:); 77 | end 78 | 79 | function A = col(A) 80 | A = A(:); 81 | end 82 | -------------------------------------------------------------------------------- /libs/export_fig/pdf2eps.m: -------------------------------------------------------------------------------- 1 | %PDF2EPS Convert a pdf file to eps format using pdftops 2 | % 3 | % Examples: 4 | % pdf2eps source dest 5 | % 6 | % This function converts a pdf file to eps format. 7 | % 8 | % This function requires that you have pdftops, from the Xpdf suite of 9 | % functions, installed on your system. This can be downloaded from: 10 | % http://www.foolabs.com/xpdf 11 | % 12 | %IN: 13 | % source - filename of the source pdf file to convert. The filename is 14 | % assumed to already have the extension ".pdf". 15 | % dest - filename of the destination eps file. The filename is assumed to 16 | % already have the extension ".eps". 17 | 18 | % Copyright (C) Oliver Woodford 2009-2010 19 | 20 | % Thanks to Aldebaro Klautau for reporting a bug when saving to 21 | % non-existant directories. 22 | 23 | function pdf2eps(source, dest) 24 | % Construct the options string for pdftops 25 | options = ['-q -paper match -eps -level2 "' source '" "' dest '"']; 26 | % Convert to eps using pdftops 27 | [status, message] = pdftops(options); 28 | % Check for error 29 | if status 30 | % Report error 31 | if isempty(message) 32 | error('Unable to generate eps. Check destination directory is writable.'); 33 | else 34 | error(message); 35 | end 36 | end 37 | % Fix the DSC error created by pdftops 38 | fid = fopen(dest, 'r+'); 39 | if fid == -1 40 | % Cannot open the file 41 | return 42 | end 43 | fgetl(fid); % Get the first line 44 | str = fgetl(fid); % Get the second line 45 | if strcmp(str(1:min(13, end)), '% Produced by') 46 | fseek(fid, -numel(str)-1, 'cof'); 47 | fwrite(fid, '%'); % Turn ' ' into '%' 48 | end 49 | fclose(fid); 50 | end 51 | 52 | -------------------------------------------------------------------------------- /libs/export_fig/print2eps.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/libs/export_fig/print2eps.m -------------------------------------------------------------------------------- /libs/export_fig/read_write_entire_textfile.m: -------------------------------------------------------------------------------- 1 | %READ_WRITE_ENTIRE_TEXTFILE Read or write a whole text file to/from memory 2 | % 3 | % Read or write an entire text file to/from memory, without leaving the 4 | % file open if an error occurs. 5 | % 6 | % Reading: 7 | % fstrm = read_write_entire_textfile(fname) 8 | % Writing: 9 | % read_write_entire_textfile(fname, fstrm) 10 | % 11 | %IN: 12 | % fname - Pathname of text file to be read in. 13 | % fstrm - String to be written to the file, including carriage returns. 14 | % 15 | %OUT: 16 | % fstrm - String read from the file. If an fstrm input is given the 17 | % output is the same as that input. 18 | 19 | function fstrm = read_write_entire_textfile(fname, fstrm) 20 | modes = {'rt', 'wt'}; 21 | writing = nargin > 1; 22 | fh = fopen(fname, modes{1+writing}); 23 | if fh == -1 24 | error('Unable to open file %s.', fname); 25 | end 26 | try 27 | if writing 28 | fwrite(fh, fstrm, 'char*1'); 29 | else 30 | fstrm = fread(fh, '*char')'; 31 | end 32 | catch ex 33 | fclose(fh); 34 | rethrow(ex); 35 | end 36 | fclose(fh); 37 | end 38 | -------------------------------------------------------------------------------- /libs/export_fig/using_hg2.m: -------------------------------------------------------------------------------- 1 | %USING_HG2 Determine if the HG2 graphics pipeline is used 2 | % 3 | % tf = using_hg2(fig) 4 | % 5 | %IN: 6 | % fig - handle to the figure in question. 7 | % 8 | %OUT: 9 | % tf - boolean indicating whether the HG2 graphics pipeline is being used 10 | % (true) or not (false). 11 | 12 | function tf = using_hg2(fig) 13 | try 14 | tf = ~graphicsversion(fig, 'handlegraphics'); 15 | catch 16 | tf = false; 17 | end 18 | end 19 | -------------------------------------------------------------------------------- /libs/haufe/cm17.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/libs/haufe/cm17.mat -------------------------------------------------------------------------------- /libs/haufe/cs2coh.m: -------------------------------------------------------------------------------- 1 | function coh = cs2coh(cs) 2 | 3 | % (C) 2018 Stefan Haufe 4 | 5 | [nfreq nchan nchan njack] = size(cs); 6 | 7 | coh = cs; 8 | for ijack = 1:njack 9 | for ifreq = 1:nfreq 10 | coh(ifreq, :, :, ijack) = squeeze(cs(ifreq, :, :, ijack)) ... 11 | ./ sqrt(diag(squeeze(cs(ifreq, :, :, ijack)))*diag(squeeze(cs(ifreq, :, :, ijack)))'); 12 | end 13 | end 14 | 15 | 16 | -------------------------------------------------------------------------------- /libs/haufe/cs2psd.m: -------------------------------------------------------------------------------- 1 | function ps = cs2psd(cs) 2 | 3 | % (C) 2018 Stefan Haufe 4 | 5 | [nfreq nchan nchan njack] = size(cs); 6 | 7 | coh = cs; 8 | for ijack = 1:njack 9 | for ifreq = 1:nfreq 10 | ps(ifreq, :, ijack) = real(diag(squeeze(cs(ifreq, :, :, ijack)))); 11 | end 12 | end 13 | 14 | 15 | -------------------------------------------------------------------------------- /libs/haufe/est_DTF.m: -------------------------------------------------------------------------------- 1 | function [out] = DTF(A,Sigma,f_array,type) 2 | % DTF - Directed Transfer Function (formula (11) from Baccal? and Sameshima 3 | % 2001) 4 | % [Y] = DTF(A,C,TYPE) computes the DTF given the MVAR coefficients matrix 5 | % A and the residuals covariance matrix C. TYPE determines whether to 6 | % compute the standard DTF (TYPE='DTF') or the Directed DTF (TYPE = 'dDTF') 7 | % or the ffDTF (TYPE = 'ffDTF') 8 | % 9 | % See also: PDC 10 | 11 | % Author: G. Gomez-Herrero, german.gomezherrero@ieee.org 12 | % $Revision: 1.0 $Date: 22/06/2007 13 | 14 | if nargin < 4, type = 'dtf'; end 15 | 16 | 17 | [N,L] = size(A); 18 | p = L/N; 19 | A = reshape(A,[N,N,p]); 20 | densum = zeros(N,1); 21 | 22 | % initialize variables 23 | if strcmpi(type,'dtf'), 24 | dtf = zeros(N,N,length(f_array)); 25 | elseif sum(strcmpi(type,{'ffdtf','ddtf'})), 26 | ffdtf = zeros(N,N,length(f_array)); 27 | S = zeros(N,N,length(f_array)); 28 | else 29 | error('Wrong type'); 30 | end 31 | for i = 1:length(f_array) 32 | f = f_array(i); 33 | % build A(f) 34 | Af = zeros(N,N); 35 | for r = 1:p 36 | Af = Af + squeeze(A(:,:,r))*exp(-j*2*pi*f*r); 37 | end 38 | Hf = inv(eye(N,N)-Af); 39 | 40 | den = sum(((abs(Hf).^2)),2); 41 | if strcmpi(type,'dtf'), 42 | dtf(:,:,i) = Hf./repmat(sqrt(den),1,N); 43 | elseif strcmpi(type,'ffdtf') || strcmpi(type,'ddtf'), 44 | ffdtf(:,:,i) = Hf; 45 | densum = densum + den; 46 | end 47 | if strcmpi(type,'ddtf'), 48 | % build the power spectra matrix 49 | S(:,:,i) = Hf*Sigma*ctranspose(Hf); 50 | end 51 | end 52 | if strcmpi(type,'dtf'), 53 | out = dtf; 54 | elseif strcmpi(type,'ffdtf'), 55 | out = ffdtf./repmat(sqrt(densum),[1,N,length(f_array)]); 56 | elseif strcmpi(type,'ddtf'), 57 | ffdtf=ffdtf./repmat(sqrt(densum),[1,N,length(f_array)]); 58 | y = zeros(N,N,length(f_array)); 59 | for i = 1:N 60 | for l = 1:N 61 | for k = 1:length(f_array) 62 | if abs((minor(S(:,:,k),i,i)*minor(S(:,:,k),l,l))-(minor(S(:,:,k),i,l)^2)) < eps, 63 | y(i,l,k) = 1; 64 | else 65 | y(i,l,k) = (minor(S(:,:,k),i,l)^2)/(minor(S(:,:,k),i,i)*minor(S(:,:,k),l,l)); 66 | end 67 | y(i,l,k) = sqrt(y(i,l,k))*ffdtf(i,l,k); 68 | end 69 | end 70 | end 71 | out = y; 72 | end 73 | 74 | -------------------------------------------------------------------------------- /libs/haufe/est_PDC.m: -------------------------------------------------------------------------------- 1 | function [pdc] = PDC(A,f_array) 2 | % PDC - Partial Directed Coherence Factor (formula (18) from Baccal? and 3 | % Sameshima 2001) 4 | % [Y] = PDC(A,F) computes the PDC given the MVAR coefficients matrix A 5 | % 6 | % See also: DTF 7 | 8 | % Author: G. Gomez-Herrero, german.gomezherrero@ieee.org 9 | % $Revision: 1.0 $Date: 21/06/2007 10 | 11 | 12 | [N,L] = size(A); 13 | p = L/N; 14 | A = reshape(A,[N,N,p]); 15 | pdc = zeros(N,N,length(f_array)); 16 | for i = 1:length(f_array) 17 | f = f_array(i); 18 | % build A(f) 19 | Af = zeros(N,N); 20 | for r = 1:p 21 | Af = Af + squeeze(A(:,:,r))*exp(-j*2*pi*f*r); 22 | end 23 | Afh = (eye(N,N)-Af); 24 | den = zeros(1,N); 25 | for k = 1:N, 26 | den(1,k) = sqrt(ctranspose(Afh(:,k))*Afh(:,k)); 27 | end 28 | pdc(:,:,i) = Afh./repmat(den,N,1); 29 | end 30 | 31 | 32 | -------------------------------------------------------------------------------- /libs/haufe/mkfilt_eloreta_v2.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/libs/haufe/mkfilt_eloreta_v2.m -------------------------------------------------------------------------------- /libs/haufe/roi_mim2.m: -------------------------------------------------------------------------------- 1 | function [mic,mim]= roi_mim(Cohroi, subinds1, subinds2) 2 | 3 | regu = 0.000001; 4 | [~,~,nfreq] = size(Cohroi); 5 | 6 | ipcs = numel(subinds1); 7 | jpcs = numel(subinds2); 8 | 9 | for ifq = 1:nfreq 10 | cs_red=[]; 11 | cs_red1 = Cohroi(subinds1,subinds1,ifq); 12 | cs_red2 = Cohroi(subinds1,subinds2,ifq); 13 | cs_red3 = Cohroi(subinds2,subinds2,ifq); 14 | 15 | caainv=inv(real(cs_red1)+regu*eye(ipcs)*mean(diag(real(cs_red1)))); 16 | cab=imag(cs_red2); 17 | cbbinv=inv(real(cs_red3)+regu*eye(jpcs)*mean(diag(real(cs_red3)))); 18 | X=cab*cbbinv*cab'; 19 | % MIM Ewald Eq. 14 20 | mim(ifq)=(trace(caainv*X)); 21 | caainvsqrt=sqrtm(caainv); 22 | Y=caainvsqrt*X*caainvsqrt; %Eq. 23 23 | [~,s,~]=svd(Y); 24 | % MIC 25 | mic(ifq)=sqrt(s(1,1)); 26 | end 27 | 28 | -------------------------------------------------------------------------------- /libs/jurhar/bispectral_TD_est.m: -------------------------------------------------------------------------------- 1 | % Implements Bispectral Time Delay Estimations from Nikias Paper 2 | % (1988). Inputs are precomputed univariate bispectra. 3 | % 4 | % Inputs: 5 | % B_xxx, B_xyx, B_yyy - (n_freq x n_freq) univariate bispectra 6 | % method - determines the TDE method, must be between 1:4. 7 | % frqs_idx - (n_freq x 1) vector of frequency bins? 8 | % zeropad - zero-padding, used for frequency-domain bispectral estimates 9 | % 10 | % Outputs: 11 | % T - (1 x 2 * n_freq - 1) time-domain time delay estimate (bispectral hologram) 12 | % I - (n_freq x 2 * n_freq - 1) method-dependent coefficient to estimate bispectral delays 13 | 14 | function [T,I] = bispectral_TD_est(B_xxx, B_xyx, B_yyy, method, frqs_idx, zeropad) 15 | 16 | if nargin < 6 17 | zeropad = 1; 18 | end 19 | 20 | assert(ismember(method,1:4), 'Method must be [1;4].'); 21 | [m,n,boots] = size(B_xxx); 22 | 23 | switch method 24 | case 1 25 | phi = angle(B_xyx)-angle(B_xxx); 26 | I = exp(1i.*phi); 27 | case 2 28 | phi = angle(B_xyx)- 0.5 * (angle(B_xxx) + angle(B_yyy)); 29 | I = exp(1i.*phi); 30 | case 3 31 | I = B_xyx ./ B_xxx; 32 | case 4 33 | phi = angle(B_xyx)- 0.5 * (angle(B_xxx) + angle(B_yyy)); 34 | I = abs(B_xyx).* exp(1i.*phi) ./ sqrt(abs(B_xxx).*abs(B_yyy)); 35 | end 36 | 37 | % translate back to time domain. 38 | if nargin > 4 & ~isempty(frqs_idx) 39 | frqs_idx = [frqs_idx zeros(1,n-length(frqs_idx))]; 40 | I = frqs_idx.' * frqs_idx .* I; 41 | end 42 | 43 | % use for frequency-domain bispec estimates (not time domain) 44 | if zeropad 45 | I = [I zeros(m,n-1,boots)]; 46 | end 47 | 48 | T = sum(I,1); 49 | T = abs(fftshift(ifft(T),2)); 50 | 51 | end -------------------------------------------------------------------------------- /libs/jurhar/combine_sn.m: -------------------------------------------------------------------------------- 1 | function [X,Y] = combine_sn(rawX,noiseX,noiseY,delay,samplefreq,snr,theta,beta) 2 | % Combines signals and noise vectors with specified SNR (alpha), theta, 3 | % beta. 4 | 5 | [rawX,rawY] = mk_delay(delay,rawX); 6 | 7 | % zero-center signal and noise 8 | rawX = rawX-mean(rawX); 9 | rawY = rawY-mean(rawY); 10 | noiseX = noiseX-mean(noiseX); 11 | noiseY = noiseY-mean(noiseY); 12 | 13 | [~,~,~,pX] = obw(rawX,samplefreq); 14 | [~,~,~,pY] = obw(rawY,samplefreq); 15 | [~,~,~,pnoiseX] = obw(noiseX,samplefreq); 16 | [~,~,~,pnoiseY] = obw(noiseY,samplefreq); 17 | 18 | % Normalize signal and noise powers 19 | rawX = rawX / sqrt(pX); 20 | rawY = rawY /sqrt(pY); 21 | noiseX = noiseX / sqrt(pnoiseX); 22 | noiseY = noiseY /sqrt(pnoiseY); 23 | 24 | if nargin < 8 | isempty(beta) 25 | beta =1; 26 | end 27 | 28 | % Combine signal and noise with specified SNR 29 | X = snr * rawX + (1-snr) * (noiseX + theta(1) * noiseY); 30 | Y = snr * beta * rawY + (1-snr) * (noiseY + theta(2) * noiseX); 31 | end -------------------------------------------------------------------------------- /libs/jurhar/mk_delay.m: -------------------------------------------------------------------------------- 1 | function [X,Y] = mk_delay(delay,sig1,sig2) 2 | %% Syntax 3 | % [X,Y] = mk_delay(delay,sig1,sig2) 4 | %% Arguments 5 | % _input_ 6 | % delay integer, introduced delay 7 | % sig1 (1,N1) time series 1 8 | % sig2 (1,N2) time series 2 (optional) 9 | % _output_ 10 | % X (1,N1-delay), sig1 derived time series 11 | % Y (1,N2-delay), sig2 derived time series 12 | %% Description 13 | % Takes time series sig1 and sig2 and time shifts them by delay bins. delay 14 | % can take positive and negative values. If only sig1 is provided, then X,Y 15 | % are time-shifted instances of sig1. 16 | % 17 | % (C) Tin Jurhar, 2022 18 | 19 | if nargin < 3 20 | sig2 = sig1; 21 | end 22 | 23 | if delay < 0 24 | X = sig1(1:end-abs(delay)); 25 | Y = sig2(max(abs(delay))+1:end); 26 | else 27 | X = sig1(max(abs(delay))+1:end); 28 | Y = sig2(1:end-abs(delay)); 29 | end 30 | end 31 | 32 | -------------------------------------------------------------------------------- /libs/jurhar/mk_series.m: -------------------------------------------------------------------------------- 1 | % Function to generate simulated signals. Signals are generated either as 2 | % as samples from an exponential distribution, a Gaussian distribution or 3 | % from a Gaussian pink noise process. The option to model the signal as 4 | % spikes is disabled here. 5 | % 6 | % Inputs: 7 | % t - [integer] length of signal in datapoints 8 | % source_type - [String] underlying model of the signal: 'exp', 'G', 'pink', 'pinksq' 9 | % param - [integer] noise parameter 10 | % noise_mask - [boolean] if 1, additional Gaussian noise is added to the signal 11 | % 12 | % Output: 13 | % signal - (1 x t) simulated signal of length t 14 | 15 | function [signal] = mk_series(t,source_type,param,noise_mask) 16 | switch source_type 17 | case 'exp' 18 | signal= exprnd(param,1,t); 19 | case 'G' % Gaussian Noise 20 | signal = randn(1,t); 21 | case 'pink' 22 | signal = mkpinknoise(t,1,param).'; 23 | case 'pinksq' 24 | signal = mkpinknoise(t,1,param).'; 25 | signal = signal.^2; 26 | % case 'spiky' 27 | % load('spike_signal.mat'); 28 | % signal = spikes_signal(randperm(t)).'; 29 | end 30 | 31 | if nargin >3 & noise_mask % add Gaussian noise for numerical stability 32 | signal = signal./norm(signal,'fro'); 33 | noise= randn(1,t); 34 | noise = noise./ norm(noise,'fro'); 35 | 36 | signal = 0.95 * signal + 0.05 * noise; 37 | end 38 | end 39 | -------------------------------------------------------------------------------- /libs/jurhar/segment_data.m: -------------------------------------------------------------------------------- 1 | function Xs = segment_data(X,seglen,shift) 2 | 3 | %% Syntax 4 | % Xs = segment_data(X,seglen,shift) 5 | %% Arguments 6 | % _input_ 7 | % X (1,N) Time series of length N 8 | % seglen integer, desired segment length 9 | % shift integer, number of bins shifted for next segment,(optional) 10 | % _output_ 11 | % Xs (nseg,seglen) output matrix of segmeneted timeseries 12 | %% Description 13 | % Segments input time series Xs (row vector) into segments of length seglen 14 | % with desired shift. 15 | % 16 | % (C) Tin Jurhar, 2022 17 | if nargin < 3 | isempty(shift) 18 | shift = seglen; 19 | end 20 | 21 | assert(shift<=seglen,"shift must be geq seglen.") 22 | assert(length(size(X))==2 & (size(X,1)==1 | size(X,2)==1),"X must be 1-dimensional.") 23 | if size(X,2)==1 24 | X = X.'; 25 | end 26 | assert(seglen <= length(X),'seglen must be geq than the input vector.') 27 | 28 | [~,lenX] = size(X); 29 | Xs = []; 30 | i = 1; 31 | while i+seglen-1 <= lenX 32 | Xs = [Xs; X(i:i+seglen-1)]; 33 | i = i+shift; 34 | end 35 | end -------------------------------------------------------------------------------- /libs/mvgc_v1.0/C/genvar_mex.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "mex.h" 3 | 4 | /* WARNING: THIS FUNCTION PERFORMS NO ERROR CHECKING WHATSOEVER! Don't even 5 | * think of calling genvar_mex itself! It is designed to be called via the 6 | * genvar.m Matlab wrapper function (utils subfolder); all error checking - not 7 | * to mention documentation - happens there. To compile, see mvgc_makemex.m in 8 | * the utils subfolder */ 9 | 10 | void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) 11 | { 12 | double* a = mxGetPr(prhs[0]); 13 | double* z = mxGetPr(prhs[1]); 14 | 15 | const size_t n = mxGetM(prhs[1]); 16 | const size_t m = mxGetN(prhs[1]); 17 | const mwSize d = mxGetNumberOfDimensions(prhs[0]); 18 | const mwSize p = (d < 3 ? 1 : mxGetDimensions(prhs[0])[2]); 19 | const size_t nn = n*n; 20 | 21 | size_t t, k, i, j; 22 | double *xt, *xtk, *xti, *ak, *aki, w; 23 | 24 | double* x = mxGetPr(plhs[0] = mxCreateDoubleMatrix(n,m,mxREAL)); /* allocate output array x */ 25 | memcpy(x,z,n*m*sizeof(double)); /* copy input z to output x */ 26 | 27 | xt = x+n*p; 28 | for (t=p; t 6 | % 7 | %% Syntax 8 | % 9 | % [S,fres] = autocov_to_cpsd(G,fres) 10 | % 11 | %% Arguments 12 | % 13 | % See also . 14 | % 15 | % _input_ 16 | % 17 | % G autocovariance sequence 18 | % fres frequency resolution to calculate (default: automatic) 19 | % 20 | % _output_ 21 | % 22 | % S cross-power spectral density (cpsd) matrix 23 | % fres frequency resolution actually calculated 24 | % 25 | %% Description 26 | % 27 | % Calculates the cross-power spectral density (cpsd) |S| at frequency resolution 28 | % |fres| from the autocovariance sequence |G| defined as [[ii_acseq.png]]. This 29 | % is essentially a Fourier transform: 30 | % 31 | % <> 32 | % 33 | % implemented as a discrete Fast Fourier Transform (FFT). If a frequency resolution 34 | % |fres| is not supplied, then the default is to set it to the number of 35 | % autocovariance lags. The actual frequency resolution calculated is returned in 36 | % |fres|. Call |freqs = (fres,fs)|, where |fs| is the 37 | % sampling rate, to get a corresponding vector |freqs| of frequencies on 38 | % |[0,fs/2]|. 39 | % 40 | %% References 41 | % 42 | % [1] L. Barnett and A. K. Seth, 43 | % , _J. Neurosci. Methods_ 223, 2014 46 | % [ ]. 47 | % 48 | %% See also 49 | % 50 | % | 51 | % 52 | % 53 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 54 | % installation directory for licensing terms. 55 | % 56 | %% 57 | 58 | function [S,fres] = autocov_to_cpsd(G,fres) 59 | 60 | if nargin < 2 || isempty(fres), fres = size(G,3); end 61 | h = fres+1; 62 | 63 | G0 = G(:,:,1); 64 | 65 | S = bfft(G,2*fres); % over [0,2*pi) 66 | S = S(:,:,1:h); % over [0,pi] 67 | S = S + conj(permute(S,[2 1 3])) - G0(:,:,ones(1,1,h)); % last term is repmat(G0,[1 1 h]) 68 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/core/cpsd_to_autocov.m: -------------------------------------------------------------------------------- 1 | %% cpsd_to_autocov 2 | % 3 | % Calculate autocovariance sequence from cross-power spectral density 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % [G,q] = cpsd_to_autocov(S,q) 10 | % 11 | %% Arguments 12 | % 13 | % See also . 14 | % 15 | % _input_ 16 | % 17 | % S cross-power spectral density (cpsd) matrix 18 | % q number of autocovariance lags to calculate (default: automatic) 19 | % 20 | % _output_ 21 | % 22 | % G autocovariance sequence 23 | % q number of autocovariance lags actually calculated 24 | % 25 | %% Description 26 | % 27 | % Calculates the autocovariance sequence |G| defined as [[ii_acseq.png]] to |q| 28 | % lags from the cross-power spectral density (cpsd) |S|. This is essentially an 29 | % inverse Fourier transform 30 | % 31 | % <> 32 | % 33 | % implemented as an (discrete) inverse fast Fourier transform. If a number of 34 | % lags |q| is not supplied, then the default is to set it to the frequency 35 | % resolution of the cpsd. The actual number of lags calculated is returned in 36 | % |q|. 37 | % 38 | %% References 39 | % 40 | % [1] L. Barnett and A. K. Seth, 41 | % , _J. Neurosci. Methods_ 223, 2014 44 | % [ ]. 45 | % 46 | %% See also 47 | % 48 | % 49 | % 50 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 51 | % installation directory for licensing terms. 52 | % 53 | %% 54 | 55 | function [G,q] = cpsd_to_autocov(S,q) 56 | 57 | [n,~,h] = size(S); 58 | fres = h-1; 59 | if nargin < 2 || isempty(q), q = fres-1; end 60 | assert(q < 2*fres,'too many lags'); 61 | q1 = q+1; 62 | 63 | %G = bifft(cat(3,flipdim(permute(S(:,:,2:fres+1),[2 1 3]),3),S(:,:,1:fres)),2*fres); % inverse transform of "circular shifted" spectral density 64 | G = bifft(cat(3,flipdim(conj(S(:,:,2:fres+1)),3),S(:,:,1:fres)),2*fres); % inverse transform of "circular shifted" spectral density 65 | 66 | r = ones(1,ceil(q1/2)); 67 | sgn = [r; -r]; 68 | sgn = sgn(1:q1); % sgn = [1 -1 1 -1 ...] 69 | 70 | G = real(reshape(sgn(ones(1,n*n),:).*reshape(G(:,:,1:q1),n*n,q1),n,n,q1)); 71 | 72 | % note 1: G truncated to q1 lags 73 | % note 2: G should be real, but ... 74 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/core/cpsd_xform.m: -------------------------------------------------------------------------------- 1 | %% cpsd_xform 2 | % 3 | % Transform cross-power spectral density for reduced regression 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % SR = cpsd_xform(S,AR,SIGR) 10 | % 11 | %% Arguments 12 | % 13 | % See also . 14 | % 15 | % _input_ 16 | % 17 | % S cross-power spectral density (cpsd) matrix 18 | % AR VAR coefficients matrix for reduced regression 19 | % SIGR residuals covariance matrix for reduced regression 20 | % 21 | % _output_ 22 | % 23 | % SR transformed cpsd 24 | % 25 | %% Description 26 | % 27 | % Returns the cpsd |SR| for a new variable defined as the residuals of a reduced 28 | % regression, for a VAR with cpsd |S|. |AR| and |SIGR| are the coefficients 29 | % matrices and residuals covariance matrix respectively of the reduced 30 | % regression, which is is assumed to correspond to the first |size(AR,1)| 31 | % indices of |G|. 32 | % 33 | %% References 34 | % 35 | % [1] L. Barnett and A. K. Seth, 36 | % , _J. Neurosci. Methods_ 223, 2014 39 | % [ ]. 40 | % 41 | %% See also 42 | % 43 | % 44 | % 45 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 46 | % installation directory for licensing terms. 47 | % 48 | %% 49 | 50 | function S = cpsd_xform(S,AR,SIGR) 51 | 52 | [n,~,h] = size(S); 53 | fres = h-1; 54 | 55 | [nx,nx1,~] = size(AR); 56 | assert(nx1 == nx,'reduced VAR coefficients matrix has bad shape'); 57 | assert(nx <= n,'reduced VAR coefficients matrix appears to be for more variables than autocovariance sequence'); 58 | 59 | [n1,n2] = size(SIGR); 60 | assert(n1 == n2,'reduced VAR residuals covariance matrix not square'); 61 | assert(n1 == nx,'reduced VAR residuals covariance matrix doesn''t match reduced VAR coefficients matrix'); 62 | 63 | x = 1:nx; 64 | y = nx+1:n; 65 | 66 | AF = bfft(cat(3,eye(nx),-AR),2*fres); % over [0,2*pi) 67 | 68 | for k = 1:h 69 | S(x,x,k) = SIGR; % flat spectrum, since residuals serially uncorrelated 70 | S(x,y,k) = AF(:,:,k)*S(x,y,k); 71 | S(y,x,k) = S(y,x,k)*AF(:,:,k)'; 72 | end 73 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/core/var_to_cpsd.m: -------------------------------------------------------------------------------- 1 | %% var_to_cpsd 2 | % 3 | % Calculate cross-power spectral density and transfer function from VAR 4 | % parameters 5 | % 6 | % 7 | % 8 | %% Syntax 9 | % 10 | % [S,H] = var_to_cpsd(A,SIG,fres) 11 | % 12 | %% Arguments 13 | % 14 | % See also . 15 | % 16 | % _input_ 17 | % 18 | % A VAR coefficients matrix 19 | % SIG residuals covariance matrix 20 | % fres frequency resolution 21 | % 22 | % _output_ 23 | % 24 | % S cross-power spectral density (cpsd) matrix 25 | % H VAR transfer function matrix 26 | % 27 | %% Description 28 | % 29 | % Calculates cross-spectral density |S| and transfer function |H| of VAR process 30 | % with coefficients matrix |A| and residuals covariance matrix |SIG|. |fres| 31 | % specifies the frequency resolution. Call |freqs = (fres,fs)|, where |fs| is the sampling rate, to get a corresponding 33 | % vector |freqs| of frequencies on |[0,fs/2]|. 34 | % 35 | %% References 36 | % 37 | % [1] L. Barnett and A. K. Seth, 38 | % , _J. Neurosci. Methods_ 223, 2014 41 | % [ ]. 42 | % 43 | %% See also 44 | % 45 | % | 46 | % 47 | % 48 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 49 | % installation directory for licensing terms. 50 | % 51 | %% 52 | 53 | function [S,H] = var_to_cpsd(A,SIG,fres) 54 | 55 | n = size(A,1); 56 | h = fres+1; 57 | H = var2trfun(A,fres); 58 | S = zeros(n,n,h); 59 | for k = 1:h 60 | S(:,:,k) = H(:,:,k)*SIG*H(:,:,k)'; 61 | end 62 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/demo/var5_test.m: -------------------------------------------------------------------------------- 1 | %% var5_test 2 | % 3 | % Create VAR coefficients for 5-node test network 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % A = var5_test 10 | % 11 | %% Arguments 12 | % 13 | % See also . 14 | % 15 | % _output_ 16 | % 17 | % A VAR coefficients matrix for 5-node test network 18 | % 19 | %% Description 20 | % 21 | % Returns coefficients |A| for a VAR(3) based on a 5-node test network with causal 22 | % architecture: 23 | % 24 | % <> 25 | % 26 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 27 | % installation directory for licensing terms. 28 | % 29 | %% 30 | 31 | function A = var5_test 32 | 33 | n = 5; 34 | p = 3; 35 | 36 | r = sqrt(2); 37 | 38 | A = zeros(n,n,p); 39 | 40 | A(1,1,1) = 0.95*r; 41 | A(1,1,2) = -0.9025; 42 | 43 | A(2,1,2) = 0.5; 44 | A(3,1,3) = -0.4; 45 | 46 | A(4,1,2) = -0.5; 47 | A(4,4,1) = 0.25*r; 48 | A(4,5,1) = 0.25*r; 49 | 50 | A(5,4,1) = -0.25*r; 51 | A(5,5,1) = 0.25*r; 52 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/docs/html/eq_ac2cpsd.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/libs/mvgc_v1.0/docs/html/eq_ac2cpsd.png -------------------------------------------------------------------------------- /libs/mvgc_v1.0/docs/html/eq_aitr.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/libs/mvgc_v1.0/docs/html/eq_aitr.png -------------------------------------------------------------------------------- /libs/mvgc_v1.0/docs/html/eq_cpsd2ac.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/libs/mvgc_v1.0/docs/html/eq_cpsd2ac.png -------------------------------------------------------------------------------- /libs/mvgc_v1.0/docs/html/eq_dlyap.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/libs/mvgc_v1.0/docs/html/eq_dlyap.png -------------------------------------------------------------------------------- /libs/mvgc_v1.0/docs/html/eq_mvgc.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/libs/mvgc_v1.0/docs/html/eq_mvgc.png -------------------------------------------------------------------------------- /libs/mvgc_v1.0/docs/html/eq_mvgc_pwc.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/libs/mvgc_v1.0/docs/html/eq_mvgc_pwc.png -------------------------------------------------------------------------------- /libs/mvgc_v1.0/docs/html/eq_smvgc.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/libs/mvgc_v1.0/docs/html/eq_smvgc.png -------------------------------------------------------------------------------- /libs/mvgc_v1.0/docs/html/eq_smvgc_int.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/libs/mvgc_v1.0/docs/html/eq_smvgc_int.png -------------------------------------------------------------------------------- /libs/mvgc_v1.0/docs/html/eq_smvgc_pwc.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/libs/mvgc_v1.0/docs/html/eq_smvgc_pwc.png -------------------------------------------------------------------------------- /libs/mvgc_v1.0/docs/html/eq_smvgc_uncond.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/libs/mvgc_v1.0/docs/html/eq_smvgc_uncond.png -------------------------------------------------------------------------------- /libs/mvgc_v1.0/docs/html/eq_var.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/libs/mvgc_v1.0/docs/html/eq_var.png -------------------------------------------------------------------------------- /libs/mvgc_v1.0/docs/html/eq_varnn.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/libs/mvgc_v1.0/docs/html/eq_varnn.png -------------------------------------------------------------------------------- /libs/mvgc_v1.0/docs/html/eq_vma.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/libs/mvgc_v1.0/docs/html/eq_vma.png -------------------------------------------------------------------------------- /libs/mvgc_v1.0/docs/html/eq_yweqs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/libs/mvgc_v1.0/docs/html/eq_yweqs.png -------------------------------------------------------------------------------- /libs/mvgc_v1.0/docs/html/ii_Sigma.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/libs/mvgc_v1.0/docs/html/ii_Sigma.png -------------------------------------------------------------------------------- /libs/mvgc_v1.0/docs/html/ii_acseq.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/libs/mvgc_v1.0/docs/html/ii_acseq.png -------------------------------------------------------------------------------- /libs/mvgc_v1.0/docs/html/ii_dlyapre.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/libs/mvgc_v1.0/docs/html/ii_dlyapre.png -------------------------------------------------------------------------------- /libs/mvgc_v1.0/docs/html/ii_inej.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/libs/mvgc_v1.0/docs/html/ii_inej.png -------------------------------------------------------------------------------- /libs/mvgc_v1.0/docs/html/ii_nu.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/libs/mvgc_v1.0/docs/html/ii_nu.png -------------------------------------------------------------------------------- /libs/mvgc_v1.0/docs/html/mvgcschema.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/libs/mvgc_v1.0/docs/html/mvgcschema.png -------------------------------------------------------------------------------- /libs/mvgc_v1.0/docs/html/var5test.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/libs/mvgc_v1.0/docs/html/var5test.png -------------------------------------------------------------------------------- /libs/mvgc_v1.0/docs/html/var9test.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/libs/mvgc_v1.0/docs/html/var9test.png -------------------------------------------------------------------------------- /libs/mvgc_v1.0/docs/info.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 2011a 4 | MVGC Multivariate Granger Causality 5 | toolbox 6 | $toolbox/matlab/icons/matlabicon.gif 7 | html 8 | 9 | 10 | 11 | web(fullfile('.','docs','html','mvgchelp.html'),'-helpbrowser') 12 | $toolbox/matlab/icons/book_mat.gif 13 | 14 | 15 | 16 | web http://www.sussex.ac.uk/sackler/mvgc; 17 | $docroot/techdoc/matlab_env/examples/webicon.gif 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/docs/mvgc_preprint.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/libs/mvgc_v1.0/docs/mvgc_preprint.pdf -------------------------------------------------------------------------------- /libs/mvgc_v1.0/docs/mvgcrelnotes.m: -------------------------------------------------------------------------------- 1 | %% MVGC Multivariate Granger Causality Toolbox - Release Notes 2 | % 3 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 4 | % installation directory for licensing terms. 5 | % 6 | %% v1.0 2012-10-09 7 | % 8 | % * Initial release 9 | % 10 | %% 11 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/experimental/tsdata_to_autocov_debias.m: -------------------------------------------------------------------------------- 1 | %% tsdata_to_autocov_debias (EXPERIMENTAL) 2 | % 3 | % Calculate sample autocovariance sequence from time series data with debias 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % G = tsdata_to_autocov_debias(X,q) 10 | % 11 | %% Arguments 12 | % 13 | % See also . 14 | % 15 | % _input_ 16 | % 17 | % X multi-trial time series data 18 | % q number of lags 19 | % 20 | % _output_ 21 | % 22 | % G sample autocovariance sequence 23 | % 24 | %% Description 25 | % 26 | % Returns |q|-lag sample autocovariance sequence |G| defined as 27 | % [[ii_acseq.png]] for the (presumed stationary) multivariate process |X|. 28 | % |X| may contain single- or multi-trial time series data. See 29 | % for more details. 30 | % 31 | % This (experimental) algorithm [2] attempts to reduce bias due to mean estimation 32 | % for small samples. 33 | % 34 | %% References 35 | % 36 | % [1] L. Barnett and A. K. Seth, 37 | % , _J. Neurosci. Methods_ 223, 2014 40 | % [ ]. 41 | % 42 | % [2] Y. Shkolnisky, F. J. Sigworth and A. Singer, 43 | % , 2008. 45 | % 46 | %% See also 47 | % 48 | % | 49 | % | 50 | % | 51 | % 52 | % 53 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 54 | % installation directory for licensing terms. 55 | % 56 | %% 57 | 58 | function G = tsdata_to_autocov_debias(X,q) 59 | 60 | [n,m,N] = size(X); 61 | 62 | assert(q < m-1,'too many lags'); 63 | 64 | if N > 1 % multi-trial 65 | 66 | Nm = N*m; 67 | M = sum(X(:,:),2); 68 | B = (M*M'-X(:,:)*X(:,:)')/(Nm*(Nm-1)); % debiasing term 69 | G = zeros(n,n,q+1); 70 | for k=0:q 71 | Nmk = Nm-N*k; 72 | for r = 1:N 73 | G(:,:,k+1) = G(:,:,k+1) + (X(:,k+1:m,r)*X(:,1:m-k,r)')/Nmk; 74 | end 75 | G(:,:,k+1) = G(:,:,k+1)-B; 76 | end 77 | 78 | else 79 | 80 | M = sum(X,2); 81 | B = (M*M'-X*X')/(m*(m-1)); % debiasing term 82 | G = zeros(n,n,q+1); 83 | for k=0:q 84 | G(:,:,k+1) = (X(:,k+1:m)*X(:,1:m-k)')/(m-k)-B; 85 | end 86 | 87 | end 88 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/license.txt: -------------------------------------------------------------------------------- 1 | MVGC Multivariate Granger Causality Toolbox License Notice 2 | ---------------------------------------------------------- 3 | 4 | All files in the MVGC distribution are part of the MVGC Toolbox 5 | and are Copyright (C) Lionel Barnett and Anil K. Seth, 2012. 6 | 7 | The MVGC Toolbox is free software: you can redistribute it 8 | and/or modify it under the terms of the GNU General Public 9 | License as published by the Free Software Foundation, either 10 | version 3 of the License, or (at your option) any later version. 11 | 12 | The MVGC Toolbox is distributed in the hope that it will be 13 | useful, but WITHOUT ANY WARRANTY; without even the implied 14 | warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 15 | See the GNU General Public License for more details. 16 | 17 | You should receive a copy of the GNU General Public License along 18 | with the MVGC Toolbox distribution (see file GPL_v3.txt in the 19 | installation directory); else see http://www.gnu.org/licenses/. 20 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/mex/genvar_mex.mexa64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/libs/mvgc_v1.0/mex/genvar_mex.mexa64 -------------------------------------------------------------------------------- /libs/mvgc_v1.0/mex/genvar_mex.mexmaci64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/libs/mvgc_v1.0/mex/genvar_mex.mexmaci64 -------------------------------------------------------------------------------- /libs/mvgc_v1.0/mex/genvar_mex.mexw64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/libs/mvgc_v1.0/mex/genvar_mex.mexw64 -------------------------------------------------------------------------------- /libs/mvgc_v1.0/stats/consistency.m: -------------------------------------------------------------------------------- 1 | %% consistency 2 | % 3 | % Calculate VAR model consistency 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % cons = consistency(X,E) 10 | % 11 | %% Arguments 12 | % 13 | % See also . 14 | % 15 | % _input_ 16 | % 17 | % X multi-trial time series data 18 | % E residuals time series 19 | % 20 | % _output_ 21 | % 22 | % cons consistency statistic 23 | % 24 | %% Description 25 | % 26 | % Check what proportion of the correlation structure in data is accounted 27 | % for by a VAR model. The data |X| and residuals |E| may be single- or 28 | % multi-trial time series. A value of |cons > 0.8| might be considered 29 | % to indicate reasonable consistency. 30 | % 31 | %% References 32 | % 33 | % [1] M. Ding, S. L. Bressler, W. Yang and H. Liang, "Short-window spectral 34 | % analysis of cortical event-related potentials by adaptive multivariate 35 | % autoregressive modeling: data preprocessing, model validation, and 36 | % variability assessment", _Biol. Cybern._, 83, 2000. 37 | % 38 | % [2] A. K. Seth, "A MATLAB toolbox for Granger causal connectivity 39 | % analysis", _Journal of Neuroscience Methods_ 186, 2010. 40 | % 41 | %% See also 42 | % 43 | % | 44 | % 45 | % 46 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 47 | % installation directory for licensing terms. 48 | % 49 | %% 50 | 51 | function cons = consistency(X,E) 52 | 53 | [n,m,N] = size(X); 54 | p = m-size(E,2); % number of lags in model 55 | assert(m >= n,'too few observations'); 56 | assert(size(E,1) == n && size(E,3) == N,'residuals don''t match data'); 57 | assert(p > 0,'bad number of lags'); 58 | 59 | X = demean(X); 60 | 61 | if N > 1 % multi-trial 62 | X = X(:,p+1:m,:); 63 | X = X(:,:); % stack data 64 | E = E(:,:); % stack residuals 65 | s = N*(m-p); % sample size (number of observations) 66 | else 67 | X = X(:,p+1:m); 68 | s = m-p; % sample size (number of observations) 69 | end 70 | 71 | Y = X - E; % prediction 72 | 73 | Rr = (X*X')/(s-1); % covariance estimate 74 | Rs = (Y*Y')/(s-1); % covariance estimate 75 | 76 | cons = 1 - norm(Rs-Rr)/norm(Rr); % compare matrix norms 77 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/stats/demean.m: -------------------------------------------------------------------------------- 1 | %% demean 2 | % 3 | % Temporal demean of time series data 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % Y = demean(X,normalise) 10 | % 11 | %% Arguments 12 | % 13 | % See also . 14 | % 15 | % _input_ 16 | % 17 | % X multi-trial time series data 18 | % normalise normalise (temporal) variance of each variable to 1 (default: false) 19 | % 20 | % _output_ 21 | % 22 | % Y demeaned time series data 23 | % 24 | %% Description 25 | % 26 | % Temporally demean time series data |X|, which may be single- or 27 | % multi-trial. If the |normalise| flag is set, data is normalised so that 28 | % the (temporal) variance of each series is 1. 29 | % 30 | % *_Note:_* For multi-trial data we don't demean on a "per-trial" basis, 31 | % since this really doesn't make sense... trials in multi-trial data are 32 | % assumed to be multiple realisations of the same process. In particular, 33 | % demeaning trials separately can introduce large bias in VAR model 34 | % estimation (_cf._ ). The mean 35 | % calculated here is thus the temporal mean of ensemble means. If you feel 36 | % you absolutely have to demean per-trial, then call this function for each 37 | % trial series |X(:,:,r)| _and then_ call it with |X|. 38 | % 39 | %% See also 40 | % 41 | % 42 | % 43 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 44 | % installation directory for licensing terms. 45 | % 46 | %% 47 | 48 | function Y = demean(X,normalise) 49 | 50 | if nargin < 2 || isempty(normalise), normalise = false; end 51 | 52 | [n,m,N] = size(X); 53 | 54 | U = ones(1,N*m); 55 | Y = X(:,:); 56 | Y = Y-mean(Y,2)*U; 57 | if normalise 58 | Y = Y./(std(Y,[],2)*U); 59 | end 60 | Y = reshape(Y,n,m,N); 61 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/stats/empirical_confint.m: -------------------------------------------------------------------------------- 1 | %% empirical_confint 2 | % 3 | % Confidence intervals for sample statistics based on estimated empirical null distribution 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % [xup,xlo] = empirical_confint(alpha,X,ptails,ksmooth) 10 | % 11 | %% Arguments 12 | % 13 | % See also . 14 | % 15 | % _input_ 16 | % 17 | % alpha significance level (scalar) 18 | % X matrix of sample statistics 19 | % ptails Pareto tails lower and upper probabilities (default: no Pareto tails) 20 | % ksmooth use kernel smoothing to estimate cdf (default: no smoothing) 21 | % 22 | % _output_ 23 | % 24 | % xup matrix of upper confidence bounds 25 | % xlo matrix of lower confidence bounds 26 | % 27 | %% Description 28 | % 29 | % Return upper and lower confidence bounds |[xup,xlo]| at significance level 30 | % |alpha| based on the empirical distributions in |X| (derived e.g. from a 31 | % bootstrap). The first dimension of |X| must index samples. |NaN| s are ignored. 32 | % See for details of other parameters. 33 | % 34 | %% See also 35 | % 36 | % 37 | % | 38 | % | 39 | % | 40 | % 41 | % 42 | % 43 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 44 | % installation directory for licensing terms. 45 | % 46 | %% 47 | 48 | function [xup,xlo] = empirical_confint(alpha,X,ptails,ksmooth) 49 | 50 | if nargin < 3, ptails = []; end % force empirical_cdfi default 51 | if nargin < 4, ksmooth = []; end % force empirical_cdfi default 52 | 53 | assert(isscalar(alpha),'alpha must be a scalar'); 54 | 55 | nn = squeeze(~any(isnan(X),1)); % indices of non-NaNs (logical array) 56 | s = size(nn); 57 | n = nnz(nn); 58 | xup = NaN(s); % upper bounds matrix 59 | xlo = NaN(s); % lower bounds matrix 60 | X = X(:,nn); % vectorise non-NaN X values 61 | 62 | xu = zeros(n,1); 63 | xl = zeros(n,1); 64 | for i = 1:n 65 | xu(i) = empirical_cdfi(1-alpha,X(:,i),ptails,ksmooth); 66 | xl(i) = empirical_cdfi(alpha, X(:,i),ptails,ksmooth); 67 | end 68 | xup(nn) = xu; % upper bounds matrix with NaNs in the right place 69 | xlo(nn) = xl; % lower bounds matrix with NaNs in the right place 70 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/stats/empirical_cval.m: -------------------------------------------------------------------------------- 1 | %% empirical_cval 2 | % 3 | % Critical values for sample statistics based on estimated empirical null distribution 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % x = empirical_cval(alpha,XNULL,ptails,ksmooth) 10 | % 11 | %% Arguments 12 | % 13 | % See also . 14 | % 15 | % _input_ 16 | % 17 | % alpha vector of significance levels 18 | % XNULL matrix of null sample statistics 19 | % ptails Pareto tails lower and upper probabilities (default: no Pareto tails) 20 | % ksmooth use kernel smoothing to estimate cdf (default: no smoothing) 21 | % 22 | % _output_ 23 | % 24 | % x matrix of critical values 25 | % 26 | %% Description 27 | % 28 | % Return critical values |x| at significance levels in |alpha| based on 29 | % empirical null distributions in |XNULL| (derived e.g. from a permutation 30 | % test). The first dimension of |XNULL| must index samples. The leading indices 31 | % of |x| index null distributions, the last significance levels. |NaN| s are 32 | % ignored. See for details of other 33 | % parameters. 34 | % 35 | %% See also 36 | % 37 | % | 38 | % | 39 | % | 40 | % 41 | % 42 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 43 | % installation directory for licensing terms. 44 | % 45 | %% 46 | 47 | function x = empirical_cval(alpha,XNULL,ptails,ksmooth) 48 | 49 | if nargin < 3, ptails = []; end % force empirical_cdfi default 50 | if nargin < 4, ksmooth = []; end % force empirical_cdfi default 51 | 52 | assert(~isscalar(XNULL),'null distributions must be a vector or matrix'); 53 | assert(isvector(alpha),'significance levels must be a scalar or vector'); 54 | 55 | s = size(XNULL); 56 | sx = s(2:end); 57 | n = prod(sx); 58 | XNULL = reshape(XNULL,s(1),n); 59 | r = length(alpha); 60 | x = NaN(n,r); 61 | for i = 1:n 62 | if ~any(isnan(XNULL(:,i))); 63 | x(i,:) = empirical_cdfi(1-alpha,XNULL(:,i),ptails,ksmooth); 64 | end 65 | end 66 | x = reshape(x,[sx r]); 67 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/stats/infocrit.m: -------------------------------------------------------------------------------- 1 | %% infocrit 2 | % 3 | % Calculate Akaike and Bayesian information criteria 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % [aic,bic] = infocrit(L,k,m) 10 | % 11 | %% Arguments 12 | % 13 | % See also . 14 | % 15 | % _input_ 16 | % 17 | % L maximum log-likelihood 18 | % k number of free parameters 19 | % m number of observations 20 | % 21 | % _output_ 22 | % 23 | % aic AIC value 24 | % bic BIC value 25 | % 26 | %% Description 27 | % 28 | % Calculates the Akaike and Bayesian information criteria from the 29 | % maximised log-likelihood of a model [1]. For the Akaike information 30 | % criterion, the finite sample bias-corrected form ("AICc") of Hurvich and 31 | % Tsai [2] is calculated. 32 | % 33 | %% References 34 | % 35 | % [1] K. P. Burnham and D. R. Anderson, "Model Selection and Multimodel 36 | % Inference: A Practical Information-Theoretic Approach", _2nd ed._, 37 | % Springer-Verlag, 2002. 38 | % 39 | % [2] C. M. Hurvich and C.-L. Tsai, "Regression and time series model selection 40 | % in small samples", _Biometrika_, 76, 1989. 41 | % 42 | %% See also 43 | % 44 | % 45 | % 46 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 47 | % installation directory for licensing terms. 48 | % 49 | %% 50 | 51 | function [aic,bic] = infocrit(L,k,m) 52 | 53 | if m-k-1 <= 0 54 | aic = NaN; 55 | else 56 | aic = -2*L + 2*k*(m/(m-k-1)); % Note AIC without correction = -2*L + 2*k 57 | end 58 | bic = -2*L + k*log(m); 59 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/stats/mvgc_confint.m: -------------------------------------------------------------------------------- 1 | %% mvgc_confint 2 | % 3 | % Confidence intervals for sample MVGC based on theoretical asymptotic distribution 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % [xup,xlo] = mvgc_confint(alpha,x,p,m,N,nx,ny,nz,tstat) 10 | % 11 | %% Arguments 12 | % 13 | % See also . 14 | % 15 | % _input_ 16 | % 17 | % alpha significance level (scalar) 18 | % x matrix of MVGC values 19 | % p VAR model order 20 | % m number of observations per trial 21 | % N number of trials 22 | % nx number of target ("to") variables 23 | % ny number of source ("from") variables 24 | % nz number of conditioning variables (default: 0) 25 | % tstat statistic: 'F' or 'chi2' (default: 'F' if nx == 1, else 'chi2') 26 | % 27 | % _output_ 28 | % 29 | % xup matrix of upper confidence bounds 30 | % xlo matrix of lower confidence bounds 31 | % 32 | %% Description 33 | % 34 | % Return upper and lower confidence bounds |[xup,xlo]| at significance level 35 | % |alpha| for sample MVGCs in |x|, based on theoretical (asymptotic) 36 | % distributions. |NaN| s are ignored. See for 37 | % details of other parameters. 38 | % 39 | %% References 40 | % 41 | % [1] L. Barnett and A. K. Seth, 42 | % , _J. Neurosci. Methods_ 223, 2014 45 | % [ ]. 46 | % 47 | %% See also 48 | % 49 | % | 50 | % | 51 | % | 52 | % | 53 | % 54 | % 55 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 56 | % installation directory for licensing terms. 57 | % 58 | %% 59 | 60 | function [xup,xlo] = mvgc_confint(alpha,x,p,m,N,nx,ny,nz,tstat) 61 | 62 | if nargin < 8, nz = []; end % ensure default 63 | if nargin < 9, tstat = []; end % ensure default 64 | 65 | assert(isscalar(alpha),'alpha must be a scalar'); 66 | 67 | s = size(x); 68 | xup = NaN(s); % output xup matrix is same shape as x matrix 69 | xlo = NaN(s); % output xlo matrix is same shape as x matrix 70 | nn = ~isnan(x); % indices of non-NaN x values (logical array) 71 | x = x(nn); % vectorise non-NaN x values 72 | 73 | a = alpha*ones(size(x)); 74 | xup(nn) = mvgc_cdfi(1-a,x,p,m,N,nx,ny,nz,tstat); 75 | xlo(nn) = mvgc_cdfi(a, x,p,m,N,nx,ny,nz,tstat); 76 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/stats/mvgc_cval.m: -------------------------------------------------------------------------------- 1 | %% mvgc_cval 2 | % 3 | % Critical values for sample MVGC based on theoretical asymptotic null distribution 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % x = mvgc_cval(alpha,p,m,N,nx,ny,nz,tstat) 10 | % 11 | %% Arguments 12 | % 13 | % See also . 14 | % 15 | % _input_ 16 | % 17 | % alpha vector of significance levels 18 | % p VAR model order 19 | % m number of observations per trial 20 | % N number of trials 21 | % nx number of target ("to") variables 22 | % ny number of source ("from") variables 23 | % nz number of conditioning variables (default: 0) 24 | % tstat statistic: 'F' or 'chi2' (default: 'F' if nx == 1, else 'chi2') 25 | % 26 | % _output_ 27 | % 28 | % x vector of critical MVGC values 29 | % 30 | %% Description 31 | % 32 | % Returns critical MVGC values |x| at significance levels in |alpha| for sample 33 | % MVGC, based on theoretical (asymptotic) null distribution. See for details of other parameters. 35 | % 36 | %% References 37 | % 38 | % [1] L. Barnett and A. K. Seth, 39 | % , _J. Neurosci. Methods_ 223, 2014 42 | % [ ]. 43 | % 44 | %% See also 45 | % 46 | % | 47 | % | 48 | % | 49 | % | 50 | % | 51 | % 52 | % 53 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 54 | % installation directory for licensing terms. 55 | % 56 | %% 57 | 58 | function x = mvgc_cval(alpha,p,m,N,nx,ny,nz,tstat) 59 | 60 | if nargin < 7, nz = []; end % ensure default 61 | if nargin < 8, tstat = []; end % ensure default 62 | 63 | assert(isvector(alpha),'significance levels must be a scalar or vector'); 64 | 65 | x = mvgc_cdfi(1-alpha,0,p,m,N,nx,ny,nz,tstat); % assume null hypothesis F = 0 66 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/stats/mvgc_pval.m: -------------------------------------------------------------------------------- 1 | %% mvgc_pval 2 | % 3 | % p-values for sample MVGC based on theoretical asymptotic null distribution 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % pval = mvgc_pval(x,p,m,N,nx,ny,nz,tstat) 10 | % 11 | %% Arguments 12 | % 13 | % See also . 14 | % 15 | % _input_ 16 | % 17 | % x matrix of MVGC values 18 | % p VAR model order 19 | % m number of observations per trial 20 | % N number of trials 21 | % nx number of target ("to") variables 22 | % ny number of source ("from") variables 23 | % nz number of conditioning variables (default: 0) 24 | % tstat statistic: 'F' or 'chi2' (default: 'F' if nx == 1, else 'chi2') 25 | % 26 | % _output_ 27 | % 28 | % pval matrix of p-values 29 | % 30 | %% Description 31 | % 32 | % Returns p-values |pval| for sample MVGCs in |x|, based on theoretical 33 | % (asymptotic) null distribution. |NaN| s are ignored. See for details of other parameters. 35 | % 36 | % *_Important:_* To test p-values for statistical significance you should 37 | % correct for multiple null hypotheses; see routine . 39 | % 40 | %% References 41 | % 42 | % [1] L. Barnett and A. K. Seth, 43 | % , _J. Neurosci. Methods_ 223, 2014 46 | % [ ]. 47 | % 48 | %% See also 49 | % 50 | % | 51 | % | 52 | % | 53 | % | 54 | % | 55 | % 56 | % 57 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 58 | % installation directory for licensing terms. 59 | % 60 | %% 61 | 62 | function pval = mvgc_pval(x,p,m,N,nx,ny,nz,tstat) 63 | 64 | if nargin < 7, nz = []; end % ensure default 65 | if nargin < 8, tstat = []; end % ensure default 66 | 67 | pval = NaN(size(x)); % output p-value matrix is same shape as x matrix 68 | nn = ~isnan(x); % indices of non-NaN x values (logical array) 69 | x = x(nn); % vectorise non-NaN x values 70 | pval(nn) = 1-mvgc_cdf(x,0,p,m,N,nx,ny,nz,tstat); % assume null hypothesis F = 0 71 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/stats/rsquared.m: -------------------------------------------------------------------------------- 1 | %% rsquared 2 | % 3 | % [R^2] and adjusted [R^2] statistics 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % [RSQ,RSQADJ] = rsquared(X,E) 10 | % 11 | %% Arguments 12 | % 13 | % See also . 14 | % 15 | % _input_ 16 | % 17 | % X multi-trial time series data 18 | % E residuals time series 19 | % 20 | % _output_ 21 | % 22 | % RSQ R^2 statistic 23 | % RSQADJ adjusted R^2 statistic 24 | % 25 | %% Description 26 | % 27 | % Return [R^2] and adjusted [R^2] statistics. The time series data X and 28 | % residual errors E may be single- or multi-trial time series. 29 | % 30 | %% See also 31 | % 32 | % 33 | % 34 | %% Copyright notice 35 | % 36 | % [(C)] _Lionel Barnett and Anil K. Seth, 2012. See file 37 | % in root directory for licensing 38 | % terms._ 39 | % 40 | %% 41 | 42 | function [RSQ,RSQADJ] = rsquared(X,E) 43 | 44 | [n,m,N] = size(X); 45 | p = m-size(E,2); % number of lags in model 46 | assert(m >= n,'too few observations'); 47 | assert(size(E,1) == n && size(E,3) == N,'residuals don''t match data'); 48 | assert(p > 0,'bad number of lags'); 49 | 50 | X = demean(X); 51 | 52 | if N > 1 % multi-trial 53 | X = X(:,p+1:m,:); 54 | X = X(:,:); % stack data 55 | E = E(:,:); % stack residuals 56 | s = N*(m-p); % sample size (number of observations) 57 | else 58 | X = X(:,p+1:m); 59 | s = m-p; % sample size (number of observations) 60 | end 61 | r = n*n*p; % number of regressors in model 62 | 63 | SSR = sum(E.^2,2)'; % residuals sum of squares 64 | SST = sum(X.^2,2)'; % total sum of squares 65 | 66 | RSQ = 1 - SSR./SST; 67 | 68 | RSQADJ = 1 - ((s-1)/(s-r-1))*(1-RSQ); 69 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/bfft.m: -------------------------------------------------------------------------------- 1 | %% bfft 2 | % 3 | % "Block" Fast Fourier Transform (FFT) 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % AF = bfft(A,q) 10 | % 11 | %% Arguments 12 | % 13 | % See also . 14 | % 15 | % _input_ 16 | % 17 | % A n1 x n2 x p matrix 18 | % q frequency resolution (default: p) 19 | % 20 | % _output_ 21 | % 22 | % AF description 23 | % 24 | %% Description 25 | % 26 | % Returns the |q|-point discrete Fourier transform |AF| of each component 27 | % vector of the |n1 x n2 x p| matrix |A|, where the last index is the vector 28 | % index. If |q < p| a warning is issued that the FFT will truncate. 29 | % 30 | %% See also 31 | % 32 | % | 33 | % 34 | % 35 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 36 | % installation directory for licensing terms. 37 | % 38 | %% 39 | 40 | function AF = bfft(A,q) 41 | 42 | [n1,n2,p] = size(A); 43 | 44 | if nargin < 2 || isempty(q) 45 | q = p; 46 | else 47 | if q < p 48 | fprintf(2,'WARNING: frequency resolution too low - fft will truncate!\n'); 49 | end 50 | end 51 | 52 | AF = reshape(fft(reshape(A,n1*n2,p).',q).',n1,n2,q); % q-point Fourier transform on [0, 2*pi) 53 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/bifft.m: -------------------------------------------------------------------------------- 1 | %% bifft 2 | % 3 | % "Block" Inverse Fast Fourier Transform (IFFT) 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % AF = bifft(A,q) 10 | % 11 | %% Arguments 12 | % 13 | % See also . 14 | % 15 | % _input_ 16 | % 17 | % A n1 x n2 x p matrix 18 | % q frequency resolution (default: p) 19 | % 20 | % _output_ 21 | % 22 | % AF description 23 | % 24 | %% Description 25 | % 26 | % Returns the |q|-point discrete inverse Fourier transform |AF| of each 27 | % component vector of the |n1 x n2 x p| matrix |A|, where the last index is the 28 | % vector index. If |q < p| a warning is issued that the IFFT will truncate. 29 | % 30 | %% See also 31 | % 32 | % | 33 | % 34 | % 35 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 36 | % installation directory for licensing terms. 37 | % 38 | %% 39 | 40 | function AF = bifft(A,q) 41 | 42 | [n1,n2,p] = size(A); 43 | 44 | if nargin < 2 || isempty(q) 45 | q = p; 46 | else 47 | if q < p 48 | fprintf(2,'WARNING: frequency resolution too low - ifft will truncate!\n'); 49 | end 50 | end 51 | 52 | AF = reshape(ifft(reshape(A,n1*n2,p).',q).',n1,n2,q); % q-point inverse Fourier transform on [0, 2*pi) 53 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/control/dlyap.m: -------------------------------------------------------------------------------- 1 | %% dlyap 2 | % 3 | % Solve discrete-time Lyapunov equation by Schur decomposition 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % X = dlyap(A,Q) 10 | % 11 | %% Arguments 12 | % 13 | % See also . 14 | % 15 | % _input_ 16 | % 17 | % A square matrix with spectral radius < 1 18 | % Q symmetric positive-definite matrix 19 | % 20 | % _output_ 21 | % 22 | % X solution of discrete-time Lyapunov equation X = A*X*A'+Q 23 | % 24 | %% Description 25 | % 26 | % Solves the discrete-time Lyapunov equation 27 | % 28 | % <> 29 | % 30 | % using Schur decomposition and column-by-column solution [1,2] (this is quite 31 | % likely the same algorithm as in the Matlab Control System Toolbox 32 | % , except that no balancing is performed). This 33 | % function is substantially slower than ; if the 34 | % Matlab Control System Toolbox is not available, the user might like to 35 | % consider using instead. 36 | % 37 | % The caller should test that |Q| is positive-definite and that the spectral 38 | % radius of |A| is |< 1| before calling. 39 | % 40 | % Adapted from an early scripted (i.e. non- ) 41 | % version of 's 42 | % function. 43 | % 44 | %% References 45 | % 46 | % [1] X. Kitagawa, "An algorithm for solving the matrix equation X = F X F'+S", 47 | % _Internat. J. Control_ 25(5), 1977. 48 | % 49 | % [2] S. Hammarling, "Numerical solution of the stable, non-negative definite 50 | % Lyapunov equation", _IMA J. Numer. Anal._ 2, 1982. 51 | % 52 | %% See also 53 | % 54 | % | 55 | % 56 | % 57 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 58 | % installation directory for licensing terms. 59 | % 60 | %% 61 | 62 | function X = dlyap(A,Q) 63 | 64 | X = lyapslv('D',A,[],-Q); 65 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/control/lyapslv.m: -------------------------------------------------------------------------------- 1 | function X = lyapslv(~,A,~,Q) 2 | 3 | % called from 'dlyap' as: X = lyapslv('D',A,[],Q); 4 | 5 | n = size(A,1); 6 | assert(size(A,2) == n,'matrix A not square'); 7 | assert(isequal(size(Q),size(A)),'matrix Q does not match matrix A'); 8 | 9 | % Schur factorisation 10 | 11 | [U,T] = schur(A); 12 | Q = -U'*Q*U; 13 | 14 | % solve the equation column ~by column 15 | 16 | X = zeros(n); 17 | j = n; 18 | while j > 0 19 | j1 = j; 20 | 21 | % check Schur block size 22 | 23 | if j == 1 24 | bsiz = 1; 25 | elseif T(j,j-1) ~= 0 26 | bsiz = 2; 27 | j = j-1; 28 | else 29 | bsiz = 1; 30 | end 31 | bsizn = bsiz*n; 32 | 33 | Ajj = kron(T(j:j1,j:j1),T)-eye(bsizn); 34 | 35 | rhs = reshape(Q(:,j:j1),bsizn,1); 36 | 37 | if j1 < n 38 | rhs = rhs + reshape(T*(X(:,(j1+1):n)*T(j:j1,(j1+1):n)'),bsizn,1); 39 | end 40 | 41 | v = -Ajj\rhs; 42 | X(:,j) = v(1:n); 43 | 44 | if bsiz == 2 45 | X(:,j1) = v((n+1):bsizn); 46 | end 47 | 48 | j = j-1; 49 | end 50 | 51 | % transform back to original coordinates 52 | 53 | X = U*X*U'; 54 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/cov2corr.m: -------------------------------------------------------------------------------- 1 | %% cov2corr 2 | % 3 | % Convert (auto)covariance to (auto)correlation 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % R = cov2corr(G) 10 | % 11 | %% Arguments 12 | % 13 | % See also . 14 | % 15 | % _input_ 16 | % 17 | % G a covariance matrix or autocovariance sequence 18 | % 19 | % _output_ 20 | % 21 | % R a correlation matrix or autocorrelation sequence 22 | % 23 | %% Description 24 | % 25 | % Calculates (auto)correlation |R| from (auto)covariance |G|. 26 | % 27 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 28 | % installation directory for licensing terms. 29 | % 30 | %% 31 | 32 | function R = cov2corr(G) 33 | 34 | assert(ndims(G) == 2 || ndims(G) == 3,'(auto)covariance matrix must have 2 or 3 dimensions'); 35 | [n,n1,q1] = size(G); 36 | assert(n1 == n,'(auto)covariance matrix has bad shape'); 37 | 38 | R = zeros(size(G)); 39 | D = diag(1./sqrt(diag(G(:,:,1)))); 40 | for k = 1:q1 41 | R(:,:,k) = D*G(:,:,k)*D; 42 | end 43 | 44 | 45 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/fexists.m: -------------------------------------------------------------------------------- 1 | function res = fexists(fhandle) 2 | 3 | try 4 | feval(fhandle); 5 | %fprintf('no exception\n'); 6 | res = true; 7 | catch except 8 | %fprintf('exception: ''%s'', ''%s''\n', except.identifier,except.message); 9 | res = ~strcmpi(except.identifier,'MATLAB:UndefinedFunction'); 10 | end 11 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/genvar.m: -------------------------------------------------------------------------------- 1 | %% genvar 2 | % 3 | % Generate VAR time series data 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % [X,E] = genvar(A,E,trunc) 10 | % 11 | %% Arguments 12 | % 13 | % See also . 14 | % 15 | % _input_ 16 | % 17 | % A VAR coefficients matrix 18 | % E residuals (single-trial) time series 19 | % trunc number of initial observations to truncate (default: 0) 20 | % 21 | % _output_ 22 | % 23 | % X VAR (single-trial) time series with residuals E 24 | % E possibly truncated residuals 25 | % 26 | %% Description 27 | % 28 | % Generates a vector autoregression (VAR) time series with coefficients |A| and 29 | % residuals |E|; implements: 30 | % 31 | % <> 32 | % 33 | % Initial values for the outputs |X| are set to the residuals |E|. Optionally 34 | % truncate the first |trunc| observations. 35 | % 36 | % *_Note:_* If available will use the C routine to perform the actual computation; otherwise a (slower) 38 | % Matlab-coded routine is used. The existence of a |genvar| mex file for the 39 | % current platform is checked for in the script. 40 | % 41 | %% See also 42 | % 43 | % | 44 | % 45 | % 46 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 47 | % installation directory for licensing terms. 48 | % 49 | %% 50 | 51 | function [X,E] = genvar(A,E,trunc) 52 | 53 | global have_genvar_mex; 54 | 55 | assert(isreal(A) && (ndims(A) == 2 || ndims(A) == 3), 'VAR coefficients must be a 2D or 3D matrix') 56 | assert(isreal(E) && ndims(E) == 2, 'Residuals covariance must be a row vector or 2D matrix') 57 | 58 | [n1,n2,p] = size(A); 59 | [n,m] = size(E); 60 | 61 | assert(n1 == n2, 'VAR coefficients blocks not square'); 62 | assert(n1 == n, 'Residuals covariance matrix doesn''t match VAR coefficients matrix'); 63 | 64 | if nargin < 3 || isempty(trunc) 65 | trunc = 0; 66 | else 67 | assert(trunc >= 0 && trunc < m,'bad truncation'); 68 | end 69 | 70 | if have_genvar_mex 71 | X = genvar_mex(A,E); 72 | else 73 | X = E; 74 | for t = p+1:m 75 | for k = 1:p 76 | X(:,t) = X(:,t) + A(:,:,k)*X(:,t-k); 77 | end 78 | end 79 | end 80 | 81 | if trunc > 0 82 | X = X(:,trunc+1:m); 83 | if nargout > 1 84 | E = E(:,trunc+1:m); 85 | end 86 | end 87 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/get_crand.m: -------------------------------------------------------------------------------- 1 | %% get_crand 2 | % 3 | % Generate a high-entropy random number from clock time 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % u = get_crand 10 | % 11 | %% Arguments 12 | % 13 | % _output_ 14 | % 15 | % u a random number (double) 16 | % 17 | %% Description 18 | % 19 | % Generates a 32-bit integer from clock time via an 20 | % and converts it to double. (Nearly always) increases 22 | % sequentially every tenth of a millisecond, and will not repeat for about five 23 | % days. Handy for initial seeding of RNGs; see , 24 | % . On Unix or Mac systems, 25 | % is probably to be preferred (for Windows we might implement something based on 26 | % 27 | % at some point). 28 | % 29 | %% See also 30 | % 31 | % | 32 | % | 33 | % 34 | % 35 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 36 | % installation directory for licensing terms. 37 | % 38 | %% 39 | 40 | function u = get_crand 41 | 42 | t = clock; 43 | u = mod(round(cumprod([10000,60,60,24,31,12])*t(6:-1:1)'),2^32); % don't ask 44 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/get_hostname.m: -------------------------------------------------------------------------------- 1 | %% get_hostname 2 | % 3 | % Get system host name 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % hostname = get_hostname 10 | % 11 | %% Arguments 12 | % 13 | % _output_ 14 | % 15 | % hostname string; system short host name 16 | % 17 | %% Description 18 | % 19 | % Returns system short hostname for Unix, Mac and Windows machines. This is 20 | % handy if you run Matlab on different machines and a program needs to know 21 | % which machine it's running on. 22 | % 23 | % On Unix and Mac, it uses the system |hostname -s| call; if this fails, it 24 | % tries the system |uname -n| call. On Windows machines it uses the call 25 | % |getenv('COMPUTERNAME')|. If |get_hostname| fails it issues a warning and 26 | % returns an empty string. If called without a return argument it prints out the 27 | % name of the host name. 28 | % 29 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 30 | % installation directory for licensing terms. 31 | % 32 | %% 33 | 34 | function hostname = get_hostname 35 | 36 | hostname = ''; 37 | 38 | if isunix || ismac 39 | 40 | [status,hostname] = system('hostname -s'); 41 | if status ~= 0 || isempty(hostname) 42 | [status,hostname] = system('uname -n'); 43 | if status ~= 0 44 | hostname = ''; 45 | end 46 | end 47 | if isempty(hostname) % give up 48 | fprintf(2,'WARNING(get_hostname): failed to get host name\n'); 49 | else 50 | hostname = hostname(1:end-1); % system calls seem to append a newline - cull it 51 | if nargout == 0, fprintf('host name is ''%s''\n', hostname); end 52 | end 53 | 54 | elseif ispc 55 | 56 | hostname = getenv('COMPUTERNAME'); 57 | if isempty(hostname) % give up 58 | fprintf(2,'WARNING(get_hostname): failed to get host name\n'); 59 | else 60 | if nargout == 0, fprintf('host name is ''%s''\n', hostname); end 61 | end 62 | 63 | else 64 | fprintf(2,'WARNING(get_hostname): we only know about Unix, Mac or Windows\n'); 65 | end 66 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/get_urand.m: -------------------------------------------------------------------------------- 1 | %% get_urand 2 | % 3 | % Read high-entropy random numbers from from |/dev/urandom| (Unix and Mac only) 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % u = get_urand(n) 10 | % 11 | %% Arguments 12 | % 13 | % _input_ 14 | % 15 | % n number of random numbers (default: 1) 16 | % 17 | % _output_ 18 | % 19 | % u random numbers (double) 20 | % 21 | %% Description 22 | % 23 | % Reads |n| unsigned 32-bit integers from |/dev/urandom| and converts them to 24 | % double. Handy for initial seeding of RNGs; see , 25 | % . On systems without |/dev/urandom| an alternative is 26 | % . 27 | % 28 | %% See also 29 | % 30 | % | 31 | % | 32 | % 33 | % 34 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 35 | % installation directory for licensing terms. 36 | % 37 | %% 38 | 39 | function u = get_urand(n) 40 | 41 | if nargin < 1, n = 1; end 42 | 43 | fid = fopen('/dev/urandom'); 44 | assert(fid >= 0,'get_urand: failed to open /dev/urandom (does it exist on your system?)'); 45 | [u,count] = fread(fid,n,'uint32'); 46 | status = fclose(fid); 47 | assert(status == 0,'get_urand: failed to close /dev/urandom'); 48 | assert(count == n,'get_urand: read %d of %d unsigned integers',count,n); 49 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/helpon.m: -------------------------------------------------------------------------------- 1 | %% helpon 2 | % 3 | % Display the page for an MVGC function or 4 | % script in the Matlab Help Browser. 5 | % 6 | % 7 | % 8 | %% Syntax 9 | % 10 | % helpon mname 11 | % helpon(mname) 12 | % 13 | %% Arguments 14 | % 15 | % _input_ 16 | % 17 | % mname string; the name of an MVGC function or script 18 | % 19 | %% Description 20 | % 21 | % Displays help in the Matlab Help Browser on |mname|, provided an html help 22 | % file called |mname.html| exists in the docs/html subdirectory of the MVGC root 23 | % directory. If |mname.html| is not found, a "not found" page is displayed. 24 | % 25 | %% See also 26 | % 27 | % | 28 | % 29 | % 30 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 31 | % installation directory for licensing terms. 32 | % 33 | %% 34 | 35 | function helpon(mname) 36 | 37 | global mvgc_root; 38 | 39 | if nargin < 1 || isempty(mname), mname = 'mvgchelp'; end 40 | 41 | htmlfile = fullfile(mvgc_root,'docs','html',[mname '.html']); 42 | if exist(htmlfile,'file') == 2 43 | web(htmlfile,'-helpbrowser'); 44 | else 45 | notfound = fullfile(mvgc_root,'docs','html','notfound.html'); 46 | web(notfound,'-helpbrowser'); 47 | fprintf(2,'\nSorry, no help on ''%s''\n\n',mname); 48 | end 49 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/isbad.m: -------------------------------------------------------------------------------- 1 | %% isbad 2 | % 3 | % Determine whether array is "bad" 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % b = isbad(x) 10 | % 11 | %% Arguments 12 | % 13 | % _input_ 14 | % 15 | % x an array 16 | % demand_allfinite true (default) if "bad" means at least one NaN or Inf 17 | % 18 | % _output_ 19 | % 20 | % b logical scalar 21 | % 22 | %% Description 23 | % 24 | % Simple routine that returns true/false according as to whether the input |x| 25 | % is "bad", meaning (i) if |demand_allfinite| flag set (default) it contains at 26 | % least one |NaN| or |Inf| or (ii) if |demand_allfinite| flag unset it contains 27 | % all |NaN| s or |Inf| s. This is useful to check results of calculations that 28 | % result in |NaN| s or |Inf| s when they shouldn't (in particular 29 | % ). 30 | % 31 | %% See also 32 | % 33 | % | 34 | % 35 | % 36 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 37 | % installation directory for licensing terms. 38 | % 39 | %% 40 | 41 | function b = isbad(x,demand_allfinite) 42 | 43 | if nargin < 2 || isempty(demand_allfinite), demand_allfinite = true; end 44 | 45 | if demand_allfinite 46 | b = ~all(isfinite(x(:))); 47 | else 48 | b = ~any(isfinite(x(:))); 49 | end 50 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/isint.m: -------------------------------------------------------------------------------- 1 | %% isint 2 | % 3 | % Determine whether numerical values are integers 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % I = isint(x) 10 | % 11 | %% Arguments 12 | % 13 | % _input_ 14 | % 15 | % x a numeric array 16 | % 17 | % _output_ 18 | % 19 | % I a logical array 20 | % 21 | %% Description 22 | % 23 | % Simple routine that returns a logical array with logical |true| wherever the 24 | % corresponding entry in |x| is an integer. 25 | % 26 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 27 | % installation directory for licensing terms. 28 | % 29 | %% 30 | 31 | function I = isint(x) 32 | 33 | assert(isnumeric(x),'not a numeric array'); 34 | I = x == floor(x); 35 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/isposdef.m: -------------------------------------------------------------------------------- 1 | %% isposdef 2 | % 3 | % Determine whether (symmetric) matrix is positive-definite 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % pd = isposdef(A) 10 | % 11 | %% Arguments 12 | % 13 | % _input_ 14 | % 15 | % A a symmetric matrix 16 | % 17 | % _output_ 18 | % 19 | % pd logical true if A is positive-definite 20 | % 21 | %% Description 22 | % 23 | % Returns true if A is positive-definite. Uses the Matlab function, and like that function the lower triangle of A is assumed to 25 | % be the (complex conjugate) transpose of the upper triangle; i.e. this routine 26 | % does _not_ check for symmetry! 27 | % 28 | %% See also 29 | % 30 | % 31 | % 32 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 33 | % installation directory for licensing terms. 34 | % 35 | %% 36 | 37 | function pd = isposdef(A) 38 | 39 | [~,p] = chol(A); 40 | pd = ~(p > 0); 41 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/legacy/make_legacy.m: -------------------------------------------------------------------------------- 1 | function mdir = make_legacy(tdir) 2 | 3 | global mvgc_root; 4 | 5 | if nargin < 1 || isempty(tdir), tdir = [tempdir 'mvgc_legacy']; end 6 | 7 | fprintf('Populating target directory...'); 8 | syscmd = ['cp -r ' mvgc_root filesep '* ' tdir]; 9 | status = system(syscmd,'-echo'); 10 | if status == 0 11 | fprintf(' done\n'); 12 | else 13 | fprintf(2,' failed\n'); 14 | return 15 | end 16 | 17 | mvgctree = genpath(mvgc_root); 18 | while length(mvgctree) > 1 19 | [mdir, mvgctree] = strtok(mvgctree,pathsep); 20 | if isempty(strfind(mdir,'/docs')) && isempty(strfind(mdir,'/C')) && isempty(strfind(mdir,'/mex')) 21 | make_leg(mdir,tdir) 22 | end 23 | end 24 | 25 | function make_leg(mdir,tdir) 26 | 27 | global mvgc_root; 28 | 29 | % Replace stuff in m files 30 | 31 | tdir = strrep(mdir,mvgc_root,tdir); 32 | 33 | fprintf('Target ''%s''\n',tdir); 34 | 35 | mcells = struct2cell(dir([mdir filesep '*.m'])); 36 | n = size(mcells,2); % 1st two are ',' and '..' 37 | for i = 1:n 38 | mfile = mcells{1,i}; 39 | fprintf('\tProcessing m file %2d of %d = ''%s''...',i,n,mfile); 40 | 41 | mfilef = fullfile(mdir,mfile); 42 | fidr = fopen(mfilef, 'r'); 43 | if fidr == -1 44 | fprintf(2,' failed to open input file ''%s''\n',mfilef); 45 | continue 46 | end 47 | str = fread(fidr,inf,'*char')'; 48 | status = fclose(fidr); 49 | if status ~= 0 50 | fprintf(2,' failed to close input file ''%s''\n',mfilef); 51 | continue 52 | end 53 | 54 | % replace '~' in return values with 'dummy' 55 | 56 | expr = '[~,'; 57 | repstr = '[dummy,'; 58 | str = strrep(str,expr,repstr); 59 | 60 | expr = ',~,'; 61 | repstr = ',dummy,'; 62 | str = strrep(str,expr,repstr); 63 | 64 | expr = ',~]'; 65 | repstr = ',dummy]'; 66 | str = strrep(str,expr,repstr); 67 | 68 | expr = '[~]'; 69 | repstr = 'dummy'; 70 | str = strrep(str,expr,repstr); 71 | 72 | tfilef = fullfile(tdir,mfile); 73 | fidw = fopen(tfilef, 'w'); 74 | if fidw == -1 75 | fprintf(2,' failed to open output file ''%s''\n',tfilef); 76 | continue 77 | end 78 | fwrite(fidw,str); 79 | status = fclose(fidw); 80 | if status ~= 0 81 | fprintf(2,' failed to close output file ''%s''\n',tfilef); 82 | continue 83 | end 84 | 85 | fprintf(' done\n'); 86 | end 87 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/legacy/randi/randi.m: -------------------------------------------------------------------------------- 1 | function r = randi(imax,n) 2 | 3 | %fprintf(2,'legacy imax!\n'); 4 | assert(nargin > 0,'too few arguments'); 5 | if nargin == 1 6 | r = 1+floor(imax*rand); 7 | elseif nargin == 2 8 | r = 1+floor(imax*rand(n)); 9 | else 10 | error('please use array form for matrix dimension argument'); 11 | end 12 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/legacy/rng/rng.m: -------------------------------------------------------------------------------- 1 | function state = rng(s) 2 | 3 | if nargin == 0 % save 4 | 5 | assert(nargout == 1,'bad syntax'); 6 | state.rand = rand('twister'); 7 | state.randn = randn('state'); 8 | 9 | elseif nargin == 1 % seed/restore 10 | 11 | assert(nargout == 0,'bad syntax'); 12 | if isstruct(s) 13 | seed = s; 14 | else 15 | seed.rand = s; 16 | seed.randn = s; 17 | end 18 | rand('twister',seed.rand); 19 | randn('state', seed.randn); 20 | 21 | else 22 | error('bad number of arguments'); 23 | end 24 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/maxabs.m: -------------------------------------------------------------------------------- 1 | %% maxabs 2 | % 3 | % Calculate maximum absolute value of all entries in an array 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % d = maxabs(X) 10 | % 11 | %% Arguments 12 | % 13 | % _input_ 14 | % 15 | % X an array 16 | % 17 | % _output_ 18 | % 19 | % d maximum absolute value of all entries in X 20 | % 21 | %% Description 22 | % 23 | % Returns the maximum absolute value |d| of all entries in |X|. |NaN| s are ignored. 24 | % 25 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 26 | % installation directory for licensing terms. 27 | % 28 | %% 29 | 30 | function d = maxabs(X) 31 | 32 | d = max(abs(X(:))); 33 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/mvdiff.m: -------------------------------------------------------------------------------- 1 | %% mvdiff 2 | % 3 | % Multivariate differencing 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % Y = mvdiff(X,dff) 10 | % 11 | %% Arguments 12 | % 13 | % See also . 14 | % 15 | % _input_ 16 | % 17 | % X multi-trial time series data 18 | % dff vector of number of differencing steps (default: 1 = 1st difference) 19 | % 20 | % _output_ 21 | % 22 | % Y differenced time series 23 | % 24 | %% Description 25 | % 26 | % Y = mvdiff(X,dff) 27 | % 28 | % Multivariate differencing of time series data in |X|, which may be 29 | % multi-trial. Differences |dff| are supplied as a scalar (applied to each time 30 | % series) or as a vector matching the number of variables. Default is 1st 31 | % difference. The individual time series in the differenced multivariate series 32 | % |Y| are correctly synchronised. 33 | % 34 | %% See also 35 | % 36 | % 37 | % 38 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 39 | % installation directory for licensing terms. 40 | % 41 | %% 42 | 43 | function Y = mvdiff(X,dff) 44 | 45 | if nargin < 2 || isempty(dff), dff = 1; end % default 46 | 47 | [n,m,N] = size(X); 48 | 49 | if isscalar(dff) 50 | dff = dff*ones(1,n); 51 | else 52 | assert(isvector(dff) && length(dff) == n,'differences must be a scalar or a vector of same length as number of variables'); 53 | end 54 | assert(all(isint(dff)) && all(dff >= 0),'differences must be non-negative integers'); 55 | 56 | Y = zeros(size(X)); 57 | for r = 1:N 58 | for i = 1:n 59 | d = dff(i); 60 | if d > 0 61 | Y(i,d+1:m,r) = diff(X(i,:,r),d,2); 62 | else 63 | Y(i,:,r) = X(i,:,r); 64 | end 65 | end 66 | end 67 | Y = Y(:,max(dff)+1:m,:); 68 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/plot_pw.m: -------------------------------------------------------------------------------- 1 | %% plot_pw 2 | % 3 | % Plot pairwise quantities on a colourmapped grid 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % plot_pw(P,cm) 10 | % 11 | %% Arguments 12 | % 13 | % _input_ 14 | % 15 | % P square matrix of pairwise quantities 16 | % cm colour map (default: something soothing) 17 | % 18 | %% Description 19 | % 20 | % Plot pairwise quantities in |P|, a 2-dim square numerical matrix with 21 | % first index representing target ("to") and second index source ("from") 22 | % quantities, typically causalities, p-values, significances, etc. (see 23 | % e.g. ). Diagonal entries 24 | % are ignored. A colormap |cm| may be supplied. 25 | % 26 | %% See also 27 | % 28 | % | 29 | % 30 | % 31 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 32 | % installation directory for licensing terms. 33 | % 34 | %% 35 | 36 | function plot_pw(P,cm) 37 | 38 | if nargin < 2 || isempty(cm), cm =flipud(bone); end; 39 | 40 | n = size(P,1); 41 | assert(ismatrix(P) && size(P,2) == n,'input must be a square 2D matrix'); 42 | 43 | colormap(cm); 44 | maxP = max(P(:)); 45 | if maxP == 0, maxP = 1; end 46 | imagesc(P,[0 maxP]); 47 | axis('square'); 48 | xlabel('from'); 49 | ylabel('to'); 50 | set(gca,'XTick',1:n); 51 | set(gca,'XTickLabel',1:n); 52 | set(gca,'YTick',1:n); 53 | set(gca,'YTickLabel',1:n); 54 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/plot_spw.m: -------------------------------------------------------------------------------- 1 | %% plot_spw 2 | % 3 | % Plot spectral pairwise quantities on a grid 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % plot_spw(P,fs) 10 | % 11 | %% Arguments 12 | % 13 | % _input_ 14 | % 15 | % P matrix of spectral pairwise quantities 16 | % fs sample rate in Hz (default: normalised freq as per routine 'sfreqs') 17 | % frange frequency range to plot: empty for all (default) else an ascending 2-vector 18 | % 19 | %% Description 20 | % 21 | % Plot pairwise spectral quantities in |P|, a 3-dim numerical matrix with 22 | % first index representing target ("to"), second index source ("from") 23 | % quantities and third index frequencies - typically spectral causalities (see 24 | % e.g. ). 25 | % 26 | %% See also 27 | % 28 | % | 29 | % | 30 | % 31 | % 32 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 33 | % installation directory for licensing terms. 34 | % 35 | %% 36 | 37 | function plot_spw(P,fs,frange) 38 | 39 | n = size(P,1); 40 | assert(ndims(P) == 3 && size(P,2) == n,'must be a 3-dim matrix with the first two dims square'); 41 | h = size(P,3); 42 | 43 | if nargin < 2, fs = []; end % default to normalised frequency as per 'sfreqs' 44 | 45 | if nargin < 3, frange = []; end; % default to all 46 | if ~isempty(frange) 47 | assert(isvector(frange) && length(frange) == 2 && frange(1) < frange(2),'frequency range must be an ascending 2-vector of frequencies'); 48 | end 49 | 50 | fres = h-1; 51 | lam = sfreqs(fres,fs)'; 52 | if ~isempty(frange) 53 | idx = lam >= frange(1) & lam <= frange(2); 54 | lam = lam(idx); 55 | P = P(:,:,idx,:); 56 | end 57 | xlims = [lam(1) lam(end)]; 58 | ylims = [min(P(:)) 1.1*max(P(:))]; 59 | if isempty(fs), xlab = 'normalised frequency'; else xlab = 'frequency (Hz)'; end 60 | 61 | k = 0; 62 | for i = 1:n 63 | for j = 1:n 64 | k = k+1; 65 | if i ~= j 66 | subplot(n,n,k); 67 | plot(lam,squeeze(P(i,j,:))); 68 | axis('square'); 69 | xlim(xlims); 70 | ylim(ylims); 71 | xlabel(xlab); 72 | ylabel(sprintf('%d -> %d',j,i)); 73 | end 74 | end 75 | end 76 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/plot_tsdata.m: -------------------------------------------------------------------------------- 1 | %% plot_tsdata 2 | % 3 | % Time series data plotting utility 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % plot_tsdata(X,leg,dt,trange) 10 | % 11 | %% Arguments 12 | % 13 | % See also . 14 | % 15 | % _input_ 16 | % 17 | % X multi-trial time series data 18 | % leg cell vector of legend strings matching G (default: 'series 1', 'series 2', etc.) 19 | % dt sample time step in seconds or empty (default) for number of time steps 20 | % trange time range to plot: empty for all (default) else an ascending 2-vector 21 | % 22 | %% Description 23 | % 24 | % Plot time series data |X| in a given time range |trange|. 25 | % 26 | %% See also 27 | % 28 | % 29 | % 30 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 31 | % installation directory for licensing terms. 32 | % 33 | %% 34 | 35 | function plot_tsdata(X,leg,dt,trange) 36 | 37 | [n,m,N] = size(X); 38 | 39 | if nargin < 2 || isempty(leg), for i=1:n, leg{i} = sprintf('series %d',i); end; end % default is 'autocov i'; 40 | assert(isvector(leg) && iscellstr(leg),'legend must be a cell vector of strings'); 41 | assert(length(leg) == n,'legend does not match time series matrix'); 42 | 43 | pnts = nargin < 3 || isempty(dt); % time = number of time steps 44 | if pnts, dt = 1; end 45 | 46 | if nargin < 4, trange = []; end; % default to all 47 | if ~isempty(trange) 48 | assert(isvector(trange) && length(trange) == 2 && trange(1) < trange(2),'frequency range must be an ascending 2-vector of times'); 49 | end 50 | 51 | m1 = m-1; 52 | tvec = (0:m1)*dt; 53 | if ~isempty(trange) 54 | idx = tvec >= trange(1) & tvec <= trange(2); 55 | tvec = tvec(idx); 56 | X = X(:,idx,:); 57 | end 58 | 59 | xlims = [tvec(1) tvec(end)]; 60 | if pnts, xlab = 'time steps'; else xlab = 'time (secs)'; end 61 | 62 | for r = 1:N 63 | subplot(N,1,r); 64 | plot(tvec,X(:,:,r)); 65 | xlim(xlims); 66 | xlabel(xlab); 67 | if N > 1, ylabel(sprintf('trial %d',r)); end % multi-trial 68 | legend(leg); 69 | end 70 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/plot_varcoeffs.m: -------------------------------------------------------------------------------- 1 | %% plot_varcoeffs 2 | % 3 | % VAR coefficients plotting utility 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % plot_varcoeffs(A) 10 | % 11 | %% Arguments 12 | % 13 | % See also . 14 | % 15 | % _input_ 16 | % 17 | % A VAR coefficients matrix 18 | % 19 | %% Description 20 | % 21 | % Plots VAR coefficients |A| against lags for each pair of variables on a grid. 22 | % 23 | %% See also 24 | % 25 | % 26 | % 27 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 28 | % installation directory for licensing terms. 29 | % 30 | %% 31 | 32 | function plot_varcoeffs(A) 33 | 34 | [n,n1,q] = size(A); 35 | assert(n1 == n,'VAR coefficients matrix has bad shape'); 36 | 37 | t = (1:q)'; 38 | xlims = [1 q]; 39 | ylims = [min(A(:)) max(A(:))]; 40 | 41 | k = 0; 42 | for i = 1:n 43 | for j = 1:n 44 | k = k+1; 45 | subplot(n,n,k); 46 | plot(t,squeeze(A(i,j,:))); 47 | grid on; 48 | xlabel('lags'); 49 | ylabel(sprintf('var %d,%d',i,j)); 50 | xlim(xlims); 51 | ylim(ylims); 52 | end 53 | end 54 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/ptic.m: -------------------------------------------------------------------------------- 1 | %% ptic 2 | % 3 | % Print message and start timer 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % ptic(s) 10 | % 11 | %% Arguments 12 | % 13 | % _input_ 14 | % 15 | % s message string 16 | % 17 | %% Description 18 | % 19 | % Simple wrapper for Matlab timer function. Print 20 | % message string |s| and start a timer. Stop timer with . 21 | % 22 | %% See also 23 | % 24 | % | 25 | % | 26 | % 27 | % 28 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 29 | % installation directory for licensing terms. 30 | % 31 | %% 32 | 33 | function ptic(s) 34 | 35 | if nargin < 1 || isempty(s); s = 'TIMER: '; end 36 | 37 | fprintf(s); 38 | 39 | tic 40 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/ptoc.m: -------------------------------------------------------------------------------- 1 | %% ptoc 2 | % 3 | % Stop timer and print message 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % ptoc(s1,s2,inhms) 10 | % 11 | %% Arguments 12 | % 13 | % _input_ 14 | % 15 | % s1 pre-time message string 16 | % 21 post-time message string 17 | % inhms use `timestr' time formatting utility to print time 18 | % 19 | %% Description 20 | % 21 | % Simple wrapper for Matlab timer function. Stop 22 | % timer, print message string |s1|, followed by the elapsed time (see 23 | % ), followed by message string |s2|. If the |inhms| flag 24 | % is set, the utility is used to format the 25 | % elapsed time printout, else elapsed time is reported in seconds (see 26 | % ). 27 | % 28 | %% See also 29 | % 30 | % | 31 | % | 32 | % | 33 | % 34 | % 35 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 36 | % installation directory for licensing terms. 37 | % 38 | %% 39 | 40 | function ptoc(s1,s2,inhms) 41 | 42 | t=toc; 43 | 44 | if nargin < 1 || isempty(s1); s1 = ''; end 45 | if nargin < 2 || isempty(s2); s2 = '\n'; end 46 | 47 | if nargin > 2 && inhms 48 | fprintf([s1 '%s' s2],timestr(t)); 49 | else 50 | fprintf([s1 '%f secs' s2],t); 51 | end 52 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/quads.m: -------------------------------------------------------------------------------- 1 | %% quads 2 | % 3 | % Trapezoidal rule quadrature (numerical integration) 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % q = quads(x,Y) 10 | % 11 | %% Arguments 12 | % 13 | % _input_ 14 | % 15 | % x vector of evaluation points 16 | % Y matrix of values corresponding to x 17 | % 18 | % _output_ 19 | % 20 | % q vector of quadratures 21 | % 22 | %% Description 23 | % 24 | % A simple trapezoidal rule quadrature routine (_cf._ ). Integrate each column of matrix |Y| assumed evaluated at 26 | % points in vector |x|. 27 | % 28 | % 29 | %% See also 30 | % 31 | % | 32 | % | 33 | % 34 | % 35 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 36 | % installation directory for licensing terms. 37 | % 38 | %% 39 | 40 | function q = quads(x,Y) 41 | 42 | assert(isvector(x),'evaluation points must be a vector'); 43 | assert(size(Y,1) == length(x),'values and evaluation points must have same length'); 44 | 45 | x = x(:); % force column vector 46 | xx = x(:,ones(1,size(Y,2))); 47 | q = sum((xx(2:end,:)-xx(1:end-1,:)).*((Y(2:end,:)+Y(1:end-1,:))))/2; 48 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/rng_restore.m: -------------------------------------------------------------------------------- 1 | %% rng_restore 2 | % 3 | % Restore the Matlab default (global) random number generator state 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % rng_restore(state) 10 | % 11 | %% Arguments 12 | % 13 | % _input_ 14 | % 15 | % state previous rng state 16 | % 17 | %% Description 18 | % 19 | % Restore the Matlab default (global) state from |state|. If |state == 0| it is ignored. See 21 | % , . 22 | % 23 | %% Example 24 | % 25 | % state = rng_seed(seed); 26 | % X = rand(10,3); 27 | % rng_restore(state); 28 | % 29 | %% See also 30 | % 31 | % | 32 | % | 33 | % 34 | % 35 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 36 | % installation directory for licensing terms. 37 | % 38 | %% 39 | 40 | function rng_restore(state) 41 | 42 | if ~isstruct(state) && isscalar(state) && state == 0, return; end % do nothing 43 | 44 | rng(state); % restore rng state 45 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/rng_save.m: -------------------------------------------------------------------------------- 1 | %% rng_save 2 | % 3 | % Save the Matlab default (global) random number generator state 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % state = rng_save 10 | % 11 | %% Arguments 12 | % 13 | % _output_ 14 | % 15 | % state current rng state 16 | % 17 | %% Description 18 | % 19 | % Save the Matlab default (global) 20 | % state. It may be restored later using . 21 | % 22 | %% See also 23 | % 24 | % | 25 | % | 26 | % 27 | % 28 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 29 | % installation directory for licensing terms. 30 | % 31 | %% 32 | 33 | function state = rng_save 34 | 35 | state = rng; % save rng state 36 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/rng_seed.m: -------------------------------------------------------------------------------- 1 | %% rng_seed 2 | % 3 | % Seed the Matlab default (global) random number generator 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % state = rng_seed(seed) 10 | % 11 | %% Arguments 12 | % 13 | % _input_ 14 | % 15 | % seed random seed: an integer in the range [0, 2^32 ? 1], or a negative number 16 | % 17 | % _output_ 18 | % 19 | % state previous rng state 20 | % 21 | %% Description 22 | % 23 | % Seed the Matlab default (global) 24 | % (which is used for calls such as , 25 | % , etc.). If |seed| is positive, use that seed. If 26 | % zero, do nothing. If negative, seed with something really unpredictable, using 27 | % either (Unix, Mac) or (Windows); see e.g. the MVGC script. 29 | % Optionally return the previous rng state in |state| (see ). 31 | % 32 | %% Example 33 | % 34 | % state = rng_seed(seed); 35 | % X = rand(10,3); 36 | % rng_restore(state); 37 | % 38 | %% See also 39 | % 40 | % | 41 | % | 42 | % | 43 | % | 44 | % | 45 | % 46 | % 47 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 48 | % installation directory for licensing terms. 49 | % 50 | %% 51 | 52 | function state = rng_seed(seed) 53 | 54 | if nargout > 0 55 | if ~isstruct(seed) && isscalar(seed) && seed == 0 56 | state = 0; % state = 0 means don't restore (see rng_restore) 57 | else 58 | state = rng_save; % save state (see rng_restore) 59 | end 60 | end 61 | 62 | if seed == 0, return; end % do nothing 63 | 64 | if seed < 0 % seed with unpredictable seed 65 | if isunix || ismac 66 | seed = get_urand; % from Unix /dev/urandom 67 | else 68 | seed = get_crand; % from clock time 69 | end 70 | end 71 | 72 | rng(seed); % seed rng 73 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/secs2hms.m: -------------------------------------------------------------------------------- 1 | %% secs2hms 2 | % 3 | % Convert time in seconds to hours/minutes/seconds 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % [h,m,s] = secs2hms(t) 10 | % 11 | %% Arguments 12 | % 13 | % _input_ 14 | % 15 | % t time in seconds 16 | % 17 | % _output_ 18 | % 19 | % h hours 20 | % m minutes 21 | % s seconds 22 | % 23 | %% Description 24 | % 25 | % Return hours, minutes, seconds |h|, |m|, |s| of time |t| in seconds. 26 | % 27 | %% See also 28 | % 29 | % 30 | % 31 | %% Copyright notice 32 | % 33 | % [(C)] _Lionel Barnett and Anil K. Seth, 2012. See file 34 | % in root directory for licensing 35 | % terms._ 36 | % 37 | %% 38 | 39 | function [h,m,s] = secs2hms(t) 40 | 41 | s = t; 42 | h = fix(s/3600); 43 | s = s - 3600*h; 44 | m = fix(s/60); 45 | s = s - 60*m; 46 | 47 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/sfreqs.m: -------------------------------------------------------------------------------- 1 | %% sfreqs 2 | % 3 | % Return vector of frequencies 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % freqs = sfreqs(fres,fs) 10 | % 11 | %% Arguments 12 | % 13 | % See also . 14 | % 15 | % _input_ 16 | % 17 | % fres frequency resolution 18 | % fs sample rate (default: 2*pi) 19 | % 20 | % _output_ 21 | % 22 | % freqs vector of frequencies 23 | % 24 | %% Description 25 | % 26 | % Returns (column) vector |freqs| of |fres+1| equally spaced frequencies on 27 | % |[0,fs/2]|, where |fs| is a sample rate (so |fs/2| is the Nyqvist frequency). 28 | % If a sample rate is not supplied (default), frequencies are returned over the 29 | % normalised range |[0 pi]|. 30 | % 31 | %% See also 32 | % 33 | % All spectral routines 34 | % 35 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 36 | % installation directory for licensing terms. 37 | % 38 | %% 39 | 40 | function freqs = sfreqs(fres,fs) 41 | 42 | if nargin < 2 || isempty(fs); 43 | fs = 2*pi; % normalised 44 | end 45 | 46 | freqs = linspace(0,fs/2,fres+1)'; 47 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/stats/chi2cdf.m: -------------------------------------------------------------------------------- 1 | function P = chi2cdf(X,V) 2 | 3 | assert((isequal(size(X),size(V))),'X and V must be of common size or scalars'); 4 | 5 | P = gamcdf(X,V/2,2); 6 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/stats/chi2inv.m: -------------------------------------------------------------------------------- 1 | function X = chi2inv(P,V) 2 | 3 | assert((isequal(size(P),size(V))),'P and V must be of common size or scalars'); 4 | 5 | X = gaminv(P,V/2,2); 6 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/stats/gamcdf.m: -------------------------------------------------------------------------------- 1 | function P = gamcdf(X,A,B) 2 | 3 | assert((isequal(size(A),size(X)) && isequal(size(B),size(X))),'X, A and B must be of common size or scalars'); 4 | 5 | sz = size(X); 6 | P = zeros(sz); 7 | 8 | k = find(~(A > 0) | ~(B > 0) | isnan(X)); 9 | if any(k) 10 | P(k) = NaN; 11 | end 12 | 13 | k = find((X > 0) & (A > 0) & (B > 0)); 14 | if any(k) 15 | if isscalar(A) && isscalar(B) 16 | P(k) = gammainc(X(k)./B,A); 17 | else 18 | P(k) = gammainc(X(k)./B(k),A(k)); 19 | end 20 | end 21 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/stats/gaminv.m: -------------------------------------------------------------------------------- 1 | function X = gaminv(P,A,B) 2 | 3 | assert((isequal(size(A),size(P)) && isequal(size(B),size(P))),'P, A and B must be of common size or scalars'); 4 | 5 | sz = size(P); 6 | X = zeros(sz); 7 | 8 | k = find((P < 0) | (P > 1) | isnan(P) | ~(A > 0) | ~(B > 0)); 9 | if (any(k)) 10 | X(k) = NaN; 11 | end 12 | 13 | k = find((P == 1) & (A > 0) & (B > 0)); 14 | if any(k) 15 | X(k) = Inf; 16 | end 17 | 18 | k = find((P > 0) & (P < 1) & (A > 0) & (B > 0)); 19 | if any(k) 20 | if ~isscalar(A) || ~isscalar(B) 21 | A = A(k); 22 | B = B(k); 23 | y = A.*B; 24 | else 25 | y = A*B*ones(size(k)); 26 | end 27 | P = P(k); 28 | 29 | if isa(P, 'single') 30 | myeps = eps('single'); 31 | else 32 | myeps = eps; 33 | end 34 | 35 | l = find(P < myeps); 36 | if any(l) 37 | y(l) = sqrt(myeps)*ones(length(l), 1); 38 | end 39 | 40 | y_old = y; 41 | for i = 1 : 100 42 | h = (gamcdf(y_old,A,B)-P)./gampdf(y_old,A,B); 43 | y_new = y_old-h; 44 | ind = find(y_new <= myeps); 45 | if any(ind) 46 | y_new(ind) = y_old(ind)/10; 47 | h = y_old-y_new; 48 | end 49 | if max(abs(h)) < sqrt(myeps) 50 | break; 51 | end 52 | y_old = y_new; 53 | end 54 | 55 | X(k) = y_new; 56 | end 57 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/stats/gampdf.m: -------------------------------------------------------------------------------- 1 | function Y = gampdf(X,A,B) 2 | 3 | assert((isequal(size(A),size(X)) && isequal(size(B),size(X))),'X, A and B must be of common size or scalars'); 4 | 5 | sz = size(X); 6 | Y = zeros(sz); 7 | 8 | k = find(~(A > 0) | ~(B > 0) | isnan(X)); 9 | if any(k) 10 | Y(k) = NaN; 11 | end 12 | 13 | k = find((X > 0) & (A > 0) & (A <= 1) & (B > 0)); 14 | if any(k) 15 | if isscalar(A) && isscalar(B) 16 | Y(k) = (X(k).^(A - 1)).*exp(-X(k)./B)./gamma(A)./(B .^ A); 17 | else 18 | Y(k) = (X(k).^(A(k)-1)).*exp(-X(k)./B(k))./gamma(A(k))./(B(k).^A(k)); 19 | end 20 | end 21 | 22 | k = find((X > 0) & (A > 1) & (B > 0)); 23 | if any(k) 24 | if isscalar(A) && isscalar(B) 25 | Y(k) = exp(-A.*log(B)+(A-1).*log(X(k))-X(k)./B-gammaln(A)); 26 | else 27 | Y(k) = exp(-A(k).*log(B(k))+(A(k)-1).*log(X(k))-X(k)./B(k)-gammaln(A(k))); 28 | end 29 | end 30 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/timestr.m: -------------------------------------------------------------------------------- 1 | %% timestr 2 | % 3 | % Format time string in hours/minutes/seconds 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % tstr = timestr(t) 10 | % 11 | %% Arguments 12 | % 13 | % _input_ 14 | % 15 | % t time (seconds) 16 | % 17 | % _output_ 18 | % 19 | % tstr formatted time string 20 | % 21 | %% Description 22 | % 23 | % Return formatted string |tstr| of time |t| (assumed in seconds). 24 | % 25 | %% See also 26 | % 27 | % | 28 | % | 29 | % 30 | % 31 | %% Copyright notice 32 | % 33 | % [(C)] _Lionel Barnett and Anil K. Seth, 2012. See file 34 | % in root directory for licensing 35 | % terms._ 36 | % 37 | %% 38 | 39 | function tstr = timestr(t) 40 | 41 | [h,m,s] = secs2hms(t); 42 | if h > 0 43 | tstr = sprintf('%d:%d:%05.2f secs',h,m,s); 44 | else 45 | if m > 0 46 | tstr = sprintf('%d:%05.2f secs',m,s); 47 | else 48 | tstr = sprintf('%.2f secs',s); 49 | end 50 | end 51 | 52 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/trfun2var.m: -------------------------------------------------------------------------------- 1 | %% trfun2var 2 | % 3 | % Calculate coefficients from VAR transfer function 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % [A,p] = trfun2var(H,p) 10 | % 11 | %% Arguments 12 | % 13 | % See also . 14 | % 15 | % _input_ 16 | % 17 | % H VAR transfer function matrix 18 | % p VAR model order = number of lags (default: calculate automatically) 19 | % 20 | % _output_ 21 | % 22 | % A VAR coefficients matrix 23 | % p VAR model order = number of lags 24 | % 25 | %% Description 26 | % 27 | % Return coefficients |A| for VAR with transfer function |H|. If a VAR 28 | % model order |p| is not specified (default), then it is set automatically 29 | % according to the frequency resolution of the transfer function. 30 | % 31 | %% References 32 | % 33 | % [1] L. Barnett and A. K. Seth, 34 | % , _J. Neurosci. Methods_ 223, 2014 37 | % [ ]. 38 | % 39 | %% See also 40 | % 41 | % | 42 | % 43 | % 44 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 45 | % installation directory for licensing terms. 46 | % 47 | %% 48 | 49 | function [A,p] = trfun2var(H,p) 50 | 51 | [n,~,h] = size(H); 52 | fres = h-1; 53 | if nargin < 2 || isempty(p), p = 2*fres-1; end 54 | assert(p < 2*fres,'too many lags'); 55 | 56 | I = eye(n); 57 | AF = zeros(n,n,2*fres); % over [0,2*pi) 58 | for k = 1:h % over [0,pi] 59 | AF(:,:,k) = I/H(:,:,k); 60 | end 61 | for k = 1:h-2 % over (pi,2*pi) 62 | AF(:,:,h+k) = conj(AF(:,:,h-k)); 63 | end 64 | A = real(bifft(AF)); 65 | A = -A(:,:,2:p+1); 66 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/var2trfun.m: -------------------------------------------------------------------------------- 1 | %% var2trfun 2 | % 3 | % Calculate VAR transfer function from VAR coefficients 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % H = var2trfun(A,fres) 10 | % 11 | %% Arguments 12 | % 13 | % See also . 14 | % 15 | % _input_ 16 | % 17 | % A VAR coefficients matrix 18 | % fres frequency resolution 19 | % 20 | % _output_ 21 | % 22 | % H VAR transfer function matrix 23 | % 24 | %% Description 25 | % 26 | % Return transfer function |H| for VAR with coefficients |A|. |fres| 27 | % specifies the frequency resolution. Call |freqs = (fres,fs)|, where |fs| is the sampling rate, to get a corresponding 29 | % vector |freqs| of frequencies on |[0,fs/2]|. 30 | % 31 | %% References 32 | % 33 | % [1] L. Barnett and A. K. Seth, 34 | % , _J. Neurosci. Methods_ 223, 2014 37 | % [ ]. 38 | % 39 | %% See also 40 | % 41 | % | 42 | % | 43 | % | 44 | % 45 | % 46 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 47 | % installation directory for licensing terms. 48 | % 49 | %% 50 | 51 | function H = var2trfun(A,fres) 52 | 53 | n = size(A,1); 54 | I = eye(n); 55 | AF = bfft(cat(3,I,-A),2*fres); % over [0,2*pi) 56 | h = fres+1; 57 | H = zeros(n,n,h); 58 | for k = 1:h % over [0,pi] only 59 | H(:,:,k) = I/AF(:,:,k); 60 | end 61 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/var_decay.m: -------------------------------------------------------------------------------- 1 | %% var_decay 2 | % 3 | % Decay VAR coefficients 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % A = var_decay(A,dfac) 10 | % 11 | %% Arguments 12 | % 13 | % See also . 14 | % 15 | % _input_ 16 | % 17 | % A VAR coefficients matrix 18 | % dfac decay factor 19 | % 20 | % _output_ 21 | % 22 | % A decayed VAR coefficients matrix 23 | % 24 | %% Description 25 | % 26 | % Exponentially decay VAR coefficients |A| by factor |dfac|, which controls 27 | % how fast coefficients decay with lag. This will, in particular, affect 28 | % the _spectral radius_ (see ) of the 29 | % coefficients. 30 | % 31 | %% References 32 | % 33 | % [1] L. Barnett and A. K. Seth, 34 | % , _J. Neurosci. Methods_ 223, 2014 37 | % [ ]. 38 | % 39 | %% See also 40 | % 41 | % 42 | % 43 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 44 | % installation directory for licensing terms. 45 | % 46 | %% 47 | 48 | function A = var_decay(A,dfac) 49 | 50 | p = size(A,3); 51 | f = dfac; 52 | for k=1:p 53 | A(:,:,k) = f*A(:,:,k); 54 | f = dfac*f; 55 | end 56 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/var_info.m: -------------------------------------------------------------------------------- 1 | %% var_info 2 | % 3 | % Display VAR information as returned by |var_to_autocov| 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % acerr = var_info(info,abort_on_error) 10 | % 11 | %% Arguments 12 | % 13 | % See also . 14 | % 15 | % _input_ 16 | % 17 | % info info structure returned by var_to_autocov 18 | % abort_on_error if set to true, abort if var_to_autocov reports an error 19 | % 20 | % _output_ 21 | % 22 | % acerr flag set to true if var_to_autocov reports an error 23 | % 24 | %% Description 25 | % 26 | % Displays information (errors, warnings, diagnostics, _etc_.) reported by the 27 | % routine ; see that routine for details. 28 | % This function should _always_ be called after a call to . 30 | % 31 | %% See also 32 | % 33 | % 34 | % 35 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 36 | % installation directory for licensing terms. 37 | % 38 | %% 39 | 40 | function acerr = var_info(info,abort_on_error) 41 | 42 | if nargin < 2 || isempty(abort_on_error), abort_on_error = true; end 43 | 44 | acerr = info.error; 45 | 46 | fprintf('\nVAR info:\n'); 47 | if info.error 48 | fprintf(2,' ERROR: %s\n',info.errmsg); 49 | else 50 | fprintf(' no errors\n'); 51 | end 52 | 53 | if info.warnings > 0 54 | for n = 1:info.warnings 55 | fprintf(2,' WARNING: %s\n',info.warnmsg{n}); 56 | end 57 | else 58 | fprintf(' no warnings\n'); 59 | end 60 | 61 | if ~isnan(info.rho) 62 | fprintf(' spectral radius : %f\n',info.rho); 63 | end 64 | 65 | if ~isnan(info.iters) 66 | fprintf(' iterations : %d\n',info.iters); 67 | end 68 | 69 | if ~isnan(info.acrelerr) 70 | fprintf(' ac relative error : %g\n',info.acrelerr); 71 | end 72 | 73 | if ~isnan(info.acminlags) 74 | fprintf(' minimum ac lags : %d\n',info.acminlags); 75 | end 76 | 77 | if ~isnan(info.aclags) 78 | fprintf(' actual ac lags : %d\n',info.aclags); 79 | end 80 | 81 | fprintf('\n'); 82 | 83 | assert(~(info.error && abort_on_error),'VAR info: aborting on error.'); 84 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/var_normalise.m: -------------------------------------------------------------------------------- 1 | %% var_normalise 2 | % 3 | % Normalise VAR coefficients 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % [A,SIG] = var_normalise(A,SIG) 10 | % 11 | %% Arguments 12 | % 13 | % See also . 14 | % 15 | % _input_ 16 | % 17 | % A VAR coefficients matrix 18 | % SIG residuals covariance matrix 19 | % 20 | % _output_ 21 | % 22 | % A normalised VAR coefficients matrix 23 | % SIG normalised residuals covariance matrix 24 | % 25 | %% Description 26 | % 27 | % Normalise VAR coefficients matrix |A| and residuals covariance matrix |SIG| so 28 | % that residuals have unit variance (are "Studentised"). 29 | % 30 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 31 | % installation directory for licensing terms. 32 | % 33 | %% 34 | 35 | function [A,SIG] = var_normalise(A,SIG) 36 | 37 | [n,n1,p] = size(A); 38 | assert(n1 == n,'VAR coefficients matrix has bad shape'); 39 | [nn1,nn2] = size(SIG); 40 | assert(nn1 == nn2,'residuals covariance matrix not square'); 41 | assert(nn1 == n ,'residuals covariance matrix doesn''t match VAR coefficients matrix'); 42 | 43 | S = sqrt(diag(SIG)); 44 | V = diag(S); 45 | VI = diag(1./S); 46 | 47 | for k = 1:p 48 | A(:,:,k) = VI*A(:,:,k)*V; 49 | end 50 | SIG = VI*SIG*VI'; 51 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/var_specrad.m: -------------------------------------------------------------------------------- 1 | %% var_specrad 2 | % 3 | % Calculate VAR spectral radius 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % rho = var_specrad(A) 10 | % [A,rho]= var_specrad(A,newrho) 11 | % 12 | %% Arguments 13 | % 14 | % See also . 15 | % 16 | % _input_ 17 | % 18 | % A VAR coefficients matrix 19 | % newrho new VAR spectral radius 20 | % 21 | % _output_ 22 | % 23 | % A VAR coefficients matrix 24 | % rho VAR spectral radius 25 | % 26 | %% Description 27 | % 28 | % _First form:_ return the spectral radius |rho| for a VAR process with 29 | % coefficients matrix |A|. May be used for unit root test (i.e. need |rho < 1|). 30 | % 31 | % _Second form:_, a new value |newrho| for the spectral radius is supplied 32 | % and the coefficients |A| are "decayed" (see function ) so that the new value of the spectral radius becomes 34 | % |newrho|. The new coefficients and old value of the spectral radius are 35 | % returned. Note: |newrho| may be negative, but |newrho < 1| is required 36 | % for the new coefficients to specify a stable process. 37 | % 38 | %% See also 39 | % 40 | % 41 | % 42 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 43 | % installation directory for licensing terms. 44 | % 45 | %% 46 | 47 | function [out1,out2] = var_specrad(A,newrho) 48 | 49 | [n,n1,p] = size(A); 50 | assert(n1 == n,'VAR coefficients matrix has bad shape'); 51 | pn1 = (p-1)*n; 52 | 53 | % construct VAR coefficients for 1-lag problem 54 | 55 | A1 = [reshape(A,n,p*n); eye(pn1) zeros(pn1,n)]; 56 | 57 | % calculate spectral radius 58 | 59 | rho = max(abs(eig(A1))); 60 | 61 | if nargin < 2 || isempty(newrho) 62 | assert(nargout <= 1,'too many output parameters'); 63 | out1 = rho; % spectral radius 64 | else 65 | out1 = var_decay(A,newrho/rho); % adjusted coefficients 66 | out2 = rho; % previous value of spectral radius 67 | end 68 | 69 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/warn_if.m: -------------------------------------------------------------------------------- 1 | %% warn_if 2 | % 3 | % Test a condition and warn if true 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % wcond = warn_if(wcond,msgstr,warnfunc) 10 | % 11 | %% Arguments 12 | % 13 | % _input_ 14 | % 15 | % wcond condition to test 16 | % msgstr string specifying warning message 17 | % warnfunc string specifying which function issued the warning 18 | % 19 | % _output_ 20 | % 21 | % wcond condition to test 22 | % 23 | %% Description 24 | % 25 | % Tests the condition |wcond|; if |false| the warning message |msgstr| is 26 | % printed. A string specifying which function issued the warning may be supplied 27 | % in |warnfunc| - if not present it defaults to the enclosing function. 28 | % 29 | % This utility is included for consistency with . 30 | % 31 | %% Example 32 | % 33 | % A = 10; 34 | % if warn_if(A > 9, 'A is > 9 !!'); 35 | % return % can't carry on 36 | % end 37 | % 38 | %% See also 39 | % 40 | % 41 | % 42 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 43 | % installation directory for licensing terms. 44 | % 45 | %% 46 | 47 | function wcond = warn_if(wcond,msgstr,wfunc) 48 | 49 | assert(nargin > 1 && ischar(msgstr),'must specify a consition and a warning message string'); 50 | if nargin < 3, wfunc = []; end 51 | 52 | if ~wcond, return; end 53 | 54 | if isempty(wfunc) % no function specified 55 | ST = dbstack; 56 | if length(ST) > 1 57 | fprintf(2,'WARNING in ''%s'': %s\n',ST(2).name,msgstr); 58 | else 59 | fprintf(2,'WARNING in unknown function: %s\n',msgstr); 60 | end 61 | else 62 | assert(ischar(wfunc),'bad warning function specification'); 63 | fprintf(2,'WARNING in ''%s'': %s\n',wfunc,msgstr); 64 | end 65 | -------------------------------------------------------------------------------- /libs/mvgc_v1.0/utils/warn_supp.m: -------------------------------------------------------------------------------- 1 | %% warn_supp 2 | % 3 | % Suppress printing of Matlab warning message 4 | % 5 | % 6 | % 7 | %% Syntax 8 | % 9 | % oldstate = warn_supp(warnid) 10 | % 11 | %% Arguments 12 | % 13 | % _input_ 14 | % 15 | % warnid Matlab warning identifier (default: 'all', for all warnings) 16 | % 17 | % _output_ 18 | % 19 | % oldstate previous state of warning corresponding to warnid 20 | % 21 | %% Description 22 | % 23 | % Suppresses printing of Matlab warning message corresponding to warning ID 24 | % |warnid|; see . The default is to 25 | % suppress _all_ warnings. The routine can be 26 | % used to test whether a condition triggering the given warning was 27 | % actually issued. 28 | % 29 | % The ... routines 30 | % exist for two reasons: (1) if routines issuing warnings are run in a loop 31 | % (which they frequently are in the MVGC Toolbox), Matlab will by default spew 32 | % confusing warnings, obscuring meaningful ouput; (2) we want to be able to 33 | % issue meaningful context-dependent warning messages. 34 | % 35 | %% Example 36 | % 37 | % A = magic(6); 38 | % oldstate = warn_supp('MATLAB:nearlySingularMatrix'); 39 | % B = inv(A); 40 | % warn_test(oldstate,'badly-conditioned matrix?'); 41 | % 42 | %% See also 43 | % 44 | % | 45 | % | 46 | % 47 | % 48 | % (C) Lionel Barnett and Anil K. Seth, 2012. See file license.txt in 49 | % installation directory for licensing terms. 50 | % 51 | %% 52 | 53 | function oldstate = warn_supp(warnid) 54 | 55 | if nargin < 1 || isempty(warnid), warnid = 'all'; end % default: suppress all warnings 56 | 57 | oldstate = warning('off', warnid); % suppress specified warning(s) 58 | lastwarn(''); % clear last warning 59 | -------------------------------------------------------------------------------- /libs/nolte/colormap_interpol.m: -------------------------------------------------------------------------------- 1 | function newmap=colormap_interpol(map,fak); 2 | % creates a finer colormap consisting of fak times more colors) 3 | 4 | [n,ndum]=size(map); 5 | 6 | newmap(1,:)=map(1,:); 7 | 8 | m=1; 9 | for i=2:n; 10 | for k=1:fak 11 | m=m+1; 12 | newmap(m,:)=((fak-k)*map(i-1,:)+k*map(i,:))/fak; 13 | end 14 | end 15 | 16 | return; -------------------------------------------------------------------------------- /libs/pellegrini/fp_fft_coeffs.m: -------------------------------------------------------------------------------- 1 | function coeffs = fp_fft_coeffs(data,segleng,segshift,epleng,freqpairs) 2 | % Get Fourier coefficients for epoched data. 3 | % The output coeffs is peaks x nchan x ntrials. 4 | % The 4 peaks correspond to 1) the low-frequeny peak, 2) the left side 5 | % lobe, 3) the high-frequency peak, 4) the right side lobe. 6 | % 7 | % Copyright (c) 2023 Franziska Pellegrini and Stefan Haufe 8 | 9 | [ndat,nchan]=size(data); 10 | 11 | mywindow=repmat(hanning(segleng),1,nchan); 12 | nep=floor(ndat/epleng); 13 | 14 | nseg=floor((epleng-segleng)/segshift)+1; %total number of segments 15 | assert(nseg==1,'only possible with 1 segment') 16 | 17 | for j=1:nep 18 | %disp(j) 19 | dataloc=data((j-1)*epleng+1:j*epleng,:); 20 | datalocfft(:,:,j)=fft(detrend(dataloc).*mywindow); 21 | end 22 | 23 | coeffs(1,:,:) = datalocfft(freqpairs(1),:,:); %f1 24 | coeffs(2,:,:) = datalocfft(freqpairs(2)-freqpairs(1)+1,:,:); %f2-f1 25 | coeffs(3,:,:) = datalocfft(freqpairs(2),:,:); %f2 26 | coeffs(4,:,:) = datalocfft(freqpairs(2)+freqpairs(1)-1,:,:); %f1+f2 -------------------------------------------------------------------------------- /libs/ssgc_v1.0/ar2iss.m: -------------------------------------------------------------------------------- 1 | function [A,C,K,rho] = ar2iss(ARA) 2 | 3 | % Return innovations form state space model parameters corresponding to a vector 4 | % autoregressive model. 5 | % 6 | % ARA - AR coefficients array 7 | % 8 | % A,C,K - innovations form state space parameters 9 | % 10 | % rho - AR spectral norm 11 | % 12 | % ARA is an n x n x p matrix, where n is the dimension of the observation 13 | % variable and p the AR model order, so that ARA(:,:,k) is the AR coefficients 14 | % matrix at lag k. Note that rho >= 1 indicates an unstable AR process: rho > 1 15 | % is explosive, rho close to 1 may be unit-root. 16 | 17 | [n,n1,p] = size(ARA); % p is VAR model order 18 | assert(n1 == n); 19 | pn1 = (p-1)*n; 20 | 21 | C = reshape(ARA,n,p*n); 22 | A = [C; eye(pn1) zeros(pn1,n)]; 23 | K = [eye(n); zeros(pn1,n)]; 24 | 25 | if nargout > 3 26 | rho = max(abs(eig(A,'nobalance'))); 27 | end 28 | -------------------------------------------------------------------------------- /libs/ssgc_v1.0/ar_IC.m: -------------------------------------------------------------------------------- 1 | function [paic,pbic,aic,bic] = ar_IC(y,pmax,disp) 2 | 3 | % Compute Akaike (AIC) and Schwarz' Bayesian (BIC) information criteria for 4 | % autoregressive model order estimation. 5 | % 6 | % y - observation process time series 7 | % pmax - maximum AR model order (number of lags) 8 | % 9 | % paic, pbic - Akaike and Bayesian optimal AR model orders based on data in y 10 | % aic, bic - vectors of the actual information criteria (for plotting) 11 | % 12 | % The time series y is a matrix of dimensions n x (number of time steps), where 13 | % n is the dimension of the observation process. The algorithm estimates the 14 | % likelihood by OLS very efficiently; a single QR decomposition is performed, 15 | % and used to calculate regressions at all model orders. Any failed regressions 16 | % will result in NaNs in the information criteria at that model order. 17 | 18 | if nargin < 3 || isempty(disp), disp = true; end 19 | 20 | [n,T] = size(y); 21 | 22 | y = bsxfun(@minus,y,mean(y,2)); % subtract temporal mean 23 | 24 | T = T-pmax; % we'll lose pmax observations 25 | 26 | % store lags 27 | 28 | y0 = y(:,pmax+1:pmax+T); % lag zero 29 | Yp = zeros(n,pmax,T); % lags 1 through pmax 30 | for p = 1:pmax 31 | Yp(:,p,:) = y(:,pmax+1-p:pmax+T-p); 32 | end 33 | Yp = reshape(Yp,n*pmax,T); % stack lagged data 34 | 35 | % perform QR decomposition for all lags in one shot 36 | 37 | [Q,R] = qr(Yp',0); % "economy-size" decomposition is all we need 38 | y0Q = y0*Q; 39 | 40 | aic = nan(pmax,1); 41 | bic = nan(pmax,1); 42 | 43 | % loop through model orders 44 | 45 | for p = 1:pmax 46 | np = n*p; 47 | r = min(np,T); 48 | ARA = y0Q(:,1:r)/R(1:r,1:np)'; % OLS for regression against first p lags only 49 | if ~all(isfinite(ARA)), continue; end % show-stopper - skip and carry on 50 | e = y0-ARA*Yp(1:np,:); % residuals 51 | L = log(det((e*e')/(T-1))); % likelihood 52 | nfp = n*np; % number of free parameters 53 | if T > nfp+1 54 | aic(p) = L + 2*nfp/(T-nfp-1); % with Hurvich and Tsai small-sample correction 55 | end 56 | bic(p) = L + nfp*log(T)/T; 57 | end 58 | 59 | % optimal model orders (note: NaNs are ignored) 60 | 61 | morder = 1:pmax; 62 | [~,idx] = min(aic); paic = morder(idx); 63 | [~,idx] = min(bic); pbic = morder(idx); 64 | 65 | if disp 66 | plot(morder,[aic bic]); 67 | xlim([1 pmax]); 68 | title('AR model order information criteria'); 69 | legend(sprintf('AIC (opt = %d)',paic),sprintf('BIC (opt = %d)',pbic),'location','northwest'); 70 | end 71 | -------------------------------------------------------------------------------- /libs/ssgc_v1.0/ar_gen.m: -------------------------------------------------------------------------------- 1 | function [y,e] = ar_gen(ARA,V,T) 2 | 3 | % Generate a realization of a vector autoregressive process with Gaussian 4 | % residuals. 5 | % 6 | % ARA - AR coefficients array 7 | % V - residuals covariance matrix 8 | % T - sequence length (time steps) 9 | % 10 | % y - observation time series 11 | % e - residuals time series 12 | % 13 | % Time series y,e are matrices of dimensions n x (number of time steps), where n 14 | % is the dimension of the observation process. The AR coefficients array ARA has 15 | % dimensions n x n x p, so that ARA(:,:,k) is the k-lag AR coefficients matrix, 16 | % while V is n x n. 17 | % 18 | % Note that we need rho < 1 for a stable process, where rho is the spectral norm 19 | % of ARA (see routine specnorm.m). V must be symmetric positive-definite. 20 | % 21 | % The returned time series should be truncated at the beginning if an 22 | % (approximately) stationary process is required. Since transients for a stable 23 | % AR(p) process decay exponentially at a rate rho, a reasonable number of time 24 | % steps to truncate is of the order log(eps)/log(rho). 25 | 26 | [n,n1,p] = size(ARA); assert(n1 == n); 27 | 28 | % Gaussian white noise innovations with covariance matrix V 29 | 30 | e = chol(V,'lower')*randn(n,T); 31 | 32 | % Construct observations - autoregress 33 | 34 | y = e; 35 | for t = p+1:T 36 | for k = 1:p 37 | y(:,t) = y(:,t) + ARA(:,:,k)*y(:,t-k); 38 | end 39 | end 40 | -------------------------------------------------------------------------------- /libs/ssgc_v1.0/ar_rand.m: -------------------------------------------------------------------------------- 1 | function ARA = ar_rand(n,p,rhoa) 2 | 3 | % Generate random stable normally distributed autoregression coefficients. 4 | % 5 | % n - observation variable dimension 6 | % p - AR model order 7 | % rhoa - spectral norm 8 | % 9 | % ARA - autoregression coefficients array 10 | % 11 | % We need rhoa < 1 for a stable model. This routine creates ARA as a random 12 | % Gaussian array of dimensions n x n x p and scales it so that its spectral norm 13 | % is equal to rhoa. 14 | 15 | assert(rhoa < 1); 16 | 17 | ARA = randn(n,n,p); 18 | dfac = rhoa/specnorm(ARA); 19 | f = 1; 20 | for k = 1:p 21 | f = dfac*f; 22 | ARA(:,:,k) = f*ARA(:,:,k); 23 | end 24 | -------------------------------------------------------------------------------- /libs/ssgc_v1.0/arsid_OLS.m: -------------------------------------------------------------------------------- 1 | function [ARA,V,e] = arsid_OLS(y,p) 2 | 3 | % Estimate a vector autoregressive model from an empirical observation time 4 | % series using Ordinary Least Squares. 5 | % 6 | % y - observation process time series 7 | % p - AR model order (number of lags) 8 | % 9 | % ARA - estimated AR coefficients array 10 | % V - estimated resdiuals covariance matrix 11 | % e - estimated residuals time series 12 | % 13 | % Time series y,e are matrices of dimensions n x (number of time steps), where n 14 | % is the dimension of the observation process. The AR coefficients array ARA has 15 | % dimensions n x n x p, so that ARA(:,:,k) is the k-lag AR coefficients matrix, 16 | % while V is n x n symmetric and positive-(semi-)definite. 17 | 18 | [n,T] = size(y); 19 | 20 | assert(p < T,'model order too high (or not enough data)'); 21 | 22 | V = []; 23 | e = []; 24 | 25 | y = bsxfun(@minus,y,mean(y,2)); % subtract temporal mean 26 | 27 | p1 = p+1; 28 | Tp = T-p; 29 | 30 | y0 = y(:,p1:T); % lag zero 31 | Yp = zeros(n,p,Tp); % lags 1 through p 32 | for k = 1:p 33 | Yp(:,k,:) = y(:,p1-k:T-k); 34 | end 35 | Yp = reshape(Yp,n*p,Tp); % stack lagged data 36 | 37 | ARA = y0/Yp; % OLS ('rdivide' will generally using QR decomposition) 38 | 39 | % IMPORTANT: test for failed OLS with something like: 40 | % 41 | % assert(all(isfinite(ARA(:))),'OLS failed'); 42 | 43 | if nargout > 1 44 | e = y0-ARA*Yp; % residuals 45 | V = (e*e')/(Tp-1); % residuals covariance matrix 46 | if nargout > 2 47 | e = [nan(n,p) e]; % pad with NaNs to align with y 48 | end 49 | end 50 | 51 | ARA = reshape(ARA,n,n,p); % so ARA(:,:,k) is the k-lag AR coefficients matrix 52 | -------------------------------------------------------------------------------- /libs/ssgc_v1.0/cov_rand.m: -------------------------------------------------------------------------------- 1 | function V = cov_rand(n,icfac,corrmat) 2 | 3 | % Generate random positive-definite covariance matrix 4 | % 5 | % n - observation variable dimension 6 | % icfac - innovations correlation factor: a positive integer (as icfac gets 7 | % bigger, innovation correlations get smaller), or set to Inf for zero 8 | % correlation 9 | % corrmat - flag: return correlation matrix (default) 10 | % 11 | % V - covariance matrix 12 | % 13 | % V is generated as the sample covariance matrix of an n-dimensional 14 | % uncorrelated Gaussian white noise sequence of length icfac*n. This ensures 15 | % positive-definiteness. As ifac -> Inf, correlation between innovations -> 0. 16 | % Setting icfac = Inf yields a diagonal V (no correlation). If the corrmat flag 17 | % is set, V is normalised to variance 1; i.e. V is returned as a correlation 18 | % matrix (the identity matrix in the case icfac = Inf). 19 | 20 | assert(isscalar(icfac) && isnumeric(icfac) && icfac == floor(icfac) && icfac >= 1); 21 | 22 | if nargin< 3 || isempty(corrmat), corrmat = true; end 23 | 24 | if isinf(icfac) % diagonal covariance matrix 25 | if corrmat 26 | V = eye(n); 27 | else 28 | SQRTV = randn(n,1); 29 | V = diag(SQRTV.^2); 30 | end 31 | else 32 | SQRTV = randn(n,icfac*n)/sqrt(icfac*n); % sample covariance of n x n white noise of length icfac*n 33 | V = SQRTV*SQRTV'; 34 | if corrmat 35 | D = diag(1./sqrt(diag(V))); 36 | V = D*V*D; % correlation matrix 37 | end 38 | end 39 | 40 | -------------------------------------------------------------------------------- /libs/ssgc_v1.0/cov_rand1.m: -------------------------------------------------------------------------------- 1 | function V = cov_rand1(n,sig,r,corrmat) 2 | 3 | % Generate random positive-definite covariance matrix 4 | % 5 | % n - observation variable dimension 6 | % icfac - innovations correlation factor: a positive integer (as icfac gets 7 | % bigger, innovation correlations get smaller), or set to Inf for zero 8 | % correlation 9 | % corrmat - flag: return correlation matrix (default) 10 | % 11 | % V - covariance matrix 12 | % 13 | % V is generated as the sample covariance matrix of an n-dimensional 14 | % uncorrelated Gaussian white noise sequence of length icfac*n. This ensures 15 | % positive-definiteness. As ifac -> Inf, correlation between innovations -> 0. 16 | % Setting icfac = Inf yields a diagonal V (no correlation). If the corrmat flag 17 | % is set, V is normalised to variance 1; i.e. V is returned as a correlation 18 | % matrix (the identity matrix in the case icfac = Inf). 19 | 20 | %assert(isscalar(icfac) && isnumeric(icfac) && icfac == floor(icfac) && icfac >= 1); 21 | 22 | if nargin< 3 || isempty(corrmat), corrmat = true; end 23 | 24 | %{ 25 | if isinf(icfac) % diagonal covariance matrix 26 | if corrmat 27 | V = eye(n); 28 | else 29 | SQRTV = randn(n,1); 30 | V = diag(SQRTV.^2); 31 | end 32 | else 33 | %} 34 | 35 | R = tanh(triu(r*randn(n),0)); % correlations 36 | %R = R+R'+eye(n); 37 | R = R*R'; 38 | D = sig*diag(abs(randn(n,1))); 39 | V = D*R*D; 40 | if corrmat 41 | D = diag(1./sqrt(diag(V))); 42 | V = D*V*D; % correlation matrix 43 | end 44 | -------------------------------------------------------------------------------- /libs/ssgc_v1.0/iss_AR.m: -------------------------------------------------------------------------------- 1 | function B = iss_AR(A,C,K,z) 2 | 3 | % Compute autoregressive representation (inverse transfer function) for a state 4 | % space model in innovations form (eq. 5 in the reference article). 5 | % 6 | % A,C,K - innovations form state space parameters 7 | % z - a vector of points on the unit circle in the complex plane 8 | % 9 | % B - inverse transfer function 10 | 11 | [m,m1] = size(A); assert(m1 == m); 12 | [n,m1] = size(C); assert(m1 == m); 13 | [m1,n1] = size(K); assert(n1 == n && m1 == m); 14 | z = z(:); 15 | 16 | h = length(z); 17 | In = eye(n); 18 | Im = eye(m); 19 | BB = A-K*C; 20 | B = zeros(n,n,h); 21 | for k = 1:h 22 | B(:,:,k) = In - C*((z(k)*Im-BB)\K); % eq. 5 23 | end 24 | -------------------------------------------------------------------------------- /libs/ssgc_v1.0/iss_GC.m: -------------------------------------------------------------------------------- 1 | function F = iss_GC(A,C,K,V,i1,i2) 2 | 3 | % Compute time-domain (conditional) GC for a state space model from innovations 4 | % form parameters (eq. 9 in the reference article). 5 | % 6 | % A,C,K,V - innovations form state space parameters 7 | % i1 - target variable multi-index (vector of indices) 8 | % i2 - source variable multi-index (vector of indices) 9 | % 10 | % F - GC from i2 -> i1 11 | % 12 | % Calculates GC from y_i2 -> y_i1 conditional on y_i3, where i3 is the 13 | % multi-index of the remaining variables in the model. The multi-indices i1, i2 14 | % must not overlap. 15 | 16 | [m,m1] = size(A); assert(m1 == m); 17 | [n,m1] = size(C); assert(m1 == m); 18 | [m1,n1] = size(K); assert(n1 == n && m1 == m); 19 | [n1,n2] = size(V); assert(n1 == n && n2 == n); 20 | 21 | i1 = i1(:)'; assert(all(i1 >=1 & i1 <= n)); 22 | i2 = i2(:)'; assert(all(i2 >=1 & i2 <= n)); 23 | assert(isempty(intersect(i1,i2))); 24 | 25 | i3 = 1:n; i3([i1 i2]) = []; % indices of remaining (conditioning) variables 26 | i13 = [i1 i3]; 27 | i1R = 1:length(i1); 28 | 29 | F = NaN; 30 | 31 | KVSQRT = K*chol(V,'lower'); 32 | [~,VR,rep] = ss2iss(A,C(i13,:),KVSQRT*KVSQRT',V(i13,i13),K*V(:,i13)); % reduced model innovations covariance 33 | if rep < 0 34 | if rep == -1, warning('DARE: eigenvalues on/near unit circle'); 35 | elseif rep == -2, warning('DARE: couldn''t find stablising solution'); 36 | end 37 | return 38 | end 39 | if rep > sqrt(eps), warning('DARE: there were accuracy issues (relative residual = %e)',rep); 40 | return 41 | end 42 | 43 | F = log(det(VR(i1R,i1R))) - log(det(V(i1,i1))); % eq. 9 44 | -------------------------------------------------------------------------------- /libs/ssgc_v1.0/iss_MA.m: -------------------------------------------------------------------------------- 1 | function H = iss_MA(A,C,K,z) 2 | 3 | % Compute moving-average representation (transfer function) for a state space 4 | % model in innovations form (eq. 4 in the reference article). 5 | % 6 | % A,C,K - innovations form state space parameters 7 | % z - a vector of points on the unit circle in the complex plane 8 | % 9 | % H - transfer function 10 | 11 | [m,m1] = size(A); assert(m1 == m); 12 | [n,m1] = size(C); assert(m1 == m); 13 | [m1,n1] = size(K); assert(n1 == n && m1 == m); 14 | z = z(:); 15 | 16 | h = length(z); 17 | In = eye(n); 18 | Im = eye(m); 19 | H = zeros(n,n,h); 20 | for k = 1:h 21 | H(:,:,k) = In + C*((z(k)*Im-A)\K); % eq. 4 22 | end 23 | -------------------------------------------------------------------------------- /libs/ssgc_v1.0/iss_PWGC.m: -------------------------------------------------------------------------------- 1 | function F = iss_PWGC(A,C,K,V) 2 | 3 | % Compute pairwise-conditional time-domain GCs for a state space model from 4 | % innovations form parameters (eq. 9 in the reference article). 5 | % 6 | % A,C,K,V - innovations form state space parameters 7 | % 8 | % F - pairwise-conditional GCs ("causal graph") 9 | % 10 | % Calculates the GCs F(i1,i2) from y_i2 -> y_i1 conditional on y_i3, where i3 is 11 | % the multi-index of the remaining variables in the model, for all pairs of 12 | % (scalar) indices i1, i2. Note that F will not in general be symmetric, and 13 | % will have NaNs on the diagonal. 14 | 15 | [m,m1] = size(A); assert(m1 == m); 16 | [n,m1] = size(C); assert(m1 == m); 17 | [m1,n1] = size(K); assert(n1 == n && m1 == m); 18 | [n1,n2] = size(V); assert(n1 == n && n2 == n); 19 | 20 | F = nan(n); 21 | 22 | KVSQRT = K*chol(V,'lower'); 23 | KVK = KVSQRT*KVSQRT'; 24 | LV = log(diag(V)); 25 | 26 | for i2 = 1:n 27 | oi2 = [1:i2-1 i2+1:n]; % omit i2 28 | 29 | [~,VR,rep] = ss2iss(A,C(oi2,:),KVK,V(oi2,oi2),K*V(:,oi2)); % reduced model innovations covariance 30 | if rep < 0 31 | if rep == -1, warning('DARE: eigenvalues on/near unit circle for source %d',i2); 32 | elseif rep == -2, warning('DARE: couldn''t find stablising solution for source node %d',i2); 33 | end 34 | continue 35 | end 36 | if rep > sqrt(eps), warning('DARE: there were accuracy issues (relative residual = %e) for source %d',rep,i2); 37 | continue 38 | end 39 | 40 | F(oi2,i2) = log(diag(VR))-LV(oi2); 41 | end 42 | -------------------------------------------------------------------------------- /libs/ssgc_v1.0/iss_SPWGC.m: -------------------------------------------------------------------------------- 1 | function f = iss_SPWGC(A,C,K,V,z) 2 | 3 | % Compute pairwise-conditional frequency-domain GCs for a state space model from 4 | % innovations form parameters (eqs. 11 and 12-15 in the reference article). 5 | % 6 | % A,C,K,V - innovations form state space parameters 7 | % z - a vector of points on the unit circle in the complex plane 8 | % 9 | % f - pairwise-conditional spectral GCs ("frequency-domain causal graph") 10 | % 11 | % Calculates the spectral GCs f(z,i1,i2) from y_i2 -> y_i1 conditional on y_i3, 12 | % where i3 is the multi-index of the remaining variables in the model, for all 13 | % pairs of (scalar) indices i1, i2. Note that for fixed z, f will not in general 14 | % be symmetric, and will have NaNs on the diagonal. 15 | 16 | [m,m1] = size(A); assert(m1 == m); 17 | [n,m1] = size(C); assert(m1 == m); 18 | [m1,n1] = size(K); assert(n1 == n && m1 == m); 19 | [n1,n2] = size(V); assert(n1 == n && n2 == n); 20 | z = z(:); 21 | 22 | h = length(z); 23 | f = nan(n,n,h); 24 | 25 | H = iss_MA(A,C,K,z); 26 | KVSQRT = K*chol(V,'lower'); 27 | KVK = KVSQRT*KVSQRT'; 28 | 29 | % for efficiency (in time if not memory) we pre-compute partial covariances 30 | PV = zeros(n-1,n-1,n); 31 | for i1 = 1:n 32 | oi1 = [1:i1-1 i1+1:n]; % omit i1 33 | PV(:,:,i1) = parcovar(V,oi1,i1); 34 | end 35 | 36 | for i2 = 1:n 37 | oi2 = [1:i2-1 i2+1:n]; % omit i2 38 | 39 | CR = C(oi2,:); 40 | [KR,VR,rep] = ss2iss(A,CR,KVK,V(oi2,oi2),K*V(:,oi2)); % reduced model Kalman gain and innovations covariance 41 | if rep < 0 42 | if rep == -1, warning('DARE: eigenvalues on/near unit circle for source node %d',i2); 43 | elseif rep == -2, warning('DARE: couldn''t find stablising solution for source node %d',i2); 44 | end 45 | continue 46 | end 47 | if rep > sqrt(eps), warning('DARE: there were accuracy issues (relative residual = %e) for source node %d',rep,i2); 48 | continue 49 | end 50 | BR = iss_AR(A,CR,KR,z); 51 | 52 | for i1R = 1:n-1; 53 | i1 = oi2(i1R); 54 | oi1 = [1:i1-1 i1+1:n]; % omit i1 55 | 56 | SR = VR(i1R,i1R); % reduced model spectrum is flat! 57 | LSR = log(SR); 58 | 59 | for k = 1:h 60 | HR = BR(i1R,:,k)*H(oi2,oi1,k); % eqs. 13, 15 61 | f(i1,i2,k) = LSR - log(SR-real(HR*PV(:,:,i1)*HR')); % eq. 14 62 | end 63 | end 64 | end 65 | -------------------------------------------------------------------------------- /libs/ssgc_v1.0/iss_cpsd.m: -------------------------------------------------------------------------------- 1 | function S = iss_cpsd(H,V) 2 | 3 | % Calculate cross-power spectral density from transfer function and innovations 4 | % covariance matrix (eq. 6 in the reference article). 5 | % 6 | % H - transfer function 7 | % V - innovations covariance matrix 8 | % 9 | % S - cross-power spectral density array (last dimension is frequency) 10 | % 11 | % You may calculate the cpsd from innovations form parameters A,C,K,V by calling 12 | % 13 | % S = iss_cpsd(iss_MA(A,C,K,z),V); 14 | 15 | [n,n1,h] = size(H); assert(n1 == n); 16 | [n1,n2] = size(V); assert(n1 == n && n2 == n); 17 | 18 | S = zeros(n,n,h); 19 | SQRTV = chol(V,'lower'); 20 | for k = 1:h 21 | Hk = H(:,:,k)*SQRTV; 22 | S(:,:,k) = Hk*Hk'; 23 | end 24 | -------------------------------------------------------------------------------- /libs/ssgc_v1.0/iss_ds.m: -------------------------------------------------------------------------------- 1 | function [Ak,Kk,Vk] = iss_ds(A,C,K,V,k) 2 | 3 | % Calculate innovations form state space parameters for a downsampled state 4 | % space model 5 | % 6 | % A,C,K,V - innovations form state space parameters 7 | % k - downsample factor (positive integer) 8 | % 9 | % Ak,Kk,Vk - innovations form state space parameters for downsampled model 10 | % 11 | % See V. Solo, arXiv:1501.04663v1, Sec. 4. 12 | 13 | [m,m1] = size(A); assert(m1 == m); 14 | [n,m1] = size(C); assert(m1 == m); 15 | [m1,n1] = size(K); assert(n1 == n && m1 == m); 16 | [n1,n2] = size(V); assert(n1 == n && n2 == n); 17 | assert(isscalar(k) && isnumeric(k) && k == floor(k) && k > 0); 18 | 19 | if k == 1 % nothing to do 20 | Ak = A; 21 | Kk = K; 22 | Vk = V; 23 | return 24 | end 25 | 26 | Ak = eye(m); % Ak = A^0 27 | AkKSQRTV = K*chol(V,'lower'); 28 | Qk = AkKSQRTV*AkKSQRTV'; 29 | for p = 1:k-1 30 | Ak = Ak*A; % Ak = A^p 31 | AkKSQRTV = Ak*AkKSQRTV; 32 | Qk = Qk + AkKSQRTV*AkKSQRTV'; 33 | end 34 | Sk = Ak*K*V; % Ak = A^(k-1) 35 | Ak = Ak*A; % Ak = A^k 36 | 37 | % We now have general form state space parameters for the downsampled model 38 | % (note: Ck = C and Rk = V for any k). We solve the DARE to get remaining 39 | % innovations form parameters. 40 | 41 | [Kk,Vk] = ss2iss(Ak,C,Qk,V,Sk); 42 | -------------------------------------------------------------------------------- /libs/ssgc_v1.0/iss_gen.m: -------------------------------------------------------------------------------- 1 | function [y,z,e] = iss_gen(A,C,K,V,T) 2 | 3 | % Generate a realization of a state space process with Gaussian innovations from 4 | % innovations form state space parameters. 5 | % 6 | % A,C,K,V - innovations form state space parameters 7 | % T - sequence length (time steps) 8 | % 9 | % y - observation time series 10 | % z - state time series 11 | % e - innovations time series 12 | % 13 | % Time series y,z,e are matrices of dimensions (number of variables) x (number 14 | % of time steps). 15 | % 16 | % Note that we need rhoA < 1 for a stable process and rhoB < 1 for a minimum 17 | % phase process, where rhoA is the spectral norm of A and rhoB the spectral norm 18 | % of B = A-K*C (see routine specnorm.m). V must be symmetric positive-definite. 19 | % 20 | % The returned time series should be truncated at the beginning if an 21 | % (approximately) stationary process is required. Since transients for the 22 | % stable AR(1) state space process z decay exponentially at a rate rhoA, a 23 | % reasonable number of time steps to truncate is of the order 24 | % log(eps)/log(rhoA). 25 | 26 | [m,m1] = size(A); assert(m1 == m); 27 | [n,m1] = size(C); assert(m1 == m); 28 | [m1,n1] = size(K); assert(n1 == n && m1 == m); 29 | [n1,n2] = size(V); assert(n1 == n && n2 == n); 30 | 31 | % Gaussian white noise innovations with covariance matrix V 32 | 33 | e = chol(V,'lower')*randn(n,T); 34 | 35 | % z is AR(1) with residuals K*e 36 | 37 | z = K*e; 38 | for t = 2:T 39 | z(:,t) = A*z(:,t-1) + z(:,t); 40 | end 41 | 42 | % Construct observations 43 | 44 | y = C*z + e; 45 | 46 | 47 | -------------------------------------------------------------------------------- /libs/ssgc_v1.0/iss_rand.m: -------------------------------------------------------------------------------- 1 | function [A,C,K,V] = iss_rand(n,m,rhoa,dis) 2 | 3 | % Generate some random stable and minimum-phase normally distributed innovations 4 | % form parameters. 5 | % 6 | % n - observation variable dimension 7 | % m - state dimension 8 | % rhoa - state transition matrix spectral norm 9 | % dis - display spectral norm of pencil of AR transition matrices 10 | % 11 | % A,C,K - innovations form state space parameters 12 | % 13 | % We need rhoa < 1 for a stable model. This routine creates A,K,C as random 14 | % Gaussian matrices, and scales A so that its spectral norm is equal to rhoa. C 15 | % and K are then each scaled by a factor sqrt(r), so that the AR transition 16 | % matrix A - r*K*C has spectral norm < 1, thereby ensuring minimum phase. (The 17 | % subroutine speclim is used to identify minimum and maximum r between which 18 | % minimum phase holds, and r is chosen uniformly from this range.) 19 | 20 | assert(rhoa < 1); 21 | 22 | if nargin < 4 || isempty(dis), dis = false; end 23 | 24 | A = randn(m); 25 | A = (rhoa/specnorm(A))*A; 26 | C = randn(n,m); 27 | K = randn(m,n); 28 | 29 | M = K*C; 30 | rmin = speclim(A,M,-1,0); 31 | rmax = speclim(A,M,+1,0); 32 | 33 | r = rmin + (rmax-rmin)*rand; % uniform on [rmin,rmax] 34 | sqrtr = sqrt(abs(r)); 35 | C = sqrtr*C; 36 | K = sign(r)*sqrtr*K; 37 | 38 | if dis 39 | nr = 1000; 40 | ramax = 1.1*max(rmax,-rmin); 41 | rr = linspace(-ramax,ramax,nr)'; 42 | rrhob = zeros(nr,1); 43 | for i = 1:nr 44 | rrhob(i) = specnorm(A-rr(i)*M); 45 | end 46 | rholim = [0.9*min(rrhob) 1.1*max(rrhob)]; 47 | plot(rr,rrhob); 48 | xlim([-ramax,ramax]); 49 | ylim(rholim); 50 | line([-ramax,ramax],[1 1],'Color','k'); 51 | line([0 0],rholim,'Color','r'); 52 | line([r r],rholim,'Color','g'); 53 | xlabel('r'); 54 | ylabel('rho'); 55 | legend('rho(B)'); 56 | title(sprintf('rho(A) = %g, rho(B) = %g',rhoa,specnorm(A-r*M))); 57 | end 58 | 59 | function r = speclim(A,M,r1,r2) 60 | 61 | assert(specnorm(A-r1*M) > 1 && specnorm(A-r2*M) < 1); 62 | while true 63 | r = (r1+r2)/2; 64 | rho = specnorm(A-r*M); 65 | if rho > 1, r1 = r; else r2 = r; end 66 | if abs(r1-r2) < eps, break; end 67 | end 68 | 69 | -------------------------------------------------------------------------------- /libs/ssgc_v1.0/parcovar.m: -------------------------------------------------------------------------------- 1 | function PV = parcovar(V,i,k) 2 | 3 | % Compute partial covariance PV = V(i,i) - V(i,k) * V(k,k)^{-1} * V(k,i); used 4 | % in spectral GC calculations (see eqs. 11 and 12-15 in the reference article). 5 | % 6 | % V - a (symmetric, positive-definite) covariance matrix 7 | % i,k - non-overlapping multi-indices (vectors of integers) 8 | % 9 | % PV - partial covariance matrix 10 | 11 | if isscalar(k) 12 | W = sqrt(V(k,k))\V(k,i); % for 1-dim target no matrix division required 13 | else 14 | opts.LT = true; % we can use the more efficient linsolve (rather than rdivide) 15 | W = linsolve(chol(V(k,k),'lower'),V(k,i),opts); % here, since we know the Cholesky factor is lower triangular 16 | end 17 | PV = V(i,i)-W'*W; 18 | -------------------------------------------------------------------------------- /libs/ssgc_v1.0/specnorm.m: -------------------------------------------------------------------------------- 1 | function rho = specnorm(ARA) 2 | 3 | % Calculate spectral norm (maximum absolute eigenvalue of the associated AR(1) 4 | % transition matrix) for a vector autoregressive model. 5 | % 6 | % ARA - AR coefficients array 7 | % 8 | % rho - spectral norm of ARA 9 | % 10 | % ARA is n x n x p where where n is the dimension of the model and p the model 11 | % order, so that ARA(:,:,k) is the k-lag AR coefficients matrix. The model is 12 | % stable iff rho < 1. 13 | % 14 | % Note that for a state space model in innovations form with parameters (A,C,K), 15 | % the model is stable iff specnorm(A) < 1, and minimum-phase iff specnorm(B) < 16 | % 1, where B = A - K*C. 17 | 18 | [n,n1,p] = size(ARA); assert(n1 == n); % n is dimensionality, p is model order 19 | 20 | if p > 1 % set up associated AR(1) matrix 21 | ARA = [reshape(ARA,n,p*n); eye((p-1)*n) zeros((p-1)*n,n)]; 22 | end 23 | rho = max(abs(eig(ARA,'nobalance'))); 24 | -------------------------------------------------------------------------------- /private/getatlaslist.m: -------------------------------------------------------------------------------- 1 | function [atlasstr, atlas] = getatlaslist(fileName) 2 | 3 | data = load('-mat', fileName); 4 | 5 | atlasstr = {}; 6 | atlas = {}; 7 | for iAtlas = 1:length(data.Atlas) 8 | if ~isempty(data.Atlas(iAtlas).Scouts) && ~strcmpi(data.Atlas(iAtlas).Name, 'Structures') 9 | atlasstr{end+1} = [data.Atlas(iAtlas).Name ' (' int2str(length(data.Atlas(iAtlas).Scouts)) ' ROIs)' ]; 10 | atlas{ end+1} = data.Atlas(iAtlas).Name; 11 | end 12 | end -------------------------------------------------------------------------------- /raw_example/NDARAA948VFH/raw.set: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/raw_example/NDARAA948VFH/raw.set -------------------------------------------------------------------------------- /resources/FC_MIM_cortex_left.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/resources/FC_MIM_cortex_left.jpg -------------------------------------------------------------------------------- /resources/FC_MIM_cortex_right.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/resources/FC_MIM_cortex_right.jpg -------------------------------------------------------------------------------- /resources/FC_MIM_cortex_seed49_left.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/resources/FC_MIM_cortex_seed49_left.jpg -------------------------------------------------------------------------------- /resources/FC_MIM_cortex_seed50_right.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/resources/FC_MIM_cortex_seed50_right.jpg -------------------------------------------------------------------------------- /resources/FC_MIM_matrix.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/resources/FC_MIM_matrix.png -------------------------------------------------------------------------------- /resources/FC_MIM_matrix_groupedhems.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/resources/FC_MIM_matrix_groupedhems.png -------------------------------------------------------------------------------- /resources/FC_MIM_matrix_groupedhems_left.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/resources/FC_MIM_matrix_groupedhems_left.jpg -------------------------------------------------------------------------------- /resources/FC_MIM_matrix_left.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/resources/FC_MIM_matrix_left.jpg -------------------------------------------------------------------------------- /resources/FC_MIM_matrix_left.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/resources/FC_MIM_matrix_left.png -------------------------------------------------------------------------------- /resources/FC_MIM_matrix_lefthem_left.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/resources/FC_MIM_matrix_lefthem_left.jpg -------------------------------------------------------------------------------- /resources/FC_MIM_matrix_right.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/resources/FC_MIM_matrix_right.jpg -------------------------------------------------------------------------------- /resources/FC_MIM_matrix_righthem_right.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/resources/FC_MIM_matrix_righthem_right.jpg -------------------------------------------------------------------------------- /resources/power_barplot_left.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/resources/power_barplot_left.jpg -------------------------------------------------------------------------------- /resources/power_barplot_right.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/resources/power_barplot_right.jpg -------------------------------------------------------------------------------- /resources/power_cortex_left.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/resources/power_cortex_left.jpg -------------------------------------------------------------------------------- /resources/power_cortex_right.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/roiconnect/7df8313de38c94f6ce0d1b6a2bf821f8204ea2d6/resources/power_cortex_right.jpg -------------------------------------------------------------------------------- /roi_getpower.m: -------------------------------------------------------------------------------- 1 | % roi_getpower() - compute power of a given ROI (region of interest) 2 | % 3 | % Usage: 4 | % [power, powernorm] = roi_getpower(roi_data, ind_roi); 5 | % 6 | % Inputs: 7 | % roi_data - [times x voxels x trials] source activity data 8 | % ind_roi - indices of voxels for the ROI 9 | 10 | % Copyright (C) Arnaud Delorme, arnodelorme@gmail.com 11 | % 12 | % Redistribution and use in source and binary forms, with or without 13 | % modification, are permitted provided that the following conditions are met: 14 | % 15 | % 1. Redistributions of source code must retain the above copyright notice, 16 | % this list of conditions and the following disclaimer. 17 | % 18 | % 2. Redistributions in binary form must reproduce the above copyright notice, 19 | % this list of conditions and the following disclaimer in the documentation 20 | % and/or other materials provided with the distribution. 21 | % 22 | % THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 23 | % AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 24 | % IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 25 | % ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 26 | % LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 27 | % CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 28 | % SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 29 | % INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 30 | % CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 31 | % ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 32 | % THE POSSIBILITY OF SUCH DAMAGE. 33 | 34 | function [source_roi_power, source_roi_power_norm] = roi_getpower(source_voxel_data, ind_roi) 35 | 36 | data_ = source_voxel_data(:, ind_roi, :); 37 | source_roi_power = sum(var(data_(:, :)))'; 38 | source_roi_power_norm = source_roi_power/length(ind_roi); 39 | 40 | -------------------------------------------------------------------------------- /roi_neighbor.m: -------------------------------------------------------------------------------- 1 | % distanceMat = neighbormat( EEG(1).roi.cortex.Vertices, EEG(1).roi.cortex.Atlas.Scouts, 'distance', 50); figure; imagesc(distanceMat); 2 | % distanceMat = neighbormat( EEG(1).roi.cortex.Vertices, EEG(1).roi.cortex.Atlas.Scouts, 'pairwise', 15); figure; imagesc(distanceMat); 3 | function distanceMat = neighbormat(vertices, scouts, method, threshold) 4 | 5 | if nargin < 3 6 | method = 'distance'; 7 | threshold = 40; 8 | end 9 | distanceMat = ones(length(scouts), length(scouts))*1000; 10 | 11 | if strcmpi(method, 'distance') 12 | % compute center 13 | centers = zeros(3, length(scouts)); 14 | for iScout = 1:length(scouts) 15 | centers(:,iScout) = mean(vertices(scouts(iScout).Vertices,:),1); 16 | end 17 | 18 | for iScout1 = 1:length(scouts) 19 | for iScout2 = iScout1+1:length(scouts) 20 | distanceMat(iScout1, iScout2) = sqrt(sum((centers(:,iScout1) - centers(:,iScout2)).^2)); 21 | distanceMat(iScout2, iScout1) = sqrt(sum((centers(:,iScout1) - centers(:,iScout2)).^2)); 22 | end 23 | end 24 | distanceMat = distanceMat < threshold; 25 | else 26 | verticesTmp = cell(1, length(scouts)); 27 | for iScout = 1:length(scouts) 28 | verticesTmp{iScout} = vertices(scouts(iScout).Vertices,:); 29 | end 30 | 31 | for iScout1 = 1:length(scouts) 32 | for iScout2 = iScout1+1:length(scouts) 33 | minDist = zeros(1, length(verticesTmp{iScout1})); 34 | for iVertice = 1: length(verticesTmp{iScout1}) 35 | diffsq = bsxfun(@minus, verticesTmp{iScout2}, verticesTmp{iScout1}(iVertice,:)).^2; 36 | minDist(iVertice) = min(sqrt(sum(diffsq,2))); 37 | end 38 | distanceMat(iScout1, iScout2) = min(minDist); 39 | distanceMat(iScout2, iScout1) = distanceMat(iScout1, iScout2); 40 | end 41 | end 42 | distanceMat = distanceMat < threshold; 43 | end 44 | 45 | -------------------------------------------------------------------------------- /test_pipes/cmp_roi_selection.m: -------------------------------------------------------------------------------- 1 | % Function to test if the ROI selection works by comparing the values of the respective data arrays. 2 | % Let 'n_roisel' be the number of selected ROIs. Used in 'test_roi_selection'. 3 | % 4 | % Inputs: 5 | % roi_selection - [cell array of integers] Cell array of ROI indices {1, 2, 3, ...} indicating for which regions (ROIs) connectivity was computed. 6 | % conn1 - (nfreq, nROI, nROI) connectivity tensor, original data array without ROI selection 7 | % conn2 - (nfreq, n_roisel, n_roisel) connectivity tensor, data array with ROI selection (connectivity was computed for a selected 8 | % number of ROIs) 9 | 10 | function cmp_roi_selection(roi_selection, conn1, conn2) 11 | % generate all possible combinations of ROI combinations 12 | 13 | [p,q] = meshgrid(cell2mat(roi_selection), cell2mat(roi_selection)); 14 | roi_pairs = [p(:) q(:)]; 15 | 16 | roi_inds = 1:1:length(roi_selection); 17 | [p,q] = meshgrid(roi_inds, roi_inds); 18 | roi_inds_pairs = [p(:) q(:)]; 19 | 20 | for ipair = 1:size(roi_pairs, 1) 21 | cmp1 = conn1(roi_pairs(ipair, 1), roi_pairs(ipair, 2)); 22 | cmp2 = conn2(roi_inds_pairs(ipair, 1), roi_inds_pairs(ipair, 2)); 23 | if ~isequal(cmp1, cmp2) 24 | disp(cmp1) 25 | disp(cmp2) 26 | fprintf('Values for the ROI combination [%d %d] are not exactly the same.\n', roi_pairs(ipair, :)) 27 | end 28 | end 29 | end -------------------------------------------------------------------------------- /test_pipes/test_brainplots_dkatlas.m: -------------------------------------------------------------------------------- 1 | % Test cortical surface topographies with different parameters. Here, the Desikan-Killiany atlas with 68 ROIs is used as the source model. 2 | %% Run pipeline 3 | clear 4 | eeglab 5 | 6 | eeglabp = fileparts(which('eeglab.m')); 7 | EEG = pop_loadset('filename','eeglab_data_epochs_ica.set','filepath',fullfile(eeglabp, 'sample_data/')); 8 | EEG = pop_resample( EEG, 100); 9 | EEG = pop_epoch( EEG, { }, [-0.5 1.5], 'newname', 'EEG Data epochs epochs', 'epochinfo', 'yes'); 10 | EEG = pop_select( EEG, 'trial',1:30); 11 | [ALLEEG, EEG, CURRENTSET] = eeg_store(ALLEEG, EEG); 12 | eeglab redraw; 13 | 14 | EEG = pop_dipfit_settings( EEG, 'hdmfile',fullfile(eeglabp, 'plugins','dipfit','standard_BEM','standard_vol.mat'), ... 15 | 'coordformat','MNI','mrifile',fullfile(eeglabp, 'plugins','dipfit','standard_BEM','standard_mri.mat'),... 16 | 'chanfile',fullfile(eeglabp, 'plugins','dipfit','standard_BEM','elec', 'standard_1005.elc'),... 17 | 'coord_transform',[0.83215 -15.6287 2.4114 0.081214 0.00093739 -1.5732 1.1742 1.0601 1.1485] ,'chansel',[1:32] ); 18 | 19 | EEG = pop_leadfield(EEG, 'sourcemodel',fullfile(eeglabp,'functions','supportfiles','head_modelColin27_5003_Standard-10-5-Cap339.mat'), ... 20 | 'sourcemodel2mni',[0 -24 -45 0 0 -1.5708 1000 1000 1000] ,'downsample',1); 21 | 22 | EEG = pop_roi_activity(EEG, 'leadfield',EEG.dipfit.sourcemodel,'model','LCMV','modelparams',{0.05},'atlas','LORETA-Talairach-BAs','nPCA',3, 'chansel', EEG.dipfit.chansel); 23 | EEG = pop_roi_connect(EEG, 'methods', {'MIM'}); 24 | 25 | %% Plot brain plot with different parameters 26 | % brain plot without any filters 27 | pop_roi_connectplot(EEG, 'measure', 'mim', 'plotcortex', 'on'); 28 | 29 | % frequency band specified 30 | pop_roi_connectplot(EEG, 'measure', 'mim', 'plotcortex', 'on', 'freqrange', [8 13]); 31 | 32 | % seed voxel specified 33 | pop_roi_connectplot(EEG, 'measure', 'mim', 'plotcortex', 'on', 'plotcortexseedregion', 49); -------------------------------------------------------------------------------- /test_pipes/test_brainplots_loretaatlas.m: -------------------------------------------------------------------------------- 1 | % Test cortical surface topographies with different parameters. Here, the LORETA-Talairach-BAs atlas with 90 ROIs is used as the source model. 2 | %% Run pipeline 3 | clear 4 | eeglab 5 | 6 | eeglabp = fileparts(which('eeglab.m')); 7 | EEG = pop_loadset('filename','eeglab_data_epochs_ica.set','filepath',fullfile(eeglabp, 'sample_data/')); 8 | EEG = pop_resample( EEG, 100); 9 | EEG = pop_epoch( EEG, { }, [-0.5 1.5], 'newname', 'EEG Data epochs epochs', 'epochinfo', 'yes'); 10 | EEG = pop_select( EEG, 'trial',1:30); 11 | [ALLEEG, EEG, CURRENTSET] = eeg_store(ALLEEG, EEG); 12 | eeglab redraw; 13 | 14 | EEG = pop_dipfit_settings( EEG, 'hdmfile',fullfile(eeglabp, 'plugins','dipfit','standard_BEM','standard_vol.mat'), ... 15 | 'coordformat','MNI','mrifile',fullfile(eeglabp, 'plugins','dipfit','standard_BEM','standard_mri.mat'),... 16 | 'chanfile',fullfile(eeglabp, 'plugins','dipfit','standard_BEM','elec', 'standard_1005.elc'),... 17 | 'coord_transform',[0.83215 -15.6287 2.4114 0.081214 0.00093739 -1.5732 1.1742 1.0601 1.1485] ,'chansel',[1:32] ); 18 | 19 | EEG = pop_leadfield(EEG, 'sourcemodel',fullfile(eeglabp,'plugins','dipfit','LORETA-Talairach-BAs.mat'), ... 20 | 'sourcemodel2mni',[0 -24 -45 0 0 -1.5708 1000 1000 1000] ,'downsample',1); 21 | 22 | EEG = pop_roi_activity(EEG, 'leadfield',EEG.dipfit.sourcemodel,'model','LCMV','modelparams',{0.05},'atlas','LORETA-Talairach-BAs','nPCA',3, 'chansel', EEG.dipfit.chansel); 23 | EEG = pop_roi_connect(EEG, 'methods', {'MIM'}); 24 | 25 | %% Plot brain plot with different parameters 26 | % brain plot without any filters 27 | pop_roi_connectplot(EEG, 'measure', 'mim', 'plotcortex', 'on'); 28 | 29 | % frequency band specified 30 | pop_roi_connectplot(EEG, 'measure', 'mim', 'plotcortex', 'on', 'freqrange', [8 13]); 31 | 32 | % seed voxel specified 33 | pop_roi_connectplot(EEG, 'measure', 'mim', 'plotcortex', 'on', 'plotcortexseedregion', 49); -------------------------------------------------------------------------------- /test_pipes/test_flex_epochlength.m: -------------------------------------------------------------------------------- 1 | % Test pipeline with an epoch length other than 2 seconds (test with 1 second epoch length). 2 | %% Run pipeline 3 | clear 4 | eeglab 5 | 6 | eeglabp = fileparts(which('eeglab.m')); 7 | EEG = pop_loadset('filename','eeglab_data_epochs_ica.set','filepath',fullfile(eeglabp, 'sample_data/')); 8 | EEG = pop_resample( EEG, 100); 9 | EEG = pop_epoch( EEG, { }, [-0.5 0.5], 'newname', 'EEG Data epochs epochs', 'epochinfo', 'yes'); 10 | EEG = pop_select( EEG, 'trial',1:30); 11 | [ALLEEG, EEG, CURRENTSET] = eeg_store(ALLEEG, EEG); 12 | eeglab redraw; 13 | 14 | EEG = pop_dipfit_settings( EEG, 'hdmfile',fullfile(eeglabp, 'plugins','dipfit','standard_BEM','standard_vol.mat'), ... 15 | 'coordformat','MNI','mrifile',fullfile(eeglabp, 'plugins','dipfit','standard_BEM','standard_mri.mat'),... 16 | 'chanfile',fullfile(eeglabp, 'plugins','dipfit','standard_BEM','elec', 'standard_1005.elc'),... 17 | 'coord_transform',[0.83215 -15.6287 2.4114 0.081214 0.00093739 -1.5732 1.1742 1.0601 1.1485] ,'chansel',[1:32] ); 18 | 19 | EEG = pop_leadfield(EEG, 'sourcemodel',fullfile(eeglabp,'functions','supportfiles','head_modelColin27_5003_Standard-10-5-Cap339.mat'), ... 20 | 'sourcemodel2mni',[0 -24 -45 0 0 -1.5708 1000 1000 1000] ,'downsample',1); 21 | 22 | EEG = pop_roi_activity(EEG, 'leadfield',EEG.dipfit.sourcemodel,'model','LCMV','modelparams',{0.05},'atlas','LORETA-Talairach-BAs','nPCA',3, 'chansel', EEG.dipfit.chansel); 23 | 24 | measures = { 'MIM' 'wPLI' }; 25 | for iMeasure = 1:length(measures) 26 | tic 27 | EEG = pop_roi_connect(EEG, 'methods', measures(iMeasure)); 28 | t(iMeasure) = toc; 29 | end 30 | 31 | 32 | -------------------------------------------------------------------------------- /test_pipes/test_fooof.m: -------------------------------------------------------------------------------- 1 | % Test FOOOF implementation. Requires prior FOOOF installation: https://github.com/fooof-tools/fooof_mat 2 | %% Run pipeline 3 | clear 4 | eeglab 5 | 6 | eeglabp = fileparts(which('eeglab.m')); 7 | EEG = pop_loadset('filename','eeglab_data_epochs_ica.set','filepath',fullfile(eeglabp, 'sample_data/')); 8 | EEG = pop_resample( EEG, 100); 9 | EEG = pop_epoch( EEG, { }, [-0.5 1.5], 'newname', 'EEG Data epochs epochs', 'epochinfo', 'yes'); 10 | EEG = pop_select( EEG, 'trial',1:30); 11 | [ALLEEG, EEG, CURRENTSET] = eeg_store(ALLEEG, EEG); 12 | eeglab redraw; 13 | 14 | EEG = pop_dipfit_settings( EEG, 'hdmfile',fullfile(eeglabp, 'plugins','dipfit','standard_BEM','standard_vol.mat'), ... 15 | 'coordformat','MNI','mrifile',fullfile(eeglabp, 'plugins','dipfit','standard_BEM','standard_mri.mat'),... 16 | 'chanfile',fullfile(eeglabp, 'plugins','dipfit','standard_BEM','elec', 'standard_1005.elc'),... 17 | 'coord_transform',[0.83215 -15.6287 2.4114 0.081214 0.00093739 -1.5732 1.1742 1.0601 1.1485] ,'chansel',[1:32] ); 18 | 19 | EEG = pop_leadfield(EEG, 'sourcemodel',fullfile(eeglabp,'functions','supportfiles','head_modelColin27_5003_Standard-10-5-Cap339.mat'), ... 20 | 'sourcemodel2mni',[0 -24 -45 0 0 -1.5708 1000 1000 1000] ,'downsample',1); 21 | 22 | % compute fooof 23 | EEG = pop_roi_activity(EEG, 'leadfield',EEG.dipfit.sourcemodel,'model','LCMV','modelparams',{0.05},'atlas','LORETA-Talairach-BAs','nPCA',3, 'fooof', 'on', 'fooof_frange', [1 30], 'chansel', EEG.dipfit.chansel); 24 | 25 | % access values 26 | results = EEG.roi.fooof_results; 27 | 28 | 29 | -------------------------------------------------------------------------------- /test_pipes/test_largebarplot_dkatlas.m: -------------------------------------------------------------------------------- 1 | % Test region-to-region power bar plot. Here, the Desikan-Killiany atlas with 68 ROIs is used as the source model. 2 | %% Run pipeline 3 | clear 4 | eeglab 5 | 6 | eeglabp = fileparts(which('eeglab.m')); 7 | EEG = pop_loadset('filename','eeglab_data_epochs_ica.set','filepath',fullfile(eeglabp, 'sample_data/')); 8 | EEG = pop_resample( EEG, 100); 9 | EEG = pop_epoch( EEG, { }, [-0.5 1.5], 'newname', 'EEG Data epochs epochs', 'epochinfo', 'yes'); 10 | EEG = pop_select( EEG, 'trial',1:30); 11 | [ALLEEG, EEG, CURRENTSET] = eeg_store(ALLEEG, EEG); 12 | eeglab redraw; 13 | 14 | EEG = pop_dipfit_settings( EEG, 'hdmfile',fullfile(eeglabp, 'plugins','dipfit','standard_BEM','standard_vol.mat'), ... 15 | 'coordformat','MNI','mrifile',fullfile(eeglabp, 'plugins','dipfit','standard_BEM','standard_mri.mat'),... 16 | 'chanfile',fullfile(eeglabp, 'plugins','dipfit','standard_BEM','elec', 'standard_1005.elc'),... 17 | 'coord_transform',[0.83215 -15.6287 2.4114 0.081214 0.00093739 -1.5732 1.1742 1.0601 1.1485] ,'chansel',[1:32] ); 18 | 19 | EEG = pop_leadfield(EEG, 'sourcemodel',fullfile(eeglabp,'functions','supportfiles','head_modelColin27_5003_Standard-10-5-Cap339.mat'), ... 20 | 'sourcemodel2mni',[0 -24 -45 0 0 -1.5708 1000 1000 1000] ,'downsample',1); 21 | 22 | EEG = pop_roi_activity(EEG, 'leadfield',EEG.dipfit.sourcemodel,'model','LCMV','modelparams',{0.05},'atlas','LORETA-Talairach-BAs','nPCA',3, 'chansel', EEG.dipfit.chansel); 23 | tic 24 | EEG = pop_roi_connect(EEG, 'methods', {'MIM'}); 25 | toc 26 | 27 | %% Plot barplot 28 | % plot barplot with specified frequency band 29 | % pop_roi_connectplot(EEG, 'measure', 'roipsd', 'plotcortex', 'off', 'plotbarplot', 'on', 'freqrange', [4 8]); 30 | pop_roi_connectplot(EEG, 'measure', 'MIM', 'plotcortex', 'off', 'plotmatrix', 'on', 'freqrange', [4 8]); -------------------------------------------------------------------------------- /test_pipes/test_matrixplots_brainregions.m: -------------------------------------------------------------------------------- 1 | % Test region-to-region FC matrices (MIM) with different parameters. Here, the grouped LORETA-Talairach-BAs ('Brain-Regions') atlas with 34 ROIs is used as the source model. 2 | %% Run pipeline 3 | clear 4 | eeglab 5 | 6 | eeglabp = fileparts(which('eeglab.m')); 7 | EEG = pop_loadset('filename','eeglab_data_epochs_ica.set','filepath',fullfile(eeglabp, 'sample_data/')); 8 | EEG = pop_resample( EEG, 100); 9 | EEG = pop_epoch( EEG, { }, [-0.5 1.5], 'newname', 'EEG Data epochs epochs', 'epochinfo', 'yes'); 10 | EEG = pop_select( EEG, 'trial',1:30); 11 | [ALLEEG, EEG, CURRENTSET] = eeg_store(ALLEEG, EEG); 12 | eeglab redraw; 13 | 14 | EEG = pop_dipfit_settings( EEG, 'hdmfile',fullfile(eeglabp, 'plugins','dipfit','standard_BEM','standard_vol.mat'), ... 15 | 'coordformat','MNI','mrifile',fullfile(eeglabp, 'plugins','dipfit','standard_BEM','standard_mri.mat'),... 16 | 'chanfile',fullfile(eeglabp, 'plugins','dipfit','standard_BEM','elec', 'standard_1005.elc'),... 17 | 'coord_transform',[0.83215 -15.6287 2.4114 0.081214 0.00093739 -1.5732 1.1742 1.0601 1.1485] ,'chansel',[1:32] ); 18 | 19 | EEG = pop_leadfield(EEG, 'sourcemodel',fullfile(eeglabp,'plugins','dipfit','LORETA-Talairach-BAs.mat'), ... 20 | 'sourcemodel2mni',[0 -24 -45 0 0 -1.5708 1000 1000 1000] ,'downsample',1); 21 | 22 | EEG = pop_roi_activity(EEG, 'leadfield',EEG.dipfit.sourcemodel,'model','LCMV','modelparams',{0.05},'atlas','Brain-Regions','nPCA',3, 'chansel', EEG.dipfit.chansel); 23 | EEG = pop_roi_connect(EEG, 'methods', {'MIM'}); 24 | 25 | %% Plot matrix with different parameters 26 | % matrix without any filters 27 | pop_roi_connectplot(EEG, 'measure', 'mim', 'plotcortex', 'off', 'plotmatrix', 'on'); 28 | 29 | % group by hemispheres 30 | pop_roi_connectplot(EEG, 'measure', 'mim', 'plotcortex', 'off', 'plotmatrix', 'on', 'grouphemispheres', 'on'); 31 | 32 | % frequency band specified 33 | pop_roi_connectplot(EEG, 'measure', 'mim', 'plotcortex', 'off', 'plotmatrix', 'on', 'freqrange', [4 8]'); 34 | 35 | % hemisphere specified 36 | pop_roi_connectplot(EEG, 'measure', 'mim', 'plotcortex', 'off', 'plotmatrix', 'on', 'hemisphere', 'right'); 37 | 38 | % cortical region specified 39 | pop_roi_connectplot(EEG, 'measure', 'mim', 'plotcortex', 'off', 'plotmatrix', 'on', 'region', 'occipital'); 40 | 41 | 42 | 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /test_pipes/test_matrixplots_dkatlas.m: -------------------------------------------------------------------------------- 1 | % Test region-to-region FC matrices (MIM) with different parameters. Here, the Desikan-Killiany atlas with 68 ROIs is used as the source model. 2 | %% Run pipeline 3 | clear 4 | eeglab 5 | 6 | eeglabp = fileparts(which('eeglab.m')); 7 | EEG = pop_loadset('filename','eeglab_data_epochs_ica.set','filepath',fullfile(eeglabp, 'sample_data/')); 8 | EEG = pop_resample( EEG, 100); 9 | EEG = pop_epoch( EEG, { }, [-0.5 1.5], 'newname', 'EEG Data epochs epochs', 'epochinfo', 'yes'); 10 | EEG = pop_select( EEG, 'trial',1:30); 11 | [ALLEEG, EEG, CURRENTSET] = eeg_store(ALLEEG, EEG); 12 | eeglab redraw; 13 | 14 | EEG = pop_dipfit_settings( EEG, 'hdmfile',fullfile(eeglabp, 'plugins','dipfit','standard_BEM','standard_vol.mat'), ... 15 | 'coordformat','MNI','mrifile',fullfile(eeglabp, 'plugins','dipfit','standard_BEM','standard_mri.mat'),... 16 | 'chanfile',fullfile(eeglabp, 'plugins','dipfit','standard_BEM','elec', 'standard_1005.elc'),... 17 | 'coord_transform',[0.83215 -15.6287 2.4114 0.081214 0.00093739 -1.5732 1.1742 1.0601 1.1485] ,'chansel',[1:32] ); 18 | 19 | EEG = pop_leadfield(EEG, 'sourcemodel',fullfile(eeglabp,'functions','supportfiles','head_modelColin27_5003_Standard-10-5-Cap339.mat'), ... 20 | 'sourcemodel2mni',[0 -24 -45 0 0 -1.5708 1000 1000 1000] ,'downsample',1); 21 | 22 | EEG = pop_roi_activity(EEG, 'leadfield',EEG.dipfit.sourcemodel,'model','LCMV','modelparams',{0.05},'atlas','LORETA-Talairach-BAs','nPCA',3, 'chansel', EEG.dipfit.chansel); 23 | EEG = pop_roi_connect(EEG, 'methods', {'MIM'}); 24 | 25 | %% Plot matrix with different parameters 26 | % matrix without any filters 27 | pop_roi_connectplot(EEG, 'measure', 'mim', 'plotcortex', 'off', 'plotmatrix', 'on'); 28 | 29 | % group by hemispheres 30 | pop_roi_connectplot(EEG, 'measure', 'mim', 'plotcortex', 'off', 'plotmatrix', 'on', 'grouphemispheres', 'on'); 31 | 32 | % frequency band specified 33 | pop_roi_connectplot(EEG, 'measure', 'mim', 'plotcortex', 'off', 'plotmatrix', 'on', 'freqrange', [4 8]'); 34 | 35 | % hemisphere specified 36 | pop_roi_connectplot(EEG, 'measure', 'mim', 'plotcortex', 'off', 'plotmatrix', 'on', 'hemisphere', 'right'); 37 | 38 | % cortical region specified 39 | pop_roi_connectplot(EEG, 'measure', 'mim', 'plotcortex', 'off', 'plotmatrix', 'on', 'region', 'occipital'); 40 | 41 | 42 | 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /test_pipes/test_matrixplots_loretaatlas.m: -------------------------------------------------------------------------------- 1 | % Test region-to-region FC matrices (MIM) with different parameters. Here, the LORETA-Talairach-BAs atlas with 90 ROIs is used as the source model. 2 | %% Run pipeline 3 | clear 4 | eeglab 5 | 6 | eeglabp = fileparts(which('eeglab.m')); 7 | EEG = pop_loadset('filename','eeglab_data_epochs_ica.set','filepath',fullfile(eeglabp, 'sample_data/')); 8 | EEG = pop_resample( EEG, 100); 9 | EEG = pop_epoch( EEG, { }, [-0.5 1.5], 'newname', 'EEG Data epochs epochs', 'epochinfo', 'yes'); 10 | EEG = pop_select( EEG, 'trial',1:30); 11 | [ALLEEG, EEG, CURRENTSET] = eeg_store(ALLEEG, EEG); 12 | eeglab redraw; 13 | 14 | EEG = pop_dipfit_settings( EEG, 'hdmfile',fullfile(eeglabp, 'plugins','dipfit','standard_BEM','standard_vol.mat'), ... 15 | 'coordformat','MNI','mrifile',fullfile(eeglabp, 'plugins','dipfit','standard_BEM','standard_mri.mat'),... 16 | 'chanfile',fullfile(eeglabp, 'plugins','dipfit','standard_BEM','elec', 'standard_1005.elc'),... 17 | 'coord_transform',[0.83215 -15.6287 2.4114 0.081214 0.00093739 -1.5732 1.1742 1.0601 1.1485] ,'chansel',[1:32] ); 18 | 19 | EEG = pop_leadfield(EEG, 'sourcemodel',fullfile(eeglabp,'plugins','dipfit','LORETA-Talairach-BAs.mat'), ... 20 | 'sourcemodel2mni',[0 -24 -45 0 0 -1.5708 1000 1000 1000] ,'downsample',1); 21 | 22 | EEG = pop_roi_activity(EEG, 'leadfield',EEG.dipfit.sourcemodel,'model','LCMV','modelparams',{0.05},'atlas','LORETA-Talairach-BAs','nPCA',3, 'chansel', EEG.dipfit.chansel); 23 | EEG = pop_roi_connect(EEG, 'methods', {'MIM'}); 24 | 25 | %% Plot matrix with different parameters 26 | % matrix without any filters 27 | pop_roi_connectplot(EEG, 'measure', 'mim', 'plotcortex', 'off', 'plotmatrix', 'on'); 28 | 29 | % group by hemispheres 30 | pop_roi_connectplot(EEG, 'measure', 'mim', 'plotcortex', 'off', 'plotmatrix', 'on', 'grouphemispheres', 'on'); 31 | 32 | % frequency band specified 33 | pop_roi_connectplot(EEG, 'measure', 'mim', 'plotcortex', 'off', 'plotmatrix', 'on', 'freqrange', [4 8]'); 34 | 35 | % hemisphere specified 36 | pop_roi_connectplot(EEG, 'measure', 'mim', 'plotcortex', 'off', 'plotmatrix', 'on', 'hemisphere', 'right'); 37 | 38 | % cortical region specified 39 | pop_roi_connectplot(EEG, 'measure', 'mim', 'plotcortex', 'off', 'plotmatrix', 'on', 'region', 'occipital'); 40 | 41 | 42 | 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /test_pipes/test_mim_stats.m: -------------------------------------------------------------------------------- 1 | % Test shuffling algorithm that calculates true MIM and generates MIM null distribution. 2 | %% Run pipeline 3 | clear 4 | eeglab 5 | 6 | eeglabp = fileparts(which('eeglab.m')); 7 | EEG = pop_loadset('filename','eeglab_data_epochs_ica.set','filepath',fullfile(eeglabp, 'sample_data/')); 8 | EEG = pop_resample( EEG, 100); 9 | EEG = pop_epoch( EEG, { }, [-0.5 1.5], 'newname', 'EEG Data epochs epochs', 'epochinfo', 'yes'); 10 | EEG = pop_select( EEG, 'trial',1:30); 11 | % [ALLEEG, EEG, CURRENTSET] = eeg_store(ALLEEG, EEG); 12 | eeglab redraw; 13 | 14 | EEG = pop_dipfit_settings( EEG, 'hdmfile',fullfile(eeglabp, 'plugins','dipfit','standard_BEM','standard_vol.mat'), ... 15 | 'coordformat','MNI','mrifile',fullfile(eeglabp, 'plugins','dipfit','standard_BEM','standard_mri.mat'),... 16 | 'chanfile',fullfile(eeglabp, 'plugins','dipfit','standard_BEM','elec', 'standard_1005.elc'),... 17 | 'coord_transform',[0.83215 -15.6287 2.4114 0.081214 0.00093739 -1.5732 1.1742 1.0601 1.1485] ,'chansel',[1:32] ); 18 | 19 | EEG = pop_leadfield(EEG, 'sourcemodel',fullfile(eeglabp,'functions','supportfiles','head_modelColin27_5003_Standard-10-5-Cap339.mat'), ... 20 | 'sourcemodel2mni',[0 -24 -45 0 0 -1.5708 1000 1000 1000] ,'downsample',1); 21 | 22 | EEG = pop_roi_activity(EEG, 'leadfield',EEG.dipfit.sourcemodel,'model','LCMV','modelparams',{0.05},'atlas','LORETA-Talairach-BAs','nPCA',3, 'chansel', EEG.dipfit.chansel); 23 | 24 | %% Create null distribution 25 | EEG1_MIM = pop_roi_connect(EEG, 'methods', {'CS' 'cCOH', 'wPLI' 'MIM'}, 'freqresolution', 200, 'roi_selection', {1, 3, 7}, 'conn_stats', 'on', 'nshuf', 1000, 'poolsize', 12); 26 | EEG2_MIM = pop_roi_connect(EEG, 'methods', {'CS' 'cCOH', 'wPLI' 'MIM'}, 'conn_stats', 'on', 'nshuf', 1000); % takes very long! 27 | % load('test_pipes/MIM_shuf.mat') 28 | pop_roi_statsplot(EEG1_MIM, 'measure', 'MIM', 'freqrange', [8 13]); 29 | 30 | %% Unit test 31 | % Test if the first shuffle of the surrogate connectivity matrix in EEG1 is in fact the true matrix 32 | EEG1 = pop_roi_connect(EEG, 'methods', {'MIM'}, 'conn_stats', 'on', 'nshuf', 3); 33 | EEG2 = pop_roi_connect(EEG, 'methods', {'MIM'}, 'conn_stats', 'off'); 34 | if ~isequal(squeeze(EEG1.roi.MIM(:, :, :, 1)), EEG2.roi.MIM) 35 | error 'The first shuffle in the surrogate connectivity array is not the true matrix.' 36 | end 37 | -------------------------------------------------------------------------------- /test_pipes/test_snippets_connectivity.m: -------------------------------------------------------------------------------- 1 | % Test connectivity estimation on time snippets. 2 | %% Run pipeline 3 | clear 4 | eeglab 5 | 6 | eeglabp = fileparts(which('eeglab.m')); 7 | EEG = pop_loadset('filename','eeglab_data_epochs_ica.set','filepath',fullfile(eeglabp, 'sample_data/')); 8 | EEG = pop_resample( EEG, 100); 9 | EEG = pop_epoch( EEG, { }, [-0.5 1.5], 'newname', 'EEG Data epochs epochs', 'epochinfo', 'yes'); 10 | EEG = pop_select( EEG, 'trial',1:30); 11 | [ALLEEG, EEG, CURRENTSET] = eeg_store(ALLEEG, EEG); 12 | eeglab redraw; 13 | 14 | EEG = pop_dipfit_settings( EEG, 'hdmfile',fullfile(eeglabp, 'plugins','dipfit','standard_BEM','standard_vol.mat'), ... 15 | 'coordformat','MNI','mrifile',fullfile(eeglabp, 'plugins','dipfit','standard_BEM','standard_mri.mat'),... 16 | 'chanfile',fullfile(eeglabp, 'plugins','dipfit','standard_BEM','elec', 'standard_1005.elc'),... 17 | 'coord_transform',[0.83215 -15.6287 2.4114 0.081214 0.00093739 -1.5732 1.1742 1.0601 1.1485] ,'chansel',[1:32] ); 18 | 19 | EEG = pop_leadfield(EEG, 'sourcemodel',fullfile(eeglabp,'functions','supportfiles','head_modelColin27_5003_Standard-10-5-Cap339.mat'), ... 20 | 'sourcemodel2mni',[0 -24 -45 0 0 -1.5708 1000 1000 1000] ,'downsample',1); 21 | 22 | EEG = pop_roi_activity(EEG, 'leadfield',EEG.dipfit.sourcemodel,'model','LCMV','modelparams',{0.05},'atlas','LORETA-Talairach-BAs','nPCA',3, 'chansel', EEG.dipfit.chansel); 23 | 24 | %% Snippet analysis, individual snippets are stored 25 | % EEG = pop_roi_connect(EEG, 'methods', { 'MIM' }, 'snippet', 'on', 'snip_length', 20); % 'fcsave_format', 'mean_snips' 26 | EEG = pop_roi_connect(EEG, 'morder',20,'naccu',[],'methods', {'CS', 'MIM'}, 'roi_selection', {}, 'snippet', 'on', 'snip_length', 20, 'fcsave_format', 'all_snips'); 27 | 28 | % test for PAC 29 | fcomb.low = [8 10]; 30 | fcomb.high = [20 22]; 31 | EEG1 = pop_roi_connect(EEG, 'morder', 20,'naccu', [], 'methods', {'MIM', 'PAC'}, 'roi_selection', {}, 'fcomb', fcomb, 'snippet', 'on', 'snip_length', 20, 'fcsave_format', 'all_snips'); 32 | EEG2 = pop_roi_connect(EEG, 'morder', 20,'naccu', [], 'methods', {'PAC'}, 'roi_selection', {}, 'fcomb', fcomb, 'snippet', 'on', 'snip_length', 20, 'fcsave_format', 'mean_snips'); 33 | disp(size(EEG.roi.MIM)) % n_snips, frequency, roi, roi 34 | -------------------------------------------------------------------------------- /utils/calc_pac.m: -------------------------------------------------------------------------------- 1 | % calc_pac - Function to compute absolute values of the cross-bispectrum/bicoherence and the antisymmetrized 2 | % cross-bispectrum/bicoherence, such that biv_orig corresponds to |B(f1,f2)|. Used for the final 3 | % computation of PAC_km(f1, f2) = 0.5 * |Bkmm(f1, f2-f1)| + 0.5 * |Bkmm(f1, f2)|. 4 | % 5 | % Inputs: 6 | % BS - [array] (nchan x nchan x nchan x nfreqpairs) Cross-bispectral tensor 7 | % RTP - [array] (nchan x nchan x nchan) Threenorm tensor to normalize the cross-bispectrum, used to compute cross-bicoherence 8 | % 9 | % Outputs: 10 | % biv_orig - [array] (1 x nchan) Absolute value of the original cross-bispectrum, corresponding to [Bkmm(f1, f2), Bmkk(f1, f2)] 11 | % biv_anti - [array] (1 x nchan) Absolute value of the antisymmetrized cross-bispectrum 12 | % biv_orig_norm - [array] (1 x nchan) Absolute value of the normalized original cross-bispectrum (cross-bicoherence) 13 | % biv_anti_norm - [array] (1 x nchan) Absolute value of the normalized antisymmetrized cross-bispectrum (antisymmetrized cross-bicoherence) 14 | % 15 | % Authors: 16 | % Tien Dung Nguyen, tien-dung.nguyen@charite.de, 17 | % Zixuan Liu, zixuan.liu@campus.tu-berlin.de 18 | 19 | function [biv_orig, biv_anti, biv_orig_norm, biv_anti_norm] = calc_pac(BS, RTP) 20 | 21 | % Calculate absolute values of the cross-bispectrum 22 | biv_orig = squeeze(([mean(abs(BS(1, 2, 2, :)), 4) mean(abs(BS(2, 1, 1, :)), 4)])); % [Bkmm, Bmkk], average over frequency bands (4th dimension) 23 | xx = BS - permute(BS, [2 1 3 4]); 24 | biv_anti = squeeze(([mean(abs(xx(1, 2, 2, :)), 4) mean(abs(xx(2, 1, 1, :)), 4)])); 25 | 26 | % Calculate absolute values of the cross-bicoherence 27 | bicoh = BS ./ RTP; 28 | biv_orig_norm = squeeze(([mean(abs(bicoh(1, 2, 2, :)), 4) mean(abs(bicoh(2, 1, 1, :)), 4)])); % [Bkmm, Bmkk], average over frequency bands 29 | xx = bicoh - permute(bicoh, [2 1 3 4]); 30 | biv_anti_norm = squeeze(([mean(abs(xx(1, 2, 2, :)), 4) mean(abs(xx(2, 1, 1,:)), 4)])); 31 | 32 | end -------------------------------------------------------------------------------- /utils/get_connect_mat.m: -------------------------------------------------------------------------------- 1 | function measure = get_connect_mat( measureOri, nROI, signVal) 2 | % create a ROI x ROI connectivity matrix, if needed 3 | % TRGCmat(f, ii, jj) is net TRGC from jj to ii 4 | measure = []; 5 | iinds = 0; 6 | for iroi = 1:nROI 7 | for jroi = (iroi+1):nROI 8 | iinds = iinds + 1; 9 | measure(:, iroi, jroi) = signVal * measureOri(:, iinds); 10 | measure(:, jroi, iroi) = measureOri(:, iinds); 11 | end 12 | end 13 | end -------------------------------------------------------------------------------- /utils/get_labels.m: -------------------------------------------------------------------------------- 1 | function labels = get_labels(EEG) 2 | % retrieve labels from atlas 3 | labels = strings(1,length(EEG.roi.atlas.Scouts)); 4 | for i = 1:length(labels) 5 | scout = struct2cell(EEG.roi.atlas.Scouts(i)); 6 | labels(i) = char(scout(1)); 7 | end 8 | labels = cellstr(labels); 9 | 10 | % remove region labels that were not selected 11 | if isfield(EEG.roi, 'roi_selection') 12 | if ~isempty(EEG.roi.roi_selection) 13 | labels = labels(cell2mat(EEG.roi.roi_selection)); 14 | end 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /utils/replace_underscores.m: -------------------------------------------------------------------------------- 1 | function new_labels = replace_underscores(labels) 2 | % remove underscores in label names to avoid bug 3 | new_labels = strrep(labels, '_', ' '); 4 | end -------------------------------------------------------------------------------- /utils/rm_components.m: -------------------------------------------------------------------------------- 1 | function measure = rm_components(measure, nPCA) 2 | % only keep the first PC 3 | % measure has the size (n_freq, nROI*nPCA, nROI*nPCA) 4 | if nPCA > 1 5 | measure = measure(:, 1:nPCA:end, 1:nPCA:end); 6 | end 7 | end -------------------------------------------------------------------------------- /utils/roi_mim2_v2.m: -------------------------------------------------------------------------------- 1 | function [mic, mim] = roi_mim2_v2(Cohroi, subinds1, subinds2) 2 | 3 | regu = 0.000001; 4 | [~, ~, nfreq] = size(Cohroi); 5 | 6 | ipcs = numel(subinds1); 7 | jpcs = numel(subinds2); 8 | 9 | cs_red1 = Cohroi(subinds1,subinds1, :); 10 | cs_red2 = Cohroi(subinds1,subinds2, :); 11 | cs_red3 = Cohroi(subinds2,subinds2, :); 12 | 13 | [mean_diag_r_csred1, dim1] = get_mean_diag(cs_red1, nfreq); 14 | caainv = pageinv(real(cs_red1) + regu * ones(dim1, dim1, nfreq) .* eye(ipcs) .* mean_diag_r_csred1); 15 | cab = imag(cs_red2); 16 | [mean_diag_r_csred3, dim1] = get_mean_diag(cs_red3, nfreq); 17 | cbbinv = pageinv(real(cs_red3) + regu * ones(dim1, dim1, nfreq) .* eye(jpcs) .* mean(mean_diag_r_csred3)); 18 | X = pagemtimes(pagemtimes(cab, cbbinv), pagetranspose(cab)); 19 | 20 | % MIM Ewald Eq. 14 21 | r_caainv_X = reshape(pagemtimes(caainv, X), [], nfreq); 22 | diag_idx = 1:dim1+1:size(r_caainv_X, 1); 23 | trace_operator = zeros(1, size(r_caainv_X, 1)); 24 | trace_operator(diag_idx) = 1; 25 | mim = trace_operator * r_caainv_X; 26 | 27 | caainvsqrt = zeros(size(caainv, 1), size(caainv, 2), size(caainv, 3)); 28 | for ifq = 1:nfreq 29 | caainvsqrt(:, :, ifq) = sqrtm(caainv(:, :, ifq)); 30 | end 31 | Y = pagemtimes(pagemtimes(caainvsqrt, X), caainvsqrt); % Eq. 23 32 | [~, s, ~] = pagesvd(Y); 33 | 34 | % MIC 35 | mic = sqrt(s(1, 1, :)); 36 | end 37 | 38 | function [mean_diag_r_csred, dim1] = get_mean_diag(cs_red, nfreq) 39 | % equivalent to diag(real(cs_red) in 2D 40 | dim1 = size(cs_red, 1); 41 | r_csred = reshape(real(cs_red), [], nfreq); 42 | diag_idx = 1:dim1+1:size(r_csred, 1); 43 | diag_r_csred = r_csred(diag_idx, :); 44 | mean_diag_r_csred = reshape(mean(diag_r_csred, 1), 1, 1, []); 45 | end --------------------------------------------------------------------------------