diff --git a/.gitignore b/.gitignore index d23cbb2e..08b3167a 100644 --- a/.gitignore +++ b/.gitignore @@ -15,12 +15,10 @@ *.tar.* *.egg* *.tmproj -*.png *.idea *.old *.dat *.bak -test_*.py # Byte-compiled / optimized / DLL files __pycache__/ @@ -35,7 +33,6 @@ old/ devel env/ bin/ -build/ develop-eggs/ dist/ eggs/ @@ -76,6 +73,10 @@ coverage.xml *.pot # Sphinx documentation -docs/_build/ +.buildinfo +.doctrees/ .DS_Store +.ipynb_checkpoints/ + +*.label diff --git a/Makefile b/Makefile new file mode 100644 index 00000000..f41108d2 --- /dev/null +++ b/Makefile @@ -0,0 +1,61 @@ +# simple makefile to simplify repetitive build env management tasks under posix +# taken from Makefile for mne-python and adapted for jumeg + +PYTHON ?= python +PYTESTS ?= py.test +CTAGS ?= ctags +CODESPELL_SKIPS ?= "doc/_build,doc/auto_*,*.fif,*.eve,*.gz,*.tgz,*.zip,*.mat,*.stc,*.label,*.w,*.bz2,*.annot,*.sulc,*.log,*.local-copy,*.orig_avg,*.inflated_avg,*.gii,*.pyc,*.doctree,*.pickle,*.inv,*.png,*.edf,*.touch,*.thickness,*.nofix,*.volume,*.defect_borders,*.mgh,lh.*,rh.*,COR-*,FreeSurferColorLUT.txt,*.examples,.xdebug_mris_calc,bad.segments,BadChannels,*.hist,empty_file,*.orig,*.js,*.map,*.ipynb,searchindex.dat,plot_*.rst,*.rst.txt,c_EULA.rst*,*.html,gdf_encodes.txt,*.svg,references.bib,*.css,*.edf,*.bdf,*.vhdr" +CODESPELL_DIRS ?= jumeg/ doc/ examples/ +all: clean inplace test test-doc + +clean-pyc: + find . -name "*.pyc" | xargs rm -f + +clean-so: + find . -name "*.so" | xargs rm -f + find . -name "*.pyd" | xargs rm -f + +clean-build: + rm -rf build dist + +clean-ctags: + rm -f tags + +clean-cache: + find . -name "__pycache__" | xargs rm -rf + +clean: clean-build clean-pyc clean-so clean-ctags clean-cache + +in: inplace # just a shortcut +inplace: + $(PYTHON) setup.py build_ext -i + +wheel: + $(PYTHON) setup.py sdist bdist_wheel + +wheel_quiet: + $(PYTHON) setup.py -q sdist bdist_wheel + +pytest: test + +test: in + rm -f .coverage + $(PYTESTS) -m 'not ultraslowtest' jumeg + +test-verbose: in + rm -f .coverage + $(PYTESTS) -m 'not ultraslowtest' jumeg --verbose + +test-fast: in + rm -f .coverage + $(PYTESTS) -m 'not slowtest' jumeg + +test-full: in + rm -f .coverage + $(PYTESTS) jumeg + +build-doc: + cd docs; make clean + # cd docs; DISPLAY=:1.0 xvfb-run -n 1 -s "-screen 0 1280x1024x24 -noreset -ac +extension GLX +render" make html + cd docs; make html + diff --git a/docs/Makefile b/docs/Makefile new file mode 100755 index 00000000..61e9b040 --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,188 @@ +# makefile for Sphinx documentation + +# You can set these variables from the command line, and also +# from the environment for the first two. +SPHINXOPTS ?= +SPHINXBUILD ?= sphinx-build +SOURCEDIR = . +BUILDDIR = build + +GITHUB_PAGES_BRANCH = jumeg_sphinx +OUTPUTDIR = build/html + +# Put it first so that "make" without argument is like "make help". +# help: +# @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) +# +# .PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +# Internal variables. +PAPEROPT_a4 = -D latex_paper_size=a4 +PAPEROPT_letter = -D latex_paper_size=letter +ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . +# the i18n builder cannot share the environment and doctrees with the others +I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . + +.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext + +help: + @echo "Please use \`make ' where is one of" + @echo " clean to remove genrated output" + @echo " html to make standalone HTML files" + @echo " notebooks to make the Jupyter notebook-based tutorials" + @echo " dirhtml to make HTML files named index.html in directories" + @echo " singlehtml to make a single large HTML file" + @echo " pickle to make pickle files" + @echo " json to make JSON files" + @echo " htmlhelp to make HTML files and a HTML help project" + @echo " qthelp to make HTML files and a qthelp project" + @echo " devhelp to make HTML files and a Devhelp project" + @echo " epub to make an epub" + @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" + @echo " latexpdf to make LaTeX files and run them through pdflatex" + @echo " text to make text files" + @echo " man to make manual pages" + @echo " texinfo to make Texinfo files" + @echo " info to make Texinfo files and run them through makeinfo" + @echo " gettext to make PO message catalogs" + @echo " changes to make an overview of all changed/added/deprecated items" + @echo " linkcheck to check all external links for integrity" + @echo " doctest to run all doctests embedded in the documentation (if enabled)" + +clean: + -rm -rf $(BUILDDIR)/* + -rm -rf auto_examples/* + -rm -rf generated/* + +# tutorials: +# make -C tutorial +# +# introduction: introduction.ipynb +# tools/nb_to_doc.py introduction + +# notebooks: tutorials introduction + +html: + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." + +dirhtml: + $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." + +singlehtml: + $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml + @echo + @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." + +pickle: + $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle + @echo + @echo "Build finished; now you can process the pickle files." + +json: + $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json + @echo + @echo "Build finished; now you can process the JSON files." + +htmlhelp: + $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp + @echo + @echo "Build finished; now you can run HTML Help Workshop with the" \ + ".hhp project file in $(BUILDDIR)/htmlhelp." + +qthelp: + $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp + @echo + @echo "Build finished; now you can run "qcollectiongenerator" with the" \ + ".qhcp project file in $(BUILDDIR)/qthelp, like this:" + @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/lyman.qhcp" + @echo "To view the help file:" + @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/lyman.qhc" + +devhelp: + $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp + @echo + @echo "Build finished." + @echo "To view the help file:" + @echo "# mkdir -p $$HOME/.local/share/devhelp/lyman" + @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/lyman" + @echo "# devhelp" + +epub: + $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub + @echo + @echo "Build finished. The epub file is in $(BUILDDIR)/epub." + +latex: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo + @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." + @echo "Run \`make' in that directory to run these through (pdf)latex" \ + "(use \`make latexpdf' here to do that automatically)." + +latexpdf: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through pdflatex..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +text: + $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text + @echo + @echo "Build finished. The text files are in $(BUILDDIR)/text." + +man: + $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man + @echo + @echo "Build finished. The manual pages are in $(BUILDDIR)/man." + +texinfo: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo + @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." + @echo "Run \`make' in that directory to run these through makeinfo" \ + "(use \`make info' here to do that automatically)." + +info: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo "Running Texinfo files through makeinfo..." + make -C $(BUILDDIR)/texinfo info + @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." + +gettext: + $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale + @echo + @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." + +changes: + $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes + @echo + @echo "The overview file is in $(BUILDDIR)/changes." + +linkcheck: + $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck + @echo + @echo "Link check complete; look for any errors in the above output " \ + "or in $(BUILDDIR)/linkcheck/output.txt." + +doctest: + $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest + @echo "Testing of doctests in the sources finished, look at the " \ + "results in $(BUILDDIR)/doctest/output.txt." + +install: + touch $(BUILDDIR)/.nojekyll + git add $(BUILDDIR)/.nojekyll + rm -rf ./auto_examples ./generated + mv $(OUTPUTDIR)/* ./ + rm -rf ./$(BUILDDIR)/ + git commit -a -m 'Generate jumeg site' ./$(SOURCEDIR) + git push origin $(GITHUB_PAGES_BRANCH) diff --git a/docs/api.rst b/docs/api.rst new file mode 100755 index 00000000..f30fcc83 --- /dev/null +++ b/docs/api.rst @@ -0,0 +1,49 @@ +.. _api_documentation: + +================= +API Documentation +================= + +.. currentmodule:: jumeg + +Connectivity +============ + +Functions + +.. currentmodule:: jumeg.connectivity + +.. autosummary:: + :toctree: generated/ + :nosignatures: + + find_distances_matrix + weighted_con_matrix + get_label_distances + make_annot_from_csv + + sensor_connectivity_3d + plot_grouped_connectivity_circle + plot_generic_grouped_circle + plot_grouped_causality_circle + plot_degree_circle + plot_lines_and_blobs + plot_labelled_group_connectivity_circle + plot_fica_grouped_circle + +.. currentmodule:: jumeg.connectivity.causality + +.. autosummary:: + :toctree: generated/ + :nosignatures: + + dw_whiteness + consistency + do_mvar_evaluation + check_whiteness_and_consistency + check_model_order + prepare_causality_matrix + make_frequency_bands + compute_order_extended + compute_order + compute_causal_outflow_inflow diff --git a/docs/build/doctrees/api.doctree b/docs/build/doctrees/api.doctree new file mode 100644 index 00000000..3fc8e973 Binary files /dev/null and b/docs/build/doctrees/api.doctree differ diff --git a/docs/build/doctrees/auto_examples/causality/do_granger_causality.doctree b/docs/build/doctrees/auto_examples/causality/do_granger_causality.doctree new file mode 100644 index 00000000..0fa800ec Binary files /dev/null and b/docs/build/doctrees/auto_examples/causality/do_granger_causality.doctree differ diff --git a/docs/build/doctrees/auto_examples/causality/index.doctree b/docs/build/doctrees/auto_examples/causality/index.doctree new file mode 100644 index 00000000..8f655005 Binary files /dev/null and b/docs/build/doctrees/auto_examples/causality/index.doctree differ diff --git a/docs/build/doctrees/auto_examples/causality/plot_causality_circle.doctree b/docs/build/doctrees/auto_examples/causality/plot_causality_circle.doctree new file mode 100644 index 00000000..66bee067 Binary files /dev/null and b/docs/build/doctrees/auto_examples/causality/plot_causality_circle.doctree differ diff --git a/docs/build/doctrees/auto_examples/causality/plot_inter_and_intra_lobe_causality.doctree b/docs/build/doctrees/auto_examples/causality/plot_inter_and_intra_lobe_causality.doctree new file mode 100644 index 00000000..898eb020 Binary files /dev/null and b/docs/build/doctrees/auto_examples/causality/plot_inter_and_intra_lobe_causality.doctree differ diff --git a/docs/build/doctrees/auto_examples/causality/sg_execution_times.doctree b/docs/build/doctrees/auto_examples/causality/sg_execution_times.doctree new file mode 100644 index 00000000..48fc10f5 Binary files /dev/null and b/docs/build/doctrees/auto_examples/causality/sg_execution_times.doctree differ diff --git a/docs/build/doctrees/auto_examples/connectivity/index.doctree b/docs/build/doctrees/auto_examples/connectivity/index.doctree new file mode 100644 index 00000000..ea35ae79 Binary files /dev/null and b/docs/build/doctrees/auto_examples/connectivity/index.doctree differ diff --git a/docs/build/doctrees/auto_examples/connectivity/plot_annot_standard_rsns.doctree b/docs/build/doctrees/auto_examples/connectivity/plot_annot_standard_rsns.doctree new file mode 100644 index 00000000..5f623ed0 Binary files /dev/null and b/docs/build/doctrees/auto_examples/connectivity/plot_annot_standard_rsns.doctree differ diff --git a/docs/build/doctrees/auto_examples/connectivity/plot_brain_connectome.doctree b/docs/build/doctrees/auto_examples/connectivity/plot_brain_connectome.doctree new file mode 100644 index 00000000..8d3fbf06 Binary files /dev/null and b/docs/build/doctrees/auto_examples/connectivity/plot_brain_connectome.doctree differ diff --git a/docs/build/doctrees/auto_examples/connectivity/plot_circle_lines_and_blobs.doctree b/docs/build/doctrees/auto_examples/connectivity/plot_circle_lines_and_blobs.doctree new file mode 100644 index 00000000..e8de1280 Binary files /dev/null and b/docs/build/doctrees/auto_examples/connectivity/plot_circle_lines_and_blobs.doctree differ diff --git a/docs/build/doctrees/auto_examples/connectivity/plot_communities.doctree b/docs/build/doctrees/auto_examples/connectivity/plot_communities.doctree new file mode 100644 index 00000000..8dd38792 Binary files /dev/null and b/docs/build/doctrees/auto_examples/connectivity/plot_communities.doctree differ diff --git a/docs/build/doctrees/auto_examples/connectivity/plot_compute_epochs_surrogates.doctree b/docs/build/doctrees/auto_examples/connectivity/plot_compute_epochs_surrogates.doctree new file mode 100644 index 00000000..af6ebf84 Binary files /dev/null and b/docs/build/doctrees/auto_examples/connectivity/plot_compute_epochs_surrogates.doctree differ diff --git a/docs/build/doctrees/auto_examples/connectivity/plot_compute_label_distances.doctree b/docs/build/doctrees/auto_examples/connectivity/plot_compute_label_distances.doctree new file mode 100644 index 00000000..52d2b725 Binary files /dev/null and b/docs/build/doctrees/auto_examples/connectivity/plot_compute_label_distances.doctree differ diff --git a/docs/build/doctrees/auto_examples/connectivity/plot_connectivity_between_standard_rsns.doctree b/docs/build/doctrees/auto_examples/connectivity/plot_connectivity_between_standard_rsns.doctree new file mode 100644 index 00000000..e36c6dc8 Binary files /dev/null and b/docs/build/doctrees/auto_examples/connectivity/plot_connectivity_between_standard_rsns.doctree differ diff --git a/docs/build/doctrees/auto_examples/connectivity/plot_custom_grouped_connectivity_circle.doctree b/docs/build/doctrees/auto_examples/connectivity/plot_custom_grouped_connectivity_circle.doctree new file mode 100644 index 00000000..8197d89a Binary files /dev/null and b/docs/build/doctrees/auto_examples/connectivity/plot_custom_grouped_connectivity_circle.doctree differ diff --git a/docs/build/doctrees/auto_examples/connectivity/plot_degree_circle.doctree b/docs/build/doctrees/auto_examples/connectivity/plot_degree_circle.doctree new file mode 100644 index 00000000..1750b95e Binary files /dev/null and b/docs/build/doctrees/auto_examples/connectivity/plot_degree_circle.doctree differ diff --git a/docs/build/doctrees/auto_examples/connectivity/plot_destriux_atlas_based_connectivity.doctree b/docs/build/doctrees/auto_examples/connectivity/plot_destriux_atlas_based_connectivity.doctree new file mode 100644 index 00000000..f7a1ec0f Binary files /dev/null and b/docs/build/doctrees/auto_examples/connectivity/plot_destriux_atlas_based_connectivity.doctree differ diff --git a/docs/build/doctrees/auto_examples/connectivity/plot_generate_surrogate_connectivity.doctree b/docs/build/doctrees/auto_examples/connectivity/plot_generate_surrogate_connectivity.doctree new file mode 100644 index 00000000..5f08ea26 Binary files /dev/null and b/docs/build/doctrees/auto_examples/connectivity/plot_generate_surrogate_connectivity.doctree differ diff --git a/docs/build/doctrees/auto_examples/connectivity/plot_generate_surrogate_stcs.doctree b/docs/build/doctrees/auto_examples/connectivity/plot_generate_surrogate_stcs.doctree new file mode 100644 index 00000000..8b254856 Binary files /dev/null and b/docs/build/doctrees/auto_examples/connectivity/plot_generate_surrogate_stcs.doctree differ diff --git a/docs/build/doctrees/auto_examples/connectivity/plot_generic_grouped_connectivity_circle.doctree b/docs/build/doctrees/auto_examples/connectivity/plot_generic_grouped_connectivity_circle.doctree new file mode 100644 index 00000000..3a9842c6 Binary files /dev/null and b/docs/build/doctrees/auto_examples/connectivity/plot_generic_grouped_connectivity_circle.doctree differ diff --git a/docs/build/doctrees/auto_examples/connectivity/plot_grouped_connectivity_circle.doctree b/docs/build/doctrees/auto_examples/connectivity/plot_grouped_connectivity_circle.doctree new file mode 100644 index 00000000..ce3a3d84 Binary files /dev/null and b/docs/build/doctrees/auto_examples/connectivity/plot_grouped_connectivity_circle.doctree differ diff --git a/docs/build/doctrees/auto_examples/connectivity/plot_label_distances.doctree b/docs/build/doctrees/auto_examples/connectivity/plot_label_distances.doctree new file mode 100644 index 00000000..29def2f6 Binary files /dev/null and b/docs/build/doctrees/auto_examples/connectivity/plot_label_distances.doctree differ diff --git a/docs/build/doctrees/auto_examples/connectivity/plot_labelled_connectivity_circle.doctree b/docs/build/doctrees/auto_examples/connectivity/plot_labelled_connectivity_circle.doctree new file mode 100644 index 00000000..485e832f Binary files /dev/null and b/docs/build/doctrees/auto_examples/connectivity/plot_labelled_connectivity_circle.doctree differ diff --git a/docs/build/doctrees/auto_examples/connectivity/plot_shuffle_time_slices.doctree b/docs/build/doctrees/auto_examples/connectivity/plot_shuffle_time_slices.doctree new file mode 100644 index 00000000..45a8e25b Binary files /dev/null and b/docs/build/doctrees/auto_examples/connectivity/plot_shuffle_time_slices.doctree differ diff --git a/docs/build/doctrees/auto_examples/connectivity/plot_simulated_connectivity.doctree b/docs/build/doctrees/auto_examples/connectivity/plot_simulated_connectivity.doctree new file mode 100644 index 00000000..25141e38 Binary files /dev/null and b/docs/build/doctrees/auto_examples/connectivity/plot_simulated_connectivity.doctree differ diff --git a/docs/build/doctrees/auto_examples/connectivity/plot_standard_resting_network_on_aparc_annot_map.doctree b/docs/build/doctrees/auto_examples/connectivity/plot_standard_resting_network_on_aparc_annot_map.doctree new file mode 100644 index 00000000..d95749a2 Binary files /dev/null and b/docs/build/doctrees/auto_examples/connectivity/plot_standard_resting_network_on_aparc_annot_map.doctree differ diff --git a/docs/build/doctrees/auto_examples/connectivity/plot_surrogate_methods.doctree b/docs/build/doctrees/auto_examples/connectivity/plot_surrogate_methods.doctree new file mode 100644 index 00000000..6a9d7917 Binary files /dev/null and b/docs/build/doctrees/auto_examples/connectivity/plot_surrogate_methods.doctree differ diff --git a/docs/build/doctrees/auto_examples/connectivity/plot_test_transform_mni_to_ras.doctree b/docs/build/doctrees/auto_examples/connectivity/plot_test_transform_mni_to_ras.doctree new file mode 100644 index 00000000..2795061d Binary files /dev/null and b/docs/build/doctrees/auto_examples/connectivity/plot_test_transform_mni_to_ras.doctree differ diff --git a/docs/build/doctrees/auto_examples/connectivity/plot_vertices_around_seed.doctree b/docs/build/doctrees/auto_examples/connectivity/plot_vertices_around_seed.doctree new file mode 100644 index 00000000..abeca8da Binary files /dev/null and b/docs/build/doctrees/auto_examples/connectivity/plot_vertices_around_seed.doctree differ diff --git a/docs/build/doctrees/auto_examples/connectivity/sg_execution_times.doctree b/docs/build/doctrees/auto_examples/connectivity/sg_execution_times.doctree new file mode 100644 index 00000000..47879f19 Binary files /dev/null and b/docs/build/doctrees/auto_examples/connectivity/sg_execution_times.doctree differ diff --git a/docs/build/doctrees/auto_examples/decompose/do_MLICA.doctree b/docs/build/doctrees/auto_examples/decompose/do_MLICA.doctree new file mode 100644 index 00000000..610d5c7e Binary files /dev/null and b/docs/build/doctrees/auto_examples/decompose/do_MLICA.doctree differ diff --git a/docs/build/doctrees/auto_examples/decompose/do_compare_ica_methods.doctree b/docs/build/doctrees/auto_examples/decompose/do_compare_ica_methods.doctree new file mode 100644 index 00000000..8284f7ec Binary files /dev/null and b/docs/build/doctrees/auto_examples/decompose/do_compare_ica_methods.doctree differ diff --git a/docs/build/doctrees/auto_examples/decompose/index.doctree b/docs/build/doctrees/auto_examples/decompose/index.doctree new file mode 100644 index 00000000..c0e20f37 Binary files /dev/null and b/docs/build/doctrees/auto_examples/decompose/index.doctree differ diff --git a/docs/build/doctrees/auto_examples/decompose/plot_data_distribution.doctree b/docs/build/doctrees/auto_examples/decompose/plot_data_distribution.doctree new file mode 100644 index 00000000..15d66260 Binary files /dev/null and b/docs/build/doctrees/auto_examples/decompose/plot_data_distribution.doctree differ diff --git a/docs/build/doctrees/auto_examples/decompose/plot_rank_estimation.doctree b/docs/build/doctrees/auto_examples/decompose/plot_rank_estimation.doctree new file mode 100644 index 00000000..82cfd1fc Binary files /dev/null and b/docs/build/doctrees/auto_examples/decompose/plot_rank_estimation.doctree differ diff --git a/docs/build/doctrees/auto_examples/decompose/sg_execution_times.doctree b/docs/build/doctrees/auto_examples/decompose/sg_execution_times.doctree new file mode 100644 index 00000000..9a21e10b Binary files /dev/null and b/docs/build/doctrees/auto_examples/decompose/sg_execution_times.doctree differ diff --git a/docs/build/doctrees/auto_examples/index.doctree b/docs/build/doctrees/auto_examples/index.doctree new file mode 100644 index 00000000..945e63d3 Binary files /dev/null and b/docs/build/doctrees/auto_examples/index.doctree differ diff --git a/docs/build/doctrees/auto_examples/mft/index.doctree b/docs/build/doctrees/auto_examples/mft/index.doctree new file mode 100644 index 00000000..f029acf3 Binary files /dev/null and b/docs/build/doctrees/auto_examples/mft/index.doctree differ diff --git a/docs/build/doctrees/auto_examples/mft/plot_perform_mft_surface.doctree b/docs/build/doctrees/auto_examples/mft/plot_perform_mft_surface.doctree new file mode 100644 index 00000000..a833c5e3 Binary files /dev/null and b/docs/build/doctrees/auto_examples/mft/plot_perform_mft_surface.doctree differ diff --git a/docs/build/doctrees/auto_examples/mft/plot_perform_mft_surface_list.doctree b/docs/build/doctrees/auto_examples/mft/plot_perform_mft_surface_list.doctree new file mode 100644 index 00000000..d94f8949 Binary files /dev/null and b/docs/build/doctrees/auto_examples/mft/plot_perform_mft_surface_list.doctree differ diff --git a/docs/build/doctrees/auto_examples/mft/plot_perform_mft_volume.doctree b/docs/build/doctrees/auto_examples/mft/plot_perform_mft_volume.doctree new file mode 100644 index 00000000..6aaad160 Binary files /dev/null and b/docs/build/doctrees/auto_examples/mft/plot_perform_mft_volume.doctree differ diff --git a/docs/build/doctrees/auto_examples/mft/sg_execution_times.doctree b/docs/build/doctrees/auto_examples/mft/sg_execution_times.doctree new file mode 100644 index 00000000..55c3d291 Binary files /dev/null and b/docs/build/doctrees/auto_examples/mft/sg_execution_times.doctree differ diff --git a/docs/build/doctrees/auto_examples/preprocessing/index.doctree b/docs/build/doctrees/auto_examples/preprocessing/index.doctree new file mode 100644 index 00000000..1b079ab9 Binary files /dev/null and b/docs/build/doctrees/auto_examples/preprocessing/index.doctree differ diff --git a/docs/build/doctrees/auto_examples/preprocessing/plot_compare_jumeg_filters.doctree b/docs/build/doctrees/auto_examples/preprocessing/plot_compare_jumeg_filters.doctree new file mode 100644 index 00000000..9b812adc Binary files /dev/null and b/docs/build/doctrees/auto_examples/preprocessing/plot_compare_jumeg_filters.doctree differ diff --git a/docs/build/doctrees/auto_examples/preprocessing/plot_interpolate_bads.doctree b/docs/build/doctrees/auto_examples/preprocessing/plot_interpolate_bads.doctree new file mode 100644 index 00000000..6014746d Binary files /dev/null and b/docs/build/doctrees/auto_examples/preprocessing/plot_interpolate_bads.doctree differ diff --git a/docs/build/doctrees/auto_examples/preprocessing/plot_noise_reducer.doctree b/docs/build/doctrees/auto_examples/preprocessing/plot_noise_reducer.doctree new file mode 100644 index 00000000..9a4a5d19 Binary files /dev/null and b/docs/build/doctrees/auto_examples/preprocessing/plot_noise_reducer.doctree differ diff --git a/docs/build/doctrees/auto_examples/preprocessing/plot_suggest_bads.doctree b/docs/build/doctrees/auto_examples/preprocessing/plot_suggest_bads.doctree new file mode 100644 index 00000000..2f4017e7 Binary files /dev/null and b/docs/build/doctrees/auto_examples/preprocessing/plot_suggest_bads.doctree differ diff --git a/docs/build/doctrees/auto_examples/preprocessing/sg_execution_times.doctree b/docs/build/doctrees/auto_examples/preprocessing/sg_execution_times.doctree new file mode 100644 index 00000000..c2f99a1f Binary files /dev/null and b/docs/build/doctrees/auto_examples/preprocessing/sg_execution_times.doctree differ diff --git a/docs/build/doctrees/environment.pickle b/docs/build/doctrees/environment.pickle new file mode 100644 index 00000000..12bab41c Binary files /dev/null and b/docs/build/doctrees/environment.pickle differ diff --git a/docs/build/doctrees/generated/jumeg.connectivity.causality.check_model_order.doctree b/docs/build/doctrees/generated/jumeg.connectivity.causality.check_model_order.doctree new file mode 100644 index 00000000..455f1cab Binary files /dev/null and b/docs/build/doctrees/generated/jumeg.connectivity.causality.check_model_order.doctree differ diff --git a/docs/build/doctrees/generated/jumeg.connectivity.causality.check_whiteness_and_consistency.doctree b/docs/build/doctrees/generated/jumeg.connectivity.causality.check_whiteness_and_consistency.doctree new file mode 100644 index 00000000..50cfb5c6 Binary files /dev/null and b/docs/build/doctrees/generated/jumeg.connectivity.causality.check_whiteness_and_consistency.doctree differ diff --git a/docs/build/doctrees/generated/jumeg.connectivity.causality.compute_causal_outflow_inflow.doctree b/docs/build/doctrees/generated/jumeg.connectivity.causality.compute_causal_outflow_inflow.doctree new file mode 100644 index 00000000..804a2974 Binary files /dev/null and b/docs/build/doctrees/generated/jumeg.connectivity.causality.compute_causal_outflow_inflow.doctree differ diff --git a/docs/build/doctrees/generated/jumeg.connectivity.causality.compute_order.doctree b/docs/build/doctrees/generated/jumeg.connectivity.causality.compute_order.doctree new file mode 100644 index 00000000..63203903 Binary files /dev/null and b/docs/build/doctrees/generated/jumeg.connectivity.causality.compute_order.doctree differ diff --git a/docs/build/doctrees/generated/jumeg.connectivity.causality.compute_order_extended.doctree b/docs/build/doctrees/generated/jumeg.connectivity.causality.compute_order_extended.doctree new file mode 100644 index 00000000..4dc38bc7 Binary files /dev/null and b/docs/build/doctrees/generated/jumeg.connectivity.causality.compute_order_extended.doctree differ diff --git a/docs/build/doctrees/generated/jumeg.connectivity.causality.consistency.doctree b/docs/build/doctrees/generated/jumeg.connectivity.causality.consistency.doctree new file mode 100644 index 00000000..669bee86 Binary files /dev/null and b/docs/build/doctrees/generated/jumeg.connectivity.causality.consistency.doctree differ diff --git a/docs/build/doctrees/generated/jumeg.connectivity.causality.do_mvar_evaluation.doctree b/docs/build/doctrees/generated/jumeg.connectivity.causality.do_mvar_evaluation.doctree new file mode 100644 index 00000000..0e26f6dd Binary files /dev/null and b/docs/build/doctrees/generated/jumeg.connectivity.causality.do_mvar_evaluation.doctree differ diff --git a/docs/build/doctrees/generated/jumeg.connectivity.causality.dw_whiteness.doctree b/docs/build/doctrees/generated/jumeg.connectivity.causality.dw_whiteness.doctree new file mode 100644 index 00000000..8ec09a44 Binary files /dev/null and b/docs/build/doctrees/generated/jumeg.connectivity.causality.dw_whiteness.doctree differ diff --git a/docs/build/doctrees/generated/jumeg.connectivity.causality.make_frequency_bands.doctree b/docs/build/doctrees/generated/jumeg.connectivity.causality.make_frequency_bands.doctree new file mode 100644 index 00000000..c14d84aa Binary files /dev/null and b/docs/build/doctrees/generated/jumeg.connectivity.causality.make_frequency_bands.doctree differ diff --git a/docs/build/doctrees/generated/jumeg.connectivity.causality.prepare_causality_matrix.doctree b/docs/build/doctrees/generated/jumeg.connectivity.causality.prepare_causality_matrix.doctree new file mode 100644 index 00000000..dc70b84b Binary files /dev/null and b/docs/build/doctrees/generated/jumeg.connectivity.causality.prepare_causality_matrix.doctree differ diff --git a/docs/build/doctrees/generated/jumeg.connectivity.find_distances_matrix.doctree b/docs/build/doctrees/generated/jumeg.connectivity.find_distances_matrix.doctree new file mode 100644 index 00000000..95a4cdb8 Binary files /dev/null and b/docs/build/doctrees/generated/jumeg.connectivity.find_distances_matrix.doctree differ diff --git a/docs/build/doctrees/generated/jumeg.connectivity.get_label_distances.doctree b/docs/build/doctrees/generated/jumeg.connectivity.get_label_distances.doctree new file mode 100644 index 00000000..11e6611f Binary files /dev/null and b/docs/build/doctrees/generated/jumeg.connectivity.get_label_distances.doctree differ diff --git a/docs/build/doctrees/generated/jumeg.connectivity.make_annot_from_csv.doctree b/docs/build/doctrees/generated/jumeg.connectivity.make_annot_from_csv.doctree new file mode 100644 index 00000000..5e4f5df5 Binary files /dev/null and b/docs/build/doctrees/generated/jumeg.connectivity.make_annot_from_csv.doctree differ diff --git a/docs/build/doctrees/generated/jumeg.connectivity.plot_degree_circle.doctree b/docs/build/doctrees/generated/jumeg.connectivity.plot_degree_circle.doctree new file mode 100644 index 00000000..f7c3e9f8 Binary files /dev/null and b/docs/build/doctrees/generated/jumeg.connectivity.plot_degree_circle.doctree differ diff --git a/docs/build/doctrees/generated/jumeg.connectivity.plot_fica_grouped_circle.doctree b/docs/build/doctrees/generated/jumeg.connectivity.plot_fica_grouped_circle.doctree new file mode 100644 index 00000000..63b6f48e Binary files /dev/null and b/docs/build/doctrees/generated/jumeg.connectivity.plot_fica_grouped_circle.doctree differ diff --git a/docs/build/doctrees/generated/jumeg.connectivity.plot_generic_grouped_circle.doctree b/docs/build/doctrees/generated/jumeg.connectivity.plot_generic_grouped_circle.doctree new file mode 100644 index 00000000..5f5e6507 Binary files /dev/null and b/docs/build/doctrees/generated/jumeg.connectivity.plot_generic_grouped_circle.doctree differ diff --git a/docs/build/doctrees/generated/jumeg.connectivity.plot_grouped_causality_circle.doctree b/docs/build/doctrees/generated/jumeg.connectivity.plot_grouped_causality_circle.doctree new file mode 100644 index 00000000..f497f67b Binary files /dev/null and b/docs/build/doctrees/generated/jumeg.connectivity.plot_grouped_causality_circle.doctree differ diff --git a/docs/build/doctrees/generated/jumeg.connectivity.plot_grouped_connectivity_circle.doctree b/docs/build/doctrees/generated/jumeg.connectivity.plot_grouped_connectivity_circle.doctree new file mode 100644 index 00000000..01efc6ae Binary files /dev/null and b/docs/build/doctrees/generated/jumeg.connectivity.plot_grouped_connectivity_circle.doctree differ diff --git a/docs/build/doctrees/generated/jumeg.connectivity.plot_labelled_group_connectivity_circle.doctree b/docs/build/doctrees/generated/jumeg.connectivity.plot_labelled_group_connectivity_circle.doctree new file mode 100644 index 00000000..41520196 Binary files /dev/null and b/docs/build/doctrees/generated/jumeg.connectivity.plot_labelled_group_connectivity_circle.doctree differ diff --git a/docs/build/doctrees/generated/jumeg.connectivity.plot_lines_and_blobs.doctree b/docs/build/doctrees/generated/jumeg.connectivity.plot_lines_and_blobs.doctree new file mode 100644 index 00000000..c5e404e5 Binary files /dev/null and b/docs/build/doctrees/generated/jumeg.connectivity.plot_lines_and_blobs.doctree differ diff --git a/docs/build/doctrees/generated/jumeg.connectivity.sensor_connectivity_3d.doctree b/docs/build/doctrees/generated/jumeg.connectivity.sensor_connectivity_3d.doctree new file mode 100644 index 00000000..0072a1f4 Binary files /dev/null and b/docs/build/doctrees/generated/jumeg.connectivity.sensor_connectivity_3d.doctree differ diff --git a/docs/build/doctrees/generated/jumeg.connectivity.weighted_con_matrix.doctree b/docs/build/doctrees/generated/jumeg.connectivity.weighted_con_matrix.doctree new file mode 100644 index 00000000..265e68ea Binary files /dev/null and b/docs/build/doctrees/generated/jumeg.connectivity.weighted_con_matrix.doctree differ diff --git a/docs/build/doctrees/index.doctree b/docs/build/doctrees/index.doctree new file mode 100644 index 00000000..01385446 Binary files /dev/null and b/docs/build/doctrees/index.doctree differ diff --git a/docs/build/html/.nojekyll b/docs/build/html/.nojekyll new file mode 100644 index 00000000..e69de29b diff --git a/docs/build/html/_downloads/02feeaf38393c62157062bb928ac0629/plot_standard_resting_network_on_aparc_annot_map.py b/docs/build/html/_downloads/02feeaf38393c62157062bb928ac0629/plot_standard_resting_network_on_aparc_annot_map.py new file mode 100644 index 00000000..28fe8cba --- /dev/null +++ b/docs/build/html/_downloads/02feeaf38393c62157062bb928ac0629/plot_standard_resting_network_on_aparc_annot_map.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +''' +========== +Standard RSNs on the connectivity circle +========== + +Plot the visualization of the standard resting state network on the +connectivity circle plot showing the Freesurfer aparc annotation map. + +This provides a quick visualization of the primary connections of the standard +resting state network. + +Uses the standard RSNs provided by [1] +[1] P. Garcés, M. C. Martín-Buro, and F. Maestú, +“Quantifying the Test-Retest Reliability of Magnetoencephalography +Resting-State Functional Connectivity,” Brain Connect., vol. 6, no. 6, +pp. 448–460, 2016. + +Author: Praveen Sripad +''' + +import os.path as op +import numpy as np +import mne + +from mne.datasets import sample +from jumeg.jumeg_utils import get_jumeg_path +from jumeg.connectivity import make_annot_from_csv +from jumeg.connectivity import plot_grouped_connectivity_circle + +data_path = sample.data_path() +subject = 'sample' +subjects_dir = op.join(data_path, 'subjects') +parc_fname = 'standard_garces_2016' +csv_fname = op.join(get_jumeg_path(), 'data', 'standard_rsns.csv') + +# set make_annot to True to save the annotation to disk +labels, coords, foci = make_annot_from_csv(subject, subjects_dir, csv_fname, + parc_fname=parc_fname, + make_annot=False, + return_label_coords=True) + +aparc = mne.read_labels_from_annot('sample', subjects_dir=subjects_dir) +aparc_names = [apa.name for apa in aparc] +lh_aparc = [mylab for mylab in aparc if mylab.hemi == 'lh'] +rh_aparc = [mylab for mylab in aparc if mylab.hemi == 'rh'] + +# get the appropriate resting state labels +rst_aparc = [] +for i, rst_label in enumerate(labels): + myfoci = foci[i] # get the vertex + if rst_label.hemi == 'lh': # vertex hemi is stored in the rst_label + for mylab in lh_aparc: + if myfoci in mylab.vertices: + print('Left: ', rst_label.name, myfoci, mylab, aparc.index(mylab)) + rst_aparc.append(mylab) + elif rst_label.hemi == 'rh': + for mylab in rh_aparc: + if myfoci in mylab.vertices: + print('Right: ', rst_label.name, myfoci, mylab, aparc.index(mylab)) + rst_aparc.append(mylab) + else: + print('ERROR: ', rst_label) + +# only 16 labels in aparc show up, there are no vertices in the left hemi for +# Frontoinsular_Median cingulate-lh +rst_indices = [aparc.index(rst) for rst in rst_aparc] + +networks = {'Visual': ['lateraloccipital-lh', 'lateraloccipital-rh'], + 'Sensorimotor': ['supramarginal-lh', 'supramarginal-rh'], + 'Auditory': ['inferiortemporal-lh', 'middletemporal-rh'], + 'DMN': ['precuneus-lh', 'inferiorparietal-lh', + 'inferiorparietal-rh', 'medialorbitofrontal-lh'], + 'Left_FP': ['inferiorparietal-lh', 'superiortemporal-lh'], + 'Right_FP': ['inferiorparietal-rh', 'superiortemporal-rh'], + 'Frontoinsular': ['inferiortemporal-lh', 'inferiortemporal-rh']} + +# make a temporary connectivity matrix +n_nodes = 68 +con = np.zeros((n_nodes, n_nodes)) + +rst_combindices = [[16, 31], [50, 14], [50, 15], [50, 28], [14, 15], + [14, 28], [15, 28], [22, 23], [14, 60], [62, 63], + [15, 61], + [16, 17]] + +# assign different values to different networks manually +con[16, 31] = 0.4 # Auditory +con[50, 14] = con[50, 15] = con[50, 28] = con[14, 15] = con[14, 28] = con[15, 28] = 0.5 # DMN +con[22, 23] = 0.6 # Visual +con[14, 60] = 0.7 # Left FP +con[62, 63] = 0.8 # Sensorimotor +con[15, 61] = 0.9 # Right FP +con[16, 17] = 1 # Frontoinsular + +con += con.T # since we only add the combinations + +# plot the connectivity circle showing standard RSNs +from matplotlib.colors import ListedColormap +cmap = ListedColormap(['m', 'k', 'b', 'y', 'r', 'c', 'g']) +yaml_fname = get_jumeg_path() + '/data/desikan_aparc_cortex_based_grouping.yaml' + +plot_grouped_connectivity_circle(yaml_fname, con, aparc_names, n_lines=12, + labels_mode=None, colormap=cmap, colorbar=True, + replacer_dict=None, indices=None, + out_fname='fig_rsn_circle_plot.png') diff --git a/docs/build/html/_downloads/047fdb71f9cb68705bd352681e6764e6/plot_label_distances.ipynb b/docs/build/html/_downloads/047fdb71f9cb68705bd352681e6764e6/plot_label_distances.ipynb new file mode 100644 index 00000000..a945551c --- /dev/null +++ b/docs/build/html/_downloads/047fdb71f9cb68705bd352681e6764e6/plot_label_distances.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Plot label distances\n\nScript to plot label distances on circle and connectome plots.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import os.path as op\n\nimport mne\nfrom mne.datasets import sample\nfrom mne_connectivity import degree\n\nfrom jumeg import get_jumeg_path\nfrom jumeg.connectivity import (get_label_distances,\n plot_grouped_connectivity_circle)\nimport yaml\n\nfrom nilearn import plotting\n\ndata_path = sample.data_path()\nsubjects_dir = op.join(data_path, 'subjects')\nsubject = 'sample'\n\nparc = 'aparc'\n\nyaml_cortex_fname = op.join(get_jumeg_path(), 'data/desikan_%s_cortex_based_grouping.yaml' % parc)\n\nlabels_fname = op.join(get_jumeg_path(), 'data/desikan_label_names.yaml')\nwith open(labels_fname, 'r') as f:\n label_names = yaml.safe_load(f)['label_names']\n\nreplacer_dict_fname = op.join(get_jumeg_path(), 'data/replacer_dictionaries.yaml')\nwith open(replacer_dict_fname, 'r') as f:\n replacer_dict = yaml.safe_load(f)['replacer_dict_%s' % parc]\n\n# compute distances between center of masses (COMs) of the labels\n# we also get the MNI coordinates of the COMs in millimetres\ncon, coords, _, _ = get_label_distances(subject, subjects_dir, parc=parc)\n\n# forget long range connections, plot short neighbouring connections\nneighbor_range = 30. # millimetres\ncon[con > neighbor_range] = 0.\n\ncortex_colors = ['m', 'b', 'y', 'c', 'r', 'g',\n 'g', 'r', 'c', 'y', 'b', 'm']\n\nout_fname = 'fig_label_com_distances_circle_%0.1f_%s.png' % (neighbor_range, parc)\nplot_grouped_connectivity_circle(yaml_cortex_fname, con, label_names,\n replacer_dict=replacer_dict,\n yaml_color_fname=None, labels_mode='replace',\n cortex_colors=cortex_colors,\n out_fname=out_fname, colorbar_pos=(0.1, 0.1),\n n_lines=None, colorbar=True,\n colormap='Reds')\n\n# compute the degree\ndegs = degree(con, threshold_prop=1)\n\n# show the label ROIs and short range connections using nilearn glass brain\nfig = plotting.plot_connectome(con, coords, node_size=degs,\n edge_threshold='99%',\n node_color='cornflowerblue',\n display_mode='ortho',\n title='%s' % parc)\n\nfig.savefig('fig_%s_labels_distance_degrees.png' % parc)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.16" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/docs/build/html/_downloads/0502bd09d5a2aa3af6cddc6b74365731/do_MLICA.py b/docs/build/html/_downloads/0502bd09d5a2aa3af6cddc6b74365731/do_MLICA.py new file mode 100644 index 00000000..8f671422 --- /dev/null +++ b/docs/build/html/_downloads/0502bd09d5a2aa3af6cddc6b74365731/do_MLICA.py @@ -0,0 +1,165 @@ +""" +========== +Do MLICA +========== + +Compute ICA object based on filtered and downsampled data. +Identify ECG and EOG artifacts using the pre-trained DCNN model +and compare results using correlation & ctps analysis. + +Apply ICA object to filtered and unfiltered data. + +Ahmad Hasasneh, Nikolas Kampel, Praveen Sripad, N. Jon Shah, and Juergen Dammers +"Deep Learning Approach for Automatic Classification of Ocular and Cardiac +Artifacts in MEG Data" +Journal of Engineering, vol. 2018, Article ID 1350692,10 pages, 2018. +https://doi.org/10.1155/2018/1350692 +""" + +import os.path as op +import matplotlib.pylab as plt +plt.ion() +import numpy as np +import mne +from jumeg.decompose.ica_replace_mean_std import ICA, ica_update_mean_std +from keras.models import load_model +from jumeg.jumeg_noise_reducer import noise_reducer +from jumeg.jumeg_preprocessing import get_ics_cardiac, get_ics_ocular +from jumeg.jumeg_plot import plot_performance_artifact_rejection +from jumeg.jumeg_utils import get_jumeg_path + +# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +# settings +# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +model_thresh = 0.8 # >0.5 ..0.9 +n_components = 40 # 30 .. 60 +njobs = 'cuda' +sfreq_new = 250 # downsampling to 250 Hz +flow_raw, flow_high = 2, 45 # high pass filter prevents from false positives +flow_ecg, fhigh_ecg = 8, 20 +flow_eog, fhigh_eog = 1, 20 +ecg_thresh, eog_thresh = 0.3, 0.3 +ecg_ch = 'ECG 001' +eog1_ch = 'EOG 001' +eog2_ch = 'EOG 002' +reject = {'mag': 5e-12} + +# number time samples is fixed to 15000 +nsamples_chop = 15000 +ix_t1 = 0 # time index: here we use the first chop +ix_t2 = ix_t1 + nsamples_chop + +# ---------------------------------------------- +# load DCNN model for artifact rejection +# the details of the model is provided in: +# x_validation_shuffle_v4_split_23.txt +# model was trained on 4D data from Juelich +# ---------------------------------------------- +model_path = op.join(get_jumeg_path(), 'data') +model_name = op.join(model_path, "dcnn_model.hdf5") +model = load_model(model_name) + +# ---------------------------------------------- +# read example data file +# ---------------------------------------------- +path_data = '/data/megraid22/Common/DeepLearning/cau_data_validation/' +raw_fname = op.join(path_data, '109925_CAU01A_100715_0842_2_c,rfDC,t1,n_bcc,nr-raw.fif') +raw = mne.io.Raw(raw_fname, preload=True) +picks = mne.pick_types(raw.info, meg=True, eeg=False, eog=False, + stim=False, exclude='bads') + + +# ---------------------------------------------- +# filtering and down sampling +# ---------------------------------------------- +# filter prior to ICA +raw_filtered = raw.copy().filter(flow_raw, flow_high, picks=picks, filter_length='auto', + l_trans_bandwidth='auto', h_trans_bandwidth='auto', + n_jobs=njobs, method='fir', phase='zero', + fir_window='hamming') +# downsample data +raw_ds = raw_filtered.copy().resample(sfreq_new, npad='auto', window='boxcar', stim_picks=None, + n_jobs=njobs, events=None) + +# ---------------------------------------------- +# crop data to get first chop +# ---------------------------------------------- +# get times to crop +dt = raw_ds.times[1] # time period between two time samples +tmin = ix_t1 * dt +tmax = ix_t2 * dt - dt # subtract one sample +# crop all raw objects +raw_chop = raw.copy().crop(tmin=tmin, tmax=tmax) # raw +raw_filtered_chop = raw_filtered.copy().crop(tmin=tmin, tmax=tmax) # raw filtered +raw_ds_chop = raw_ds.copy().crop(tmin=tmin, tmax=tmax) # raw filtered downsampled +raw_filtered.close() + +# ---------------------------------------------- +# apply ICA +# ---------------------------------------------- +ica = ICA(method='fastica', n_components=n_components, random_state=42, + max_pca_components=None, max_iter=5000, verbose=None) +# do the ICA decomposition on downsampled raw +ica.fit(raw_ds_chop, picks=picks, reject=reject, verbose=None) +sources = ica.get_sources(raw_ds_chop)._data # get sources +sources = np.reshape(sources, (n_components,nsamples_chop, 1)) # reshape sources + +# ---------------------------------------------- +# model prediction +# identification of artifact components +# ---------------------------------------------- +# compute base functions +mm = np.float32(np.dot(ica.mixing_matrix_[:, :ica.n_components_].T, + ica.pca_components_[:ica.n_components_, :ica.max_pca_components])) +# get model prediction +model_scores = model.predict([mm, sources], verbose=1) +# get ICs +bads_MLICA = list(np.where(model_scores[:,0] > model_thresh)[0]) + +# ---------------------------------------------- +# order ICs for visualization +# ---------------------------------------------- +var_order = sources.std(axis=1).flatten().argsort()[::-1] +good_ics = np.setdiff1d(var_order, bads_MLICA) +ic_order = list(np.concatenate([bads_MLICA, good_ics])) +# store components in ica object +ica.exclude = list(bads_MLICA) + + +# ---------------------------------------------- +# compare MLICA results with correlation and ctps +# ---------------------------------------------- +print('Identifying components..') +# get ECG/EOG related components using JuMEG +ic_ecg = get_ics_cardiac(raw_filtered_chop, ica, flow=flow_ecg, fhigh=fhigh_ecg, + thresh=ecg_thresh, tmin=-0.5, tmax=0.5, + name_ecg=ecg_ch, use_CTPS=True)[0] # returns both ICs and scores (take only ICs) +ic_eog = get_ics_ocular(raw_filtered_chop, ica, flow=flow_eog, fhigh=fhigh_eog, + thresh=eog_thresh, name_eog_hor=eog1_ch, + name_eog_ver=eog2_ch, score_func='pearsonr') +bads_corr_ctps = list(ic_ecg) + list(ic_eog) +bads_corr_ctps = list(set(bads_corr_ctps)) # remove potential duplicates +bads_corr_ctps.sort() +print('Bad components from MLICA:', bads_MLICA) +print('Bad components from correlation & ctps:', bads_corr_ctps) + + +# ---------------------------------------------- +# plot results +# ---------------------------------------------- +# plot sources +fig = ica.plot_sources(raw_filtered_chop, picks=ic_order, title='MLICA', show=False) +#fig.savefig('MLICA_ica-sources.png') + +# plot artifact rejection performance +fnout_fig = '109925_CAU01A_100715_0842_2_c,rfDC,0-45hz,ar-perf' +ica_filtered_chop = ica_update_mean_std(raw_filtered_chop, ica, picks=picks, reject=reject) +raw_filtered_chop_clean = ica_filtered_chop.apply(raw_filtered_chop, exclude=ica.exclude, + n_pca_components=None) +ica_unfiltered_chop = ica_update_mean_std(raw_chop, ica, picks=picks, reject=reject) +raw_unfiltered_chop_clean = ica_unfiltered_chop.apply(raw_chop, exclude=ica.exclude, n_pca_components=None) +plot_performance_artifact_rejection(raw.copy().crop(tmin=tmin, tmax=tmax), ica_unfiltered_chop, fnout_fig, + meg_clean=raw_unfiltered_chop_clean, + show=True, verbose=False, + name_ecg=ecg_ch, + name_eog=eog2_ch) diff --git a/docs/build/html/_downloads/0bf2dfa06a1770bae9694412d3acf41c/plot_annot_standard_rsns.py b/docs/build/html/_downloads/0bf2dfa06a1770bae9694412d3acf41c/plot_annot_standard_rsns.py new file mode 100644 index 00000000..db4feb84 --- /dev/null +++ b/docs/build/html/_downloads/0bf2dfa06a1770bae9694412d3acf41c/plot_annot_standard_rsns.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python3 + +''' +============= +Visualise Standard RSNs +============= + +Grow and visualize standard resting state ROIs from literature. + +1. Read ROIs of standard regions involved in resting state networks from literature. + (the data is provided as a csv file with list of regions with seed MNI coordinates) +2. Grow labels of 1cm radius (approx) in the surface source space. +3. Make annotation and visualize the labels. + +Uses RSNs provided by [1] +[1] P. Garcés, M. C. Martín-Buro, and F. Maestú, +“Quantifying the Test-Retest Reliability of Magnetoencephalography +Resting-State Functional Connectivity,” Brain Connect., vol. 6, no. 6, pp. 448–460, 2016. + +Author: Praveen Sripad +''' + +import os.path as op +import numpy as np +import mne + +from mne.datasets import sample +from jumeg.jumeg_utils import get_jumeg_path +from jumeg.connectivity import make_annot_from_csv + +from nilearn import plotting +from mne.viz import Brain + +data_path = sample.data_path() +subject = 'sample' +subjects_dir = op.join(data_path, 'subjects') +parc_fname = 'standard_garces_2016' +csv_fname = op.join(get_jumeg_path(), 'data', 'standard_rsns.csv') + +# set make_annot to True to save the annotation to disk +labels, coords, _ = make_annot_from_csv(subject, subjects_dir, csv_fname, + parc_fname=parc_fname, make_annot=False, + return_label_coords=True) + +# to plot mni coords on glass brain +n_nodes = np.array(coords).shape[0] +# make a random zero valued connectivity matrix +con = np.zeros((n_nodes, n_nodes)) +# plot the connectome on a glass brain background +plotting.plot_connectome(con, coords) +plotting.show() + +# plot the brain surface, foci and labels +Brain = mne.viz.get_brain_class() +brain = Brain(subject, hemi='both', surf='white', subjects_dir=subjects_dir) + +for mni_coord, mylabel in zip(coords, labels): + brain.add_foci(mni_coord, coords_as_verts=False, hemi=mylabel.hemi, + color='red', scale_factor=0.6) + brain.add_label(mylabel, hemi=mylabel.hemi) diff --git a/docs/build/html/_downloads/12b6bcb9b626a1d1178f7fdd3249a0ce/plot_vertices_around_seed.ipynb b/docs/build/html/_downloads/12b6bcb9b626a1d1178f7fdd3249a0ce/plot_vertices_around_seed.ipynb new file mode 100644 index 00000000..cd6ab657 --- /dev/null +++ b/docs/build/html/_downloads/12b6bcb9b626a1d1178f7fdd3249a0ce/plot_vertices_around_seed.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Plot vertices around seed.\n\nFind distances between vertices and plot vertices in a small region.\n\nmainly using functions from within mne.label.grow_labels\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import os.path as op\nimport mne\nfrom mne.datasets import sample\n\ndata_path = sample.data_path()\nsubjects_dir = op.join(data_path, 'subjects')\n\ntris, vert, dist = {}, {}, {}\nhemi = 0 # lh\n\n# read the surface\nvert[hemi], tris[hemi] = mne.read_surface(subjects_dir + '/fsaverage/surf/lh.inflated')\n\n# obtain distance matrix\ndist[hemi] = mne.label.mesh_dist(tris[hemi], vert[hemi])\n\n# choose seed vertex as 20 and plot vertices within 5mm radius around it\n# obtain neighbouring vertices within 5mm distance\nmy_verts, my_dist = mne.label._verts_within_dist(dist[hemi], [20], 5)\n\n# number of vertices in a given radius\nprint(len(my_verts))\n\nfrom surfer import Brain\nbrain = Brain('fsaverage', hemi='lh', surf='inflated',\n subjects_dir=subjects_dir)\n\nfor myv in my_verts:\n brain.add_foci(myv, coords_as_verts=True, color='b', scale_factor=0.1)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.16" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/docs/build/html/_downloads/1c4991f5f22023e28372ef784a689e5a/plot_generate_surrogate_connectivity.py b/docs/build/html/_downloads/1c4991f5f22023e28372ef784a689e5a/plot_generate_surrogate_connectivity.py new file mode 100644 index 00000000..ef2b03b5 --- /dev/null +++ b/docs/build/html/_downloads/1c4991f5f22023e28372ef784a689e5a/plot_generate_surrogate_connectivity.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python +''' +Surrogate computation +''' + +import os.path as op +import numpy as np +import matplotlib.pyplot as pl + +import mne +from mne_connectivity import spectral_connectivity_epochs +from mne.datasets import sample +from mne.minimum_norm import read_inverse_operator, apply_inverse_epochs + +from jumeg.jumeg_surrogates import Surrogates + +data_path = sample.data_path() +subjects_dir = op.join(data_path, 'subjects') + +fname_inv = op.join(data_path, 'MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif') +fname_raw = op.join(data_path, 'MEG/sample/sample_audvis_filt-0-40_raw.fif') +fname_event = op.join(data_path, 'MEG/sample/sample_audvis_filt-0-40_raw-eve.fif') + +raw = mne.io.read_raw_fif(fname_raw) +events = mne.read_events(fname_event) +inverse_operator = read_inverse_operator(fname_inv) + +# add a bad channel +raw.info['bads'] += ['MEG 2443'] + +# pick MEG channels +picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=False, eog=False, + exclude='bads') + +# Define epochs for left-auditory condition +event_id, tmin, tmax = 1, -0.2, 0.5 +epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks, + baseline=(None, 0), reject=dict(mag=4e-12, grad=4000e-13)) + +snr = 1.0 # use lower SNR for single epochs +lambda2 = 1.0 / snr ** 2 +method = "dSPM" # use dSPM method (could also be MNE or sLORETA) +stcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, method, + pick_ori="normal", return_generator=False) + +# get labels for FreeSurfer 'aparc' cortical parcellation with 34 labels/hemi +labels = mne.read_labels_from_annot('sample', parc='aparc', + subjects_dir=subjects_dir) +label_colors = [label.color for label in labels] + +# average the source estimates within each label using sign-flips to reduce +# signal cancellations, also here we can return a generator +src = inverse_operator['src'] +label_ts = mne.extract_label_time_course(stcs, labels, src, mode='mean_flip', + return_generator=False) + +# compute surrogates on the first STC extracted for 68 labels +n_surr = 5 +fmin = 8. +fmax = 13. +sfreq = raw.info['sfreq'] # the sampling frequency +con_methods = ['coh', 'plv', 'wpli'] +n_rois = len(labels) +full_surr_con = np.zeros((3, n_rois, n_rois, 1, n_surr)) + +real_con = spectral_connectivity_epochs( + label_ts, method=con_methods, mode='fourier', sfreq=sfreq, + fmin=fmin, fmax=fmax, faverage=True, n_jobs=4) + +# get the data from SpectralConnectivity object and expand it +real_con = np.array([c.get_data(output='dense') for c in real_con]) + +# loop through each of the label_ts from each epoch (i.e. 71) +# for my_label_ts in label_ts: +surr_ts = Surrogates(np.array(label_ts)) +surr_ts.original_data.shape +surr_label_ts = surr_ts.compute_surrogates(n_surr=n_surr, + return_generator=True) + +for ind_surr, surr in enumerate(surr_label_ts): + con = spectral_connectivity_epochs( + surr, method=con_methods, mode='fourier', sfreq=sfreq, + fmin=fmin, fmax=fmax, faverage=True, n_jobs=4) + + con = np.array([c.get_data(output='dense') for c in con]) + + # con now a list of arrays + # con shape (method, n_signals, n_signals, n_freqs) + full_surr_con[:, :, :, :, ind_surr] = con + assert full_surr_con.flatten().max() <= 1., 'Maximum connectivity is above 1.' + assert full_surr_con.flatten().min() >= 0., 'Minimum connectivity is 0.' + +surr_ts.clear_cache() + +# visualize the surrogates +# pl.plot(label_ts[0][0, :], 'b') +# for lts in surr_label_ts: +# pl.plot(lts[0, :], 'r') +# pl.title('Extracted label time courses - real vs surrogates') +# pl.show() + + +def sanity_check_con_matrix(con): + ''' + Check if the connectivity matrix provided satisfies necessary conditions. + This is done to ensure that the data remains clean and spurious values are + easily detected. + Expected a connectivity matrix of shape + (n_methods x n_rois x n_rois x n_freqs x n_surr) + ''' + n_methods, n_rois, n_rois, n_freqs, n_surr = con.shape + assert np.any(con), 'Matrix is not all zeros.' + assert not (con == con[0]).all(), 'All rows are equal - methods not different.' + for surr in range(1, n_surr): + assert not (con[:, :, :, :, surr] == con[:, :, :, :, 0]).all(), 'All surrogates are equal.' + assert not np.triu(con[0, :, :, 0, surr]).any(), 'Matrices not symmetric.' + + +sanity_check_con_matrix(full_surr_con) diff --git a/docs/build/html/_downloads/1d2fceab7d65c26180d6e8c827cdb8c9/plot_data_distribution.ipynb b/docs/build/html/_downloads/1d2fceab7d65c26180d6e8c827cdb8c9/plot_data_distribution.ipynb new file mode 100644 index 00000000..3f048a6a --- /dev/null +++ b/docs/build/html/_downloads/1d2fceab7d65c26180d6e8c827cdb8c9/plot_data_distribution.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Plot data distribution\n\nExample script to plot a given data distribution compared with a standard\nGaussian distribution.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import os.path as op\nimport matplotlib.pyplot as plt\nimport mne\nfrom mne.datasets import sample\nfrom jumeg.jumeg_plot import plot_histo_fit_gaussian\n\ndata_path = sample.data_path()\nsubjects_dir = op.join(data_path, 'subjects')\n\nfname_raw = op.join(data_path, 'MEG/sample/sample_audvis_filt-0-40_raw.fif')\nfname_event = op.join(data_path, 'MEG/sample/sample_audvis_filt-0-40_raw-eve.fif')\n\nraw = mne.io.read_raw_fif(fname_raw)\nevents = mne.read_events(fname_event)\n\n# add a bad channel\nraw.info['bads'] += ['MEG 2443']\n\n# pick MEG channels\npicks = mne.pick_types(raw.info, meg='mag', eeg=False, stim=False, eog=False,\n exclude='bads')\n\n# Define epochs for left-auditory condition\nevent_id, tmin, tmax = 1, -0.2, 0.5\nepochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,\n baseline=(None, 0), reject=dict(mag=4e-12))\n\ndata = epochs.get_data()\n\nfig = plot_histo_fit_gaussian(data, nbins=100, fnout=None, show=True)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.16" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/docs/build/html/_downloads/1f814f9f4cefecdffeaf615e0db8e5d1/do_granger_causality.ipynb b/docs/build/html/_downloads/1f814f9f4cefecdffeaf615e0db8e5d1/do_granger_causality.ipynb new file mode 100644 index 00000000..5a66bb1e --- /dev/null +++ b/docs/build/html/_downloads/1f814f9f4cefecdffeaf615e0db8e5d1/do_granger_causality.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Granger Causality Analysis\n\nPerform Granger based causality analysis using Generalized Parital Directed\nCoherence on example dataset.\n\nUses the data and example from mne-python combined with the Scot package\nto perform the Granger Causality analysis.\n\nAuthor: Praveen Sripad \n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nfrom scipy import stats\n\nimport mne\nfrom mne.datasets import sample\nfrom mne.minimum_norm import apply_inverse_epochs, read_inverse_operator\nfrom jumeg.jumeg_utils import get_jumeg_path\nfrom jumeg.connectivity.causality import (compute_order, do_mvar_evaluation,\n prepare_causality_matrix)\nfrom jumeg.connectivity import (plot_grouped_connectivity_circle,\n plot_grouped_causality_circle)\n\nimport scot\nimport scot.connectivity_statistics as scs\nfrom scot.connectivity import connectivity\nimport yaml\n\nimport time\nt_start = time.time()\n\nprint(('Scot version -', scot.__version__))\n\nyaml_fname = get_jumeg_path() + '/data/desikan_aparc_cortex_based_grouping.yaml'\nlabels_fname = get_jumeg_path() + '/data/desikan_label_names.yaml'\n\ndata_path = sample.data_path()\nsubjects_dir = data_path + '/subjects'\nfname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'\nfname_raw = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'\nfname_event = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'\n\n# Load data\ninverse_operator = read_inverse_operator(fname_inv)\nraw = mne.io.read_raw_fif(fname_raw)\nevents = mne.read_events(fname_event)\n\n# Add a bad channel\nraw.info['bads'] += ['MEG 2443']\n\n# Pick MEG channels\npicks = mne.pick_types(raw.info, meg=True, eeg=False, stim=False, eog=True,\n exclude='bads')\n\n# Define epochs for left-auditory condition\nevent_id, tmin, tmax = 1, -0.2, 0.5\nepochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,\n baseline=(None, 0), reject=dict(mag=4e-12, grad=4000e-13,\n eog=150e-6))\nif not epochs.preload:\n epochs.load_data()\n\n# parameters, lots of parameters\nsnr = 1.0\nlambda2 = 1.0 / snr ** 2\nmethod = \"MNE\" # use MNE method (could also be MNE or sLORETA)\nstcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, method,\n pick_ori=\"normal\", return_generator=True)\n\n# Get labels for FreeSurfer 'aparc' cortical parcellation with 34 labels/hemi\nlabels = mne.read_labels_from_annot('sample', parc='aparc',\n subjects_dir=subjects_dir)\nlabel_colors = [label.color for label in labels]\n\n# Average the source estimates within each label using sign-flips to reduce\n# signal cancellations, also here we return a generator\nsrc = inverse_operator['src']\nlabel_ts = mne.extract_label_time_course(stcs, labels, src, mode='mean_flip',\n return_generator=False)\nlabel_ts_ = np.array(label_ts)\n\nbands = ['alpha']\nfreqs = [(8, 13)]\ngcmethod = 'GPDC'\nn_surr = 1 # number of surrogates\nsurr_thresh = 95 # percentile of surr threshold used\nn_jobs = 1\nnfft = 512\n\n# normalize the representative ts\nprint('\\nperform normalization using zscoring...')\nlabel_ts = stats.zscore(label_ts_, axis=2)\n\nmorder = 15 # set fixed model order\n\n# set this to find the optimal model order using the BIC criterion\n# be advised, this takes a long time !!\n# morder, bic = compute_order(label_ts, m_max=100) # code provided by Qunxi\n# print('the model order based on BIC is..', morder)\n\n# evaluate the chosen model order\nprint(('\\nShape of label_ts -', label_ts.shape))\n# mvar needs (trials, channels, samples)\nprint(('\\nRunning for model order - ', morder))\n\nthr_cons, whit_min, whit_max = 0.8, 1., 3.\nis_white, consistency, is_stable = do_mvar_evaluation(label_ts, morder,\n whit_max, whit_min,\n thr_cons)\nprint(('model_order, whiteness, consistency, stability: %d, %s, %f, %s\\n'\n % (morder, str(is_white), consistency, str(is_stable))))\n\n# compute the Granger Partial Directed Coherence values\nprint('computing GPDC connectivity...')\n\nmvar = scot.var.VAR(morder)\n# result : array, shape (`repeats`, n_channels, n_channels, nfft)\nsurr = scs.surrogate_connectivity(gcmethod, label_ts, mvar, nfft=nfft,\n n_jobs=n_jobs, repeats=n_surr)\n\nmvar.fit(label_ts)\n# mvar coefficients (n_channels, n_channels * model_order)\n# mvar covariance matrix (n_channels, n_channels)\n# result : array, shape (n_channels, n_channels, `nfft`)\ncau = connectivity(gcmethod, mvar.coef, mvar.rescov, nfft=nfft)\n\n# get the band averaged, thresholded connectivity matrix\ncaus, max_cons, max_surrs = prepare_causality_matrix(\n cau, surr, freqs, nfft=nfft,\n sfreq=epochs.info['sfreq'], surr_thresh=surr_thresh)\n\nprint(('Shape of causality matrix: ', caus.shape))\n\n# read the label names used for plotting\n# with open(labels_fname, 'r') as f:\n# label_names = pickle.load(f)\n\nwith open(labels_fname, 'r') as f:\n label_names = yaml.safe_load(f)['label_names']\n\nplot_grouped_causality_circle(caus[0], yaml_fname, label_names, n_lines=10,\n labels_mode=None, replacer_dict=None,\n out_fname='causality_sample.png',\n colormap='Blues', colorbar=True,\n arrowstyle='->,head_length=1,head_width=1',\n figsize=(10, 6), show=False)\n\nt_end = time.time()\ntotal_time_taken = t_end - t_start\nprint(('Total time taken in minutes: %f' % (total_time_taken / 60.)))" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.16" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/docs/build/html/_downloads/2497ccb3c2bd5cd1acc86b574554d155/plot_vertices_around_seed.py b/docs/build/html/_downloads/2497ccb3c2bd5cd1acc86b574554d155/plot_vertices_around_seed.py new file mode 100644 index 00000000..d5b1183e --- /dev/null +++ b/docs/build/html/_downloads/2497ccb3c2bd5cd1acc86b574554d155/plot_vertices_around_seed.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python + +''' +========== +Plot vertices around seed. +========== + +Find distances between vertices and plot vertices in a small region. + +mainly using functions from within mne.label.grow_labels +''' + +import os.path as op +import mne +from mne.datasets import sample + +data_path = sample.data_path() +subjects_dir = op.join(data_path, 'subjects') + +tris, vert, dist = {}, {}, {} +hemi = 0 # lh + +# read the surface +vert[hemi], tris[hemi] = mne.read_surface(subjects_dir + '/fsaverage/surf/lh.inflated') + +# obtain distance matrix +dist[hemi] = mne.label.mesh_dist(tris[hemi], vert[hemi]) + +# choose seed vertex as 20 and plot vertices within 5mm radius around it +# obtain neighbouring vertices within 5mm distance +my_verts, my_dist = mne.label._verts_within_dist(dist[hemi], [20], 5) + +# number of vertices in a given radius +print(len(my_verts)) + +from surfer import Brain +brain = Brain('fsaverage', hemi='lh', surf='inflated', + subjects_dir=subjects_dir) + +for myv in my_verts: + brain.add_foci(myv, coords_as_verts=True, color='b', scale_factor=0.1) diff --git a/docs/build/html/_downloads/27c1532ddb9fad71888869e44b018e4b/plot_compute_label_distances.py b/docs/build/html/_downloads/27c1532ddb9fad71888869e44b018e4b/plot_compute_label_distances.py new file mode 100644 index 00000000..eae0ae30 --- /dev/null +++ b/docs/build/html/_downloads/27c1532ddb9fad71888869e44b018e4b/plot_compute_label_distances.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python3 + +""" +============= +Compute Label Distances +============= + +Script show how to compute and visualize distance between label center of +masses for a given subject. + +Author: Praveen Sripad +""" + +import os.path as op +from jumeg.connectivity import get_label_distances +from surfer import Brain +from nilearn import plotting +from mne.datasets import sample + +data_path = sample.data_path() +subjects_dir = op.join(data_path, 'subjects') +subject = 'sample' +parc = 'aparc_sub' + +# compute the distances between COM's of the labels +rounded_coms, coords, coms_lh, coms_rh = get_label_distances(subject, + subjects_dir, + parc=parc) +# np.save('%s_distances.npy' % subject, rounded_com) + +# get maximum distance between ROIs +print('Max distance between ROIs', rounded_coms.ravel().max()) + +# do plotting using PySurfer +brain = Brain(subject, hemi='both', surf='inflated', subjects_dir=subjects_dir) +brain.add_foci(coms_lh, coords_as_verts=True, hemi='lh') +brain.add_foci(coms_rh, coords_as_verts=True, hemi='rh') +brain.save_montage('%s_%s_coms.png' % (subject, parc), + order=['lat', 'ven', 'med'], + orientation='h', border_size=15, colorbar='auto', + row=-1, col=-1) +brain.close() + +# show the label ROIs using Nilearn plotting +fig = plotting.plot_connectome(rounded_coms, coords, + edge_threshold='99%', node_color='cornflowerblue', + title='%s - label distances' % parc) +fig.savefig('fig_%s_label_distances.png' % parc) diff --git a/docs/build/html/_downloads/2ead993c41b4ada6593445c4bd948d16/plot_connectivity_between_standard_rsns.ipynb b/docs/build/html/_downloads/2ead993c41b4ada6593445c4bd948d16/plot_connectivity_between_standard_rsns.ipynb new file mode 100644 index 00000000..ad45c549 --- /dev/null +++ b/docs/build/html/_downloads/2ead993c41b4ada6593445c4bd948d16/plot_connectivity_between_standard_rsns.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\nModified MNE-Python example script to show connectivity between standard\nresting state network labels obtained from [1].\n\n[1] P. Garc\u00e9s, M. C. Mart\u00edn-Buro, and F. Maest\u00fa,\n\u201cQuantifying the Test-Retest Reliability of Magnetoencephalography\nResting-State Functional Connectivity,\u201d Brain Connect., vol. 6, no. 6, pp.\n448\u2013460, 2016.\n\nAuthor: Praveen sripad \n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import os.path as op\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport mne\nfrom mne.datasets import sample\nfrom mne.minimum_norm import apply_inverse_epochs, read_inverse_operator\nfrom mne.viz import circular_layout\n\nfrom mne_connectivity import spectral_connectivity_epochs\nfrom mne_connectivity.viz import plot_connectivity_circle\n\ndata_path = sample.data_path()\nsubjects_dir = op.join(data_path, 'subjects')\nfname_inv = op.join(data_path, 'MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif')\nfname_raw = op.join(data_path, 'MEG/sample/sample_audvis_filt-0-40_raw.fif')\nfname_event = op.join(data_path, 'MEG/sample/sample_audvis_filt-0-40_raw-eve.fif')\n\n# Load data\ninverse_operator = read_inverse_operator(fname_inv)\nraw = mne.io.read_raw_fif(fname_raw)\nevents = mne.read_events(fname_event)\n\n# Add a bad channel\nraw.info['bads'] += ['MEG 2443']\n\n# Pick MEG channels\npicks = mne.pick_types(raw.info, meg=True, eeg=False, stim=False, eog=True,\n exclude='bads')\n\n# Define epochs for left-auditory condition\nevent_id, tmin, tmax = 1, -0.2, 0.5\nepochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,\n baseline=(None, 0), reject=dict(mag=4e-12, grad=4000e-13,\n eog=150e-6))\nif not epochs.preload:\n epochs.load_data()\n\n# Compute inverse solution and for each epoch. By using \"return_generator=True\"\n# stcs will be a generator object instead of a list.\nsnr = 1.0 # use lower SNR for single epochs\nlambda2 = 1.0 / snr ** 2\nmethod = \"MNE\" # use dSPM method (could also be MNE or sLORETA)\nstcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, method,\n pick_ori=\"normal\", return_generator=True)\n\n# Get labels for FreeSurfer 'aparc' cortical parcellation with 34 labels/hemi\nlabels = mne.read_labels_from_annot('sample', parc='standard_garces_2016',\n subjects_dir=subjects_dir)\nlabels = [lab for lab in labels if not lab.name.startswith('unknown')]\nlabel_colors = [label.color for label in labels]\n\n# Average the source estimates within each label using sign-flips to reduce\n# signal cancellations, also here we return a generator\nsrc = inverse_operator['src']\nlabel_ts = mne.extract_label_time_course(stcs, labels, src, mode='mean_flip',\n return_generator=True)\n\nfmin = 8.\nfmax = 13.\nsfreq = raw.info['sfreq'] # the sampling frequency\ncon_methods = ['coh', 'wpli']\ncon = spectral_connectivity_epochs(\n label_ts, method=con_methods, mode='multitaper', sfreq=sfreq, fmin=fmin,\n fmax=fmax, faverage=True, mt_adaptive=True, n_jobs=4)\n\n# con is a 3D array, get the connectivity for the first (and only) freq. band\n# for each method\ncon_res = dict()\nfor method, c in zip(con_methods, con):\n con_res[method] = c.get_data(output='dense')[:, :, 0]\n\n# Now, we visualize the connectivity using a circular graph layout\n# First, we reorder the labels based on their location in the left hemi\nlabel_names = [label.name for label in labels]\n\nfrom jumeg import get_jumeg_path\nyaml_fname = get_jumeg_path() + '/data/standard_garces_rsns_grouping.yaml'\n\nimport yaml\nwith open(yaml_fname, 'r') as f:\n xlabels = yaml.safe_load(f)\n\n# the yaml file has been hand curated to follow the same order as label_names\n# if not the node order has to be changed appropriately\nnode_order = list()\nnode_order.extend(label_names)\n\ngroup_bound = [len(list(key.values())[0]) for key in xlabels]\ngroup_bound = [0] + group_bound\ngroup_boundaries = [sum(group_bound[:i+1]) for i in range(len(group_bound))]\ngroup_boundaries.pop()\n\nrsn_colors = ['m', 'b', 'y', 'c', 'r', 'g', 'w']\n\ngroup_bound.pop(0)\nlabel_colors = []\nfor ind, rep in enumerate(group_bound):\n label_colors += [rsn_colors[ind]] * rep\nassert len(label_colors) == len(node_order), 'Number of colours do not match'\n\nfrom mne.viz.circle import circular_layout\nnode_angles = circular_layout(label_names, label_names, start_pos=90,\n group_boundaries=group_boundaries)\n\n# Plot the graph using node colors from the FreeSurfer parcellation.\nplot_connectivity_circle(con_res['wpli'], label_names, n_lines=300,\n node_angles=node_angles, node_colors=label_colors,\n title='Connectivity between standard RSNs')\n# plt.savefig('circle.png', facecolor='black')" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.16" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/docs/build/html/_downloads/2f0e0e87a402c26c0b09b92a92c5a6d4/plot_degree_circle.py b/docs/build/html/_downloads/2f0e0e87a402c26c0b09b92a92c5a6d4/plot_degree_circle.py new file mode 100644 index 00000000..e630c044 --- /dev/null +++ b/docs/build/html/_downloads/2f0e0e87a402c26c0b09b92a92c5a6d4/plot_degree_circle.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python + +''' +============= +Plot degree circle +============= + +Plot degree values for a given set of nodes in a simple circle plot. +''' + +import os.path as op +import numpy as np +import matplotlib.pyplot as plt + +import mne +from mne_connectivity import degree +from jumeg import get_jumeg_path +from jumeg.connectivity import plot_degree_circle + +import bct + +orig_labels_fname = op.join(get_jumeg_path(), 'data/desikan_label_names.yaml') +yaml_fname = op.join(get_jumeg_path(), 'data/desikan_aparc_cortex_based_grouping.yaml') +con_fname = op.join(get_jumeg_path(), 'data/sample,aparc-con.npy') + +con = np.load(con_fname) +con_ = con[0, :, :, 2] + con[0, :, :, 2].T + +# compute the degree +degrees = degree(con_, threshold_prop=0.2) + +fig, ax = plot_degree_circle(degrees, yaml_fname, orig_labels_fname) diff --git a/docs/build/html/_downloads/30323af8a5a552a5eaf919de8c797495/plot_test_transform_mni_to_ras.py b/docs/build/html/_downloads/30323af8a5a552a5eaf919de8c797495/plot_test_transform_mni_to_ras.py new file mode 100644 index 00000000..ac4b47fe --- /dev/null +++ b/docs/build/html/_downloads/30323af8a5a552a5eaf919de8c797495/plot_test_transform_mni_to_ras.py @@ -0,0 +1,57 @@ +""" +To plot a vertex point, convert it to MNI coordinates and then reconvert it back to RAS to obtain the vertex number. + +It works when 'fsaverage' subject is used, but does not when any other subjects are used. +""" + +import os +import os.path as op +import mne +from mne.datasets import sample +from surfer import utils + +print(__doc__) + +data_path = sample.data_path() +fname_inv = op.join(data_path, 'MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif') +fname_evoked = op.join(data_path, 'MEG/sample/sample_audvis-ave.fif') +subjects_dir = op.join(data_path, 'subjects') +os.environ['SUBJECTS_DIR'] = subjects_dir + +stc_fname = op.join(data_path, 'MEG/sample/sample_audvis-meg') +stc = mne.read_source_estimate(stc_fname) + +morph = mne.compute_source_morph(stc, subject_from='sample', + subject_to='fsaverage', spacing=5, subjects_dir=subjects_dir) +new_stc = morph.apply(stc) + +subject = 'fsaverage' + +# Plot brain in 3D with PySurfer if available +brain = new_stc.plot(subject, hemi='lh', + subjects_dir=subjects_dir, backend='pyvistaqt') +brain.show_view('lateral') + +# use peak getter to move vizualization to the time point of the peak +vertno_max, time_idx = new_stc.get_peak(hemi='lh', time_as_index=True) + +brain.set_time_point(time_idx) + +# draw marker at maximum peaking vertex +brain.add_foci(vertno_max, coords_as_verts=True, hemi='lh', color='blue', + scale_factor=0.6, map_surface='white') + +mni_coords = mne.vertex_to_mni(vertno_max, hemis=0, subject=subject, + subjects_dir=subjects_dir) +print('The MNI coords are ', mni_coords) + +# my_trans = mne.read_trans(?) +# src_pts = apply_trans(trans, some_tgt_pts) + +utils.coord_to_label(subject, mni_coords, label='mycoord', + hemi='lh', n_steps=25, map_surface="white") +brain.add_label('mycoord-lh.label', color="darkseagreen", alpha=.8) + +# if the new mni_coords are computed +brain.add_foci(mni_coords, coords_as_verts=False, hemi='lh', + color='red', scale_factor=0.6) diff --git a/docs/build/html/_downloads/314892b76c9227ed158db61e71b36cf2/plot_generate_surrogate_stcs.ipynb b/docs/build/html/_downloads/314892b76c9227ed158db61e71b36cf2/plot_generate_surrogate_stcs.ipynb new file mode 100644 index 00000000..f8f5f52f --- /dev/null +++ b/docs/build/html/_downloads/314892b76c9227ed158db61e71b36cf2/plot_generate_surrogate_stcs.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Generate surrogate STCs\n\n\nExample to show surrogate generation on STCs using the jumeg Surrogates\nmodule.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import os.path as op\nimport numpy as np\nimport matplotlib.pyplot as pl\n\nfrom mne.datasets import sample\nfrom mne.minimum_norm import read_inverse_operator, apply_inverse_epochs\nimport mne\n\nfrom jumeg.jumeg_surrogates import Surrogates, check_power_spectrum\n\ndata_path = sample.data_path()\nsubjects_dir = op.join(data_path, 'subjects')\n\nfname_inv = op.join(data_path, 'MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif')\nfname_raw = op.join(data_path, 'MEG/sample/sample_audvis_filt-0-40_raw.fif')\nfname_event = op.join(data_path, 'MEG/sample/sample_audvis_filt-0-40_raw-eve.fif')\n\nstcs_testing = True\n\nraw = mne.io.read_raw_fif(fname_raw)\nevents = mne.read_events(fname_event)\ninverse_operator = read_inverse_operator(fname_inv)\n\n# add a bad channel\nraw.info['bads'] += ['MEG 2443']\n\n# pick MEG channels\npicks = mne.pick_types(raw.info, meg=True, eeg=False, stim=False, eog=False,\n exclude='bads')\n\n# define epochs for left-auditory condition\nevent_id, tmin, tmax = 1, -0.2, 0.5\nepochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,\n baseline=(None, 0), reject=dict(mag=4e-12, grad=4000e-13))\n\n\nsnr = 1.0 # use lower SNR for single epochs\nlambda2 = 1.0 / snr ** 2\nmethod = \"dSPM\" # use dSPM method (could also be MNE or sLORETA)\nstcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, method,\n pick_ori=\"normal\", return_generator=False)\n\n# compute surrogates for one STC\nsurr_stcs = Surrogates(stcs[0])\nmysurr = surr_stcs.compute_surrogates(n_surr=10, return_generator=False)\n\n# check if surrogates are correctly computed\nassert not np.array_equal(mysurr[0].data,\n mysurr[1].data), 'Surrogates mostly equal'\nassert not np.array_equal(stcs[0].data,\n mysurr[2].data), 'Surrogates equal to original'\n\n# visualize results by plotting 1 the average across voxels\n# of original and surrogate STC\npl.plot(stcs[0].data.mean(axis=0))\nfor i in mysurr:\n pl.plot(i.data.mean(axis=0), color='r')\npl.title('Averaged real vs surrogate source time courses')\npl.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.16" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/docs/build/html/_downloads/32e63256705a22009f3d3ad7527dd8d3/plot_perform_mft_surface.ipynb b/docs/build/html/_downloads/32e63256705a22009f3d3ad7527dd8d3/plot_perform_mft_surface.ipynb new file mode 100644 index 00000000..f16322e5 --- /dev/null +++ b/docs/build/html/_downloads/32e63256705a22009f3d3ad7527dd8d3/plot_perform_mft_surface.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Jumeg MFT example.\n\nPerform MFT on a surface based forward solution.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import os\nimport os.path as op\nimport numpy as np\n\nimport mne\nfrom mne.datasets import sample\n\nfrom jumeg.mft import apply_mft\nfrom jumeg.mft import jumeg_mft_plot\n\ndata_path = sample.data_path()\nsubject = 'sample'\nsubjects_dir = op.join(data_path, 'subjects')\nfwdname = op.join(data_path, 'MEG/sample/sample_audvis-meg-oct-6-fwd.fif')\nlblname = 'aparc'\nevoname = op.join(data_path, 'MEG/sample/sample_audvis-ave.fif')\nevocondition = 'Left Auditory'\nrawname = op.join(data_path, 'MEG/sample/sample_audvis_10s-raw.fif')\nt1_fname = op.join(subjects_dir, 'sample/mri/T1.mgz')\n\n# Set up pick list: MEG - bad channels\nwant_meg = 'mag'\nwant_ref = False\nwant_eeg = False\nwant_stim = False\nexclude = 'bads'\ninclude = []\n\nprint(\"########## MFT parameters:\")\n# mftpar = { 'prbfct':'Gauss',\n# 'prbcnt':np.array([[-1.039, 0.013,0.062],[-0.039, 0.013,0.062]]),\n# 'prbhw':np.array([[0.040,0.040,0.040],[0.040,0.040,0.040]]) }\nmftpar = {'prbfct': 'uniform',\n 'prbcnt': None,\n 'prbhw': None}\nmftpar.update({'iter': 2, 'currexp': 1.0})\nmftpar.update({'regtype': 'PzetaE', 'zetareg': 1.00})\n# mftpar.update({ 'regtype':'classic', 'zetareg':1.0})\nmftpar.update({'solver': 'lu', 'svrelcut': 5.e-4})\n\nprint(\"mftpar['prbcnt' ] = \", mftpar['prbcnt'])\nprint(\"mftpar['prbhw' ] = \", mftpar['prbhw'])\nprint(\"mftpar['iter' ] = \", mftpar['iter'])\nprint(\"mftpar['regtype' ] = \", mftpar['regtype'])\nprint(\"mftpar['zetareg' ] = \", mftpar['zetareg'])\nprint(\"mftpar['solver' ] = \", mftpar['solver'])\nprint(\"mftpar['svrelcut'] = \", mftpar['svrelcut'])\ncdmcut = 0.10\nprint(\"cdmcut = \", cdmcut)\n\nprint(\"########## get labels:\")\nif lblname is not None:\n labels = mne.read_labels_from_annot(subject, parc=lblname,\n subjects_dir=subjects_dir)\nelse:\n labels = None\n\nprint(\"##########################\")\nprint(\"##### Calling apply_mft()\")\nprint(\"##########################\")\nfwd = mne.read_forward_solution(fwdname, verbose=True)\nfwdspec = mne.io.pick.pick_types_forward(fwd, meg=want_meg, ref_meg=False,\n eeg=False, exclude=exclude)\ndataspec = mne.read_evokeds(evoname, condition=evocondition,\n baseline=(None, 0), verbose=True)\nfwdmag, qualmft, stc_mft = apply_mft(fwdspec, dataspec, evocondition=evocondition,\n subject=subject, meg=want_meg, save_stc=False,\n calccdm='all', cdmcut=cdmcut, cdmlabels=labels,\n mftpar=mftpar, verbose='verbose')\n\nevo = mne.read_evokeds(evoname, condition=evocondition, baseline=(None, 0))\ntmin = -0.2\ntstep = 1. / evo.info['sfreq']\n\nstcdata = stc_mft.data\n\nprint(\" \")\nprint(\"########## Some geo-numbers:\")\nlhinds = np.where(fwdmag['source_rr'][:, 0] <= 0.)\nrhinds = np.where(fwdmag['source_rr'][:, 0] > 0.)\nprint(\"> Discriminating lh/rh by sign of fwdmag['source_rr'][:,0]:\")\nprint(\"> lhinds[0].shape[0] = \", lhinds[0].shape[0], \" rhinds[0].shape[0] = \", rhinds[0].shape[0])\ninvmri_head_t = mne.transforms.invert_transform(fwdmag['info']['mri_head_t'])\nmrsrc = np.zeros(fwdmag['source_rr'].shape)\nmrsrc = mne.transforms.apply_trans(invmri_head_t['trans'], fwdmag['source_rr'], move=True)\nlhmrinds = np.where(mrsrc[:, 0] <= 0.)\nrhmrinds = np.where(mrsrc[:, 0] > 0.)\nprint(\"> Discriminating lh/rh by sign of fwdmag['source_rr'][:,0] in MR coords:\")\nprint(\"> lhmrinds[0].shape[0] = \", lhmrinds[0].shape[0], \" rhmrinds[0].shape[0] = \", rhmrinds[0].shape[0])\n\n# plotting routines\njumeg_mft_plot.plot_global_cdv_dist(stcdata)\njumeg_mft_plot.plot_visualize_mft_sources(fwdmag, stcdata, tmin=tmin, tstep=tstep,\n subject=subject, subjects_dir=subjects_dir)\njumeg_mft_plot.plot_cdv_distribution(fwdmag, stcdata)\njumeg_mft_plot.plot_max_amplitude_data(fwdmag, stcdata, tmin=tmin, tstep=tstep,\n subject=subject)\njumeg_mft_plot.plot_max_cdv_data(stc_mft, lhmrinds, rhmrinds)\njumeg_mft_plot.plot_cdvsum_data(stc_mft, lhmrinds, rhmrinds)\njumeg_mft_plot.plot_quality_data(qualmft, stc_mft)\njumeg_mft_plot.plot_cdm_data(qualmft, stc_mft, cdmlabels=labels)\njumeg_mft_plot.plot_jlong_labeldata(qualmft, stc_mft, labels)\njumeg_mft_plot.plot_jtotal_labeldata(qualmft, stc_mft, labels)\n\njumeg_mft_plot.plot_jlong_data(qualmft, stc_mft)\n\nprint(\"Done.\")" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.16" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/docs/build/html/_downloads/33957b832997ae6a669523320859666a/plot_causality_circle.ipynb b/docs/build/html/_downloads/33957b832997ae6a669523320859666a/plot_causality_circle.ipynb new file mode 100644 index 00000000..a2ceb773 --- /dev/null +++ b/docs/build/html/_downloads/33957b832997ae6a669523320859666a/plot_causality_circle.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Plot Causality Matrix\n\nExample showing how to plot a causality matrix on a circle plot.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\n\nfrom jumeg import get_jumeg_path\nfrom jumeg.connectivity import plot_grouped_causality_circle\nimport yaml\n\n# load the yaml grouping of Freesurfer labels\nyaml_fname = get_jumeg_path() + '/data/desikan_aparc_cortex_based_grouping.yaml'\nlabels_fname = get_jumeg_path() + '/data/desikan_label_names.yaml'\nreplacer_dict_fname = get_jumeg_path() + '/data/replacer_dictionaries.yaml'\n\nwith open(labels_fname, 'r') as f:\n label_names = yaml.safe_load(f)['label_names']\n\nwith open(replacer_dict_fname, 'r') as f:\n replacer_dict = yaml.safe_load(f)['replacer_dict_aparc']\n\n# make a random causality matrix\nn_nodes = 68 # currently needs to be always this number\ncaus = np.random.random((n_nodes, n_nodes))\ncaus[np.diag_indices_from(caus)] = 0.\ncaus[caus < 0.7] = 0.\n\nplot_grouped_causality_circle(caus, yaml_fname, label_names, n_lines=10,\n labels_mode='replace', replacer_dict=replacer_dict,\n out_fname='fig_causality_circle.png',\n colormap='Blues', colorbar=True,\n figsize=(6, 6), show=False,\n arrowstyle='->,head_length=1,head_width=1')" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.16" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/docs/build/html/_downloads/360c840f05a6327fac8f545530641677/plot_noise_reducer.ipynb b/docs/build/html/_downloads/360c840f05a6327fac8f545530641677/plot_noise_reducer.ipynb new file mode 100644 index 00000000..306883ed --- /dev/null +++ b/docs/build/html/_downloads/360c840f05a6327fac8f545530641677/plot_noise_reducer.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Plot noise reducer\n\nScript to show the application of noise reducer on jusample data.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import os\nimport os.path as op\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom jumeg.jumeg_noise_reducer import noise_reducer\n\nimport mne\n\nplt.ion()\n\n# load the jumeg sample data (has to be BTI)\nif os.environ.get('JUSAMPLE_MEG_PATH'):\n data_dir = os.environ['JUSAMPLE_MEG_PATH']\nelse:\n print('Data unavailable, skipping.')\n sys.exit()\n\nsubject = '207184'\nraw_fname = op.join(data_dir, 'recordings', subject,\n 'sample_207184_rest_EC-raw.fif')\n\nraw = mne.io.Raw(raw_fname, preload=True)\n\nfig, (ax1, ax2, ax3, ax4, ax5) = plt.subplots(5, 1, sharex=True, sharey=True)\n\npicks = mne.pick_types(raw.info, meg='mag', exclude='bads')\nraw.plot_psd(fmin=0., fmax=100., tmin=None, tmax=60.,\n n_fft=None, picks=picks, ax=ax1);\nax1.set_title('Original')\n\n# notch filter\nraw_notch = raw.copy().notch_filter(np.arange(50, 251, 50), picks=picks,\n filter_length='auto',\n notch_widths=None, n_jobs=4, method='fir',\n phase='zero-double',\n fir_window='hamming', fir_design='firwin')\nraw_notch.plot_psd(fmin=0., fmax=100., tmin=None, tmax=60.,\n n_fft=None, picks=picks, ax=ax2);\nax2.set_title('Notch filter 50Hz applied')\n\n# powerline removal using noise_reducer\nraw_nr_notch = noise_reducer(raw_fname, raw=raw.copy(), detrending=False,\n reflp=None, refhp=None, refnotch=[50., 100., 150.],\n return_raw=True, verbose=False)\nraw_nr_notch.plot_psd(fmin=0., fmax=100., tmin=None, tmax=60.,\n n_fft=None, picks=picks, ax=ax3);\nax3.set_title('Noise reducer notch filter 50Hz applied')\n\n\n# remove high freq noise (>0.1Hz) from ref channels\nraw_nr2 = noise_reducer(raw_fname, raw=raw_nr_notch, detrending=False,\n reflp=None, refhp=0.1, refnotch=None,\n return_raw=True, verbose=False)\nraw_nr2.plot_psd(fmin=0., fmax=100., tmin=None, tmax=60.,\n n_fft=None, picks=picks, ax=ax4);\nax4.set_title('Noise reducer high pass filtered 0.1Hz')\n\n# remove low freq noise (<5Hz) from ref channels\nraw_nr = noise_reducer(raw_fname, raw=raw_nr2, detrending=False,\n reflp=5., refhp=None, refnotch=None,\n return_raw=True, verbose=False)\nraw_nr.plot_psd(fmin=0., fmax=100., tmin=None, tmax=60.,\n n_fft=None, picks=picks, ax=ax5);\nax5.set_title('Noise reducer low pass filtered 5Hz')\n\nplt.tight_layout()\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.16" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/docs/build/html/_downloads/39b0f1d0381e68fb8eadecc32fb37b10/plot_perform_mft_surface.py b/docs/build/html/_downloads/39b0f1d0381e68fb8eadecc32fb37b10/plot_perform_mft_surface.py new file mode 100644 index 00000000..2521fe43 --- /dev/null +++ b/docs/build/html/_downloads/39b0f1d0381e68fb8eadecc32fb37b10/plot_perform_mft_surface.py @@ -0,0 +1,115 @@ +""" +==================== +Jumeg MFT example. +==================== + +Perform MFT on a surface based forward solution. +""" + +import os +import os.path as op +import numpy as np + +import mne +from mne.datasets import sample + +from jumeg.mft import apply_mft +from jumeg.mft import jumeg_mft_plot + +data_path = sample.data_path() +subject = 'sample' +subjects_dir = op.join(data_path, 'subjects') +fwdname = op.join(data_path, 'MEG/sample/sample_audvis-meg-oct-6-fwd.fif') +lblname = 'aparc' +evoname = op.join(data_path, 'MEG/sample/sample_audvis-ave.fif') +evocondition = 'Left Auditory' +rawname = op.join(data_path, 'MEG/sample/sample_audvis_10s-raw.fif') +t1_fname = op.join(subjects_dir, 'sample/mri/T1.mgz') + +# Set up pick list: MEG - bad channels +want_meg = 'mag' +want_ref = False +want_eeg = False +want_stim = False +exclude = 'bads' +include = [] + +print("########## MFT parameters:") +# mftpar = { 'prbfct':'Gauss', +# 'prbcnt':np.array([[-1.039, 0.013,0.062],[-0.039, 0.013,0.062]]), +# 'prbhw':np.array([[0.040,0.040,0.040],[0.040,0.040,0.040]]) } +mftpar = {'prbfct': 'uniform', + 'prbcnt': None, + 'prbhw': None} +mftpar.update({'iter': 2, 'currexp': 1.0}) +mftpar.update({'regtype': 'PzetaE', 'zetareg': 1.00}) +# mftpar.update({ 'regtype':'classic', 'zetareg':1.0}) +mftpar.update({'solver': 'lu', 'svrelcut': 5.e-4}) + +print("mftpar['prbcnt' ] = ", mftpar['prbcnt']) +print("mftpar['prbhw' ] = ", mftpar['prbhw']) +print("mftpar['iter' ] = ", mftpar['iter']) +print("mftpar['regtype' ] = ", mftpar['regtype']) +print("mftpar['zetareg' ] = ", mftpar['zetareg']) +print("mftpar['solver' ] = ", mftpar['solver']) +print("mftpar['svrelcut'] = ", mftpar['svrelcut']) +cdmcut = 0.10 +print("cdmcut = ", cdmcut) + +print("########## get labels:") +if lblname is not None: + labels = mne.read_labels_from_annot(subject, parc=lblname, + subjects_dir=subjects_dir) +else: + labels = None + +print("##########################") +print("##### Calling apply_mft()") +print("##########################") +fwd = mne.read_forward_solution(fwdname, verbose=True) +fwdspec = mne.io.pick.pick_types_forward(fwd, meg=want_meg, ref_meg=False, + eeg=False, exclude=exclude) +dataspec = mne.read_evokeds(evoname, condition=evocondition, + baseline=(None, 0), verbose=True) +fwdmag, qualmft, stc_mft = apply_mft(fwdspec, dataspec, evocondition=evocondition, + subject=subject, meg=want_meg, save_stc=False, + calccdm='all', cdmcut=cdmcut, cdmlabels=labels, + mftpar=mftpar, verbose='verbose') + +evo = mne.read_evokeds(evoname, condition=evocondition, baseline=(None, 0)) +tmin = -0.2 +tstep = 1. / evo.info['sfreq'] + +stcdata = stc_mft.data + +print(" ") +print("########## Some geo-numbers:") +lhinds = np.where(fwdmag['source_rr'][:, 0] <= 0.) +rhinds = np.where(fwdmag['source_rr'][:, 0] > 0.) +print("> Discriminating lh/rh by sign of fwdmag['source_rr'][:,0]:") +print("> lhinds[0].shape[0] = ", lhinds[0].shape[0], " rhinds[0].shape[0] = ", rhinds[0].shape[0]) +invmri_head_t = mne.transforms.invert_transform(fwdmag['info']['mri_head_t']) +mrsrc = np.zeros(fwdmag['source_rr'].shape) +mrsrc = mne.transforms.apply_trans(invmri_head_t['trans'], fwdmag['source_rr'], move=True) +lhmrinds = np.where(mrsrc[:, 0] <= 0.) +rhmrinds = np.where(mrsrc[:, 0] > 0.) +print("> Discriminating lh/rh by sign of fwdmag['source_rr'][:,0] in MR coords:") +print("> lhmrinds[0].shape[0] = ", lhmrinds[0].shape[0], " rhmrinds[0].shape[0] = ", rhmrinds[0].shape[0]) + +# plotting routines +jumeg_mft_plot.plot_global_cdv_dist(stcdata) +jumeg_mft_plot.plot_visualize_mft_sources(fwdmag, stcdata, tmin=tmin, tstep=tstep, + subject=subject, subjects_dir=subjects_dir) +jumeg_mft_plot.plot_cdv_distribution(fwdmag, stcdata) +jumeg_mft_plot.plot_max_amplitude_data(fwdmag, stcdata, tmin=tmin, tstep=tstep, + subject=subject) +jumeg_mft_plot.plot_max_cdv_data(stc_mft, lhmrinds, rhmrinds) +jumeg_mft_plot.plot_cdvsum_data(stc_mft, lhmrinds, rhmrinds) +jumeg_mft_plot.plot_quality_data(qualmft, stc_mft) +jumeg_mft_plot.plot_cdm_data(qualmft, stc_mft, cdmlabels=labels) +jumeg_mft_plot.plot_jlong_labeldata(qualmft, stc_mft, labels) +jumeg_mft_plot.plot_jtotal_labeldata(qualmft, stc_mft, labels) + +jumeg_mft_plot.plot_jlong_data(qualmft, stc_mft) + +print("Done.") diff --git a/docs/build/html/_downloads/3c67b6f91f0cf2029ca171963f358cab/plot_labelled_connectivity_circle.ipynb b/docs/build/html/_downloads/3c67b6f91f0cf2029ca171963f358cab/plot_labelled_connectivity_circle.ipynb new file mode 100644 index 00000000..b1a3d01b --- /dev/null +++ b/docs/build/html/_downloads/3c67b6f91f0cf2029ca171963f358cab/plot_labelled_connectivity_circle.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Plot labelled connectivity circle\n\nExample exposing the plot_labelled_group_connectivity_circle function.\n\nAuthor: Praveen Sripad \n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import os.path as op\nfrom jumeg.connectivity import (plot_labelled_group_connectivity_circle,\n generate_random_connectivity_matrix)\nfrom jumeg import get_jumeg_path\nimport yaml\n\n# load the yaml grouping of Freesurfer labels\nyaml_fname = op.join(get_jumeg_path(), 'data/rsn_desikan_aparc_cortex_grouping.yaml')\nlabel_names_yaml_fname = op.join(get_jumeg_path(), 'data/desikan_label_names.yaml')\n\nwith open(label_names_yaml_fname, 'r') as f:\n label_names = yaml.safe_load(f)['label_names']\n\n# make a random matrix with 68 nodes\ncon = generate_random_connectivity_matrix(size=(68, 68), symmetric=True)\n\n# plotting within a subplot\nplot_labelled_group_connectivity_circle(yaml_fname, con, label_names,\n out_fname='fig_rsn_circle.png',\n show=False, n_lines=20,\n fontsize_names=6,\n title='test RSN circ labels')" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.16" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/docs/build/html/_downloads/3c7a4ed9e3829176ce3989bcf05ecfed/plot_generic_grouped_connectivity_circle.ipynb b/docs/build/html/_downloads/3c7a4ed9e3829176ce3989bcf05ecfed/plot_generic_grouped_connectivity_circle.ipynb new file mode 100644 index 00000000..00cc9f62 --- /dev/null +++ b/docs/build/html/_downloads/3c7a4ed9e3829176ce3989bcf05ecfed/plot_generic_grouped_connectivity_circle.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Generic Grouped Connectivity Circle\n\nScript exposing circle plots with outer ring.\n\nAuthor: Praveen Sripad \n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import os.path as op\nfrom jumeg.connectivity import (plot_generic_grouped_circle,\n plot_fica_grouped_circle,\n generate_random_connectivity_matrix)\nfrom jumeg import get_jumeg_path\n\n# load the yaml grouping of Freesurfer labels\nyaml_fname = op.join(get_jumeg_path(), 'data/rsn_desikan_aparc_cortex_grouping.yaml')\n\n# make a random matrix\ncon = generate_random_connectivity_matrix(size=(34, 34), symmetric=True)\n\n# load the label names in the original order\n# this should be same order as the connectivity matrix\nlabels_fname = op.join(get_jumeg_path(), 'data/fica_names.txt')\nwith open(labels_fname, 'r') as f:\n orig_labels = [line.rstrip('\\n') for line in f]\n\n# plot the connectivity circle grouped\nplot_generic_grouped_circle(yaml_fname, con, orig_labels,\n node_order_size=34,\n out_fname='fig_fica_circle.png',\n show=False, n_lines=20,\n title='Groups')\n\n# plot the connectivity circle with outer group labels ring\nplot_fica_grouped_circle(yaml_fname, con, orig_labels,\n node_order_size=34,\n out_fname='fig_fica_circle_with_names.png',\n show=False, n_lines=20,\n title='Groups + Labels')" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.16" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/docs/build/html/_downloads/3e04c82ff2ffa8cefb954f9ce5a38925/plot_rank_estimation.ipynb b/docs/build/html/_downloads/3e04c82ff2ffa8cefb954f9ce5a38925/plot_rank_estimation.ipynb new file mode 100644 index 00000000..a5ae1723 --- /dev/null +++ b/docs/build/html/_downloads/3e04c82ff2ffa8cefb954f9ce5a38925/plot_rank_estimation.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Plot rank estimation\n\nExample script to estimate the rank of the given data array.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import os.path as op\nimport mne\nimport numpy as np\nfrom mne.datasets import sample\nfrom sklearn.decomposition import PCA\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nfrom jumeg.jumeg_utils import rank_estimation\nfrom jumeg.decompose.dimension_selection import mibs, bic, gap, aic, mdl, explVar, fa_rank_cv, pca_rank_cv\n\n# ----------------------------------------\n# filenames and path\n# ----------------------------------------\ndata_path = sample.data_path()\nsubjects_dir = op.join(data_path, 'subjects')\nfname_raw = op.join(data_path, 'MEG/sample/sample_audvis_filt-0-40_raw.fif')\nfname_event = op.join(data_path, 'MEG/sample/sample_audvis_filt-0-40_raw-eve.fif')\n\n# ----------------------------------------\n# read data and crop to speedup the process\n# ----------------------------------------\nraw = mne.io.read_raw_fif(fname_raw)\nevents = mne.read_events(fname_event)\n# add a bad channel\nraw.info['bads'] += ['MEG 2443']\n# pick MEG channels\npicks = mne.pick_types(raw.info, meg='mag', eeg=False, stim=False, eog=False,\n exclude='bads')\n# crop data to speed-up process\nraw.crop(tmax=180)\ndata = raw.get_data()[picks, :] # data *= 1e12 will change the results !\n\n# =========================================\n# Method 1:\n# apply various dimension reduction tools\n# to estimate the median of all\n# =========================================\nrank_all, rank_median = rank_estimation(data)\nprint ('\\nRank estimation using methods implemented in jumeg (including whitening)')\nprint('Ranks in order: MIBS, BIC, GAP, AIC, MDL, pct95, pct99: ', rank_all)\nprint('The median of the data is %f\\n' % rank_median)\n\n\n\n# =========================================\n# Method 2:\n# apply a single method for rank estimation\n# using whitening provided by sklearn\n# here we apply all methods separately\n# =========================================\n# perform PCA\npca = PCA(svd_solver='auto', whiten=True)\npc = pca.fit_transform(data.T)\nn_samples, n_features = pc.shape\n\n# rank estimation of a single method\nrank_mibs = mibs(pca.explained_variance_, n_samples) # MIBS\nrank_bic = bic(pca.explained_variance_, n_samples) # BIC\nrank_gap = gap(pca.explained_variance_) # GAP\nrank_aic = aic(pca.explained_variance_) # AIC\nrank_mdl = mdl(pca.explained_variance_) # MDL\nrank_expl95 = explVar(pca.explained_variance_, explainedVar=0.95) # expl. variance (95)\nrank_expl99 = explVar(pca.explained_variance_, explainedVar=0.99) # expl. variance (99)\nlabel_mibs = 'MIBS: n_comp = %d' % (rank_mibs)\nlabel_bic = 'BIC: n_comp = %d' % (rank_bic)\nlabel_gap = 'GAP: n_comp = %d' % (rank_gap)\nlabel_aic = 'AIC: n_comp = %d' % (rank_aic)\nlabel_mdl = 'MDL: n_comp = %d' % (rank_mdl)\nlabel_expl95 = 'expl95: n_comp = %d' % (rank_expl95)\nlabel_expl99 = 'expl99: n_comp = %d' % (rank_expl99)\nprint (label_mibs)\nprint (label_bic)\nprint (label_gap)\nprint (label_aic)\nprint (label_mdl)\nprint (label_expl95)\nprint (label_expl99)\n\n\n# -------------------------------------------\n# Method 3\n# apply rank estimation utilizing cross-validation\n# using PCA and FA scores\n# Note, on normal data sets this will take a long time\n# -------------------------------------------\n# define a list of components to test\n# here we use all components from above and add a few more for testing\nncomp_list = np.unique(np.concatenate([rank_all[rank_all > 0], [40, 50]]))\nncomp_list.sort()\ncv = 5 # depends on data length\nprint ('>>> Please be patient, this might take a while ....')\nprint ('')\n# PCA: test a list of numbers in a cross-validation scenario\nrank_cv_pca = pca_rank_cv(data, ncomp_list, cv=cv, whiten=True)\n\n# FA: test a list of components in a cross-validation scenario\nrank_cv_fa = fa_rank_cv(pc.T, ncomp_list, cv=cv)\n\nlabel_cv_pca = 'PCA (CV=%d): %d' % (cv, rank_cv_pca)\nlabel_cv_fa = 'FA (CV=%d): %d' % (cv, rank_cv_fa)\n\n\n# ----------------------\n# plot results (Scree plot)\n# ----------------------\nlabels = np.array([label_aic, label_bic, label_gap, label_mdl, label_mibs, label_expl95, label_expl99])\ncomps = np.array([rank_aic, rank_bic, rank_gap, rank_mdl, rank_mibs, rank_expl95, rank_expl99])\n# sorting by increasing number of components\nixsort = comps.argsort()\ncomps = comps[ixsort]\nlabels = labels[ixsort]\n\n# components estimated using CV\nlabel_cv = [label_cv_pca, label_cv_fa]\ncomps_cv = [rank_cv_pca, rank_cv_fa]\n\n# plot figure\ncmap = cm.get_cmap('Dark2') # 8 colors\ncolors = cmap.colors[::-1]\nxaxis = np.arange(n_features)+1\nfig = plt.figure(figsize=(10, 6))\nplt.plot(xaxis, np.cumsum(pca.explained_variance_ratio_ * 100), marker='o', color='black')\nplt.title('Scree plot')\nplt.xlabel('# components')\nplt.ylabel('explained variance / %')\n# plot vertical line and label for each method\nmethods = []\nfor i in range(len(comps)):\n if (comps[i] > 0):\n hl = plt.axvline(x=comps[i], color=colors[i], label=labels[i], linestyle='--')\n methods.append(hl)\nlegend1 = plt.legend(handles=methods, loc='lower right')\nax = plt.gca().add_artist(legend1)\n# plot vertical line and label for CV methods\nl1 = plt.axvline(x=comps_cv[0], color='blue', label=label_cv[0], linewidth=3)\nl2 = plt.axvline(x=comps_cv[1], color='red', label=label_cv[1], linewidth=3)\nmethods_cv = [l1,l2]\nlegend2 = plt.legend(handles=methods_cv, loc='center right')" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.16" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/docs/build/html/_downloads/3f32aa4be8ec94a294bd9807d4f01edc/plot_rank_estimation.py b/docs/build/html/_downloads/3f32aa4be8ec94a294bd9807d4f01edc/plot_rank_estimation.py new file mode 100644 index 00000000..0e6daec9 --- /dev/null +++ b/docs/build/html/_downloads/3f32aa4be8ec94a294bd9807d4f01edc/plot_rank_estimation.py @@ -0,0 +1,147 @@ +#!/usr/bin/env python +''' +========== +Plot rank estimation +========== + +Example script to estimate the rank of the given data array. +''' + +import os.path as op +import mne +import numpy as np +from mne.datasets import sample +from sklearn.decomposition import PCA +import matplotlib.pyplot as plt +from matplotlib import cm +from jumeg.jumeg_utils import rank_estimation +from jumeg.decompose.dimension_selection import mibs, bic, gap, aic, mdl, explVar, fa_rank_cv, pca_rank_cv + +# ---------------------------------------- +# filenames and path +# ---------------------------------------- +data_path = sample.data_path() +subjects_dir = op.join(data_path, 'subjects') +fname_raw = op.join(data_path, 'MEG/sample/sample_audvis_filt-0-40_raw.fif') +fname_event = op.join(data_path, 'MEG/sample/sample_audvis_filt-0-40_raw-eve.fif') + +# ---------------------------------------- +# read data and crop to speedup the process +# ---------------------------------------- +raw = mne.io.read_raw_fif(fname_raw) +events = mne.read_events(fname_event) +# add a bad channel +raw.info['bads'] += ['MEG 2443'] +# pick MEG channels +picks = mne.pick_types(raw.info, meg='mag', eeg=False, stim=False, eog=False, + exclude='bads') +# crop data to speed-up process +raw.crop(tmax=180) +data = raw.get_data()[picks, :] # data *= 1e12 will change the results ! + +# ========================================= +# Method 1: +# apply various dimension reduction tools +# to estimate the median of all +# ========================================= +rank_all, rank_median = rank_estimation(data) +print ('\nRank estimation using methods implemented in jumeg (including whitening)') +print('Ranks in order: MIBS, BIC, GAP, AIC, MDL, pct95, pct99: ', rank_all) +print('The median of the data is %f\n' % rank_median) + + + +# ========================================= +# Method 2: +# apply a single method for rank estimation +# using whitening provided by sklearn +# here we apply all methods separately +# ========================================= +# perform PCA +pca = PCA(svd_solver='auto', whiten=True) +pc = pca.fit_transform(data.T) +n_samples, n_features = pc.shape + +# rank estimation of a single method +rank_mibs = mibs(pca.explained_variance_, n_samples) # MIBS +rank_bic = bic(pca.explained_variance_, n_samples) # BIC +rank_gap = gap(pca.explained_variance_) # GAP +rank_aic = aic(pca.explained_variance_) # AIC +rank_mdl = mdl(pca.explained_variance_) # MDL +rank_expl95 = explVar(pca.explained_variance_, explainedVar=0.95) # expl. variance (95) +rank_expl99 = explVar(pca.explained_variance_, explainedVar=0.99) # expl. variance (99) +label_mibs = 'MIBS: n_comp = %d' % (rank_mibs) +label_bic = 'BIC: n_comp = %d' % (rank_bic) +label_gap = 'GAP: n_comp = %d' % (rank_gap) +label_aic = 'AIC: n_comp = %d' % (rank_aic) +label_mdl = 'MDL: n_comp = %d' % (rank_mdl) +label_expl95 = 'expl95: n_comp = %d' % (rank_expl95) +label_expl99 = 'expl99: n_comp = %d' % (rank_expl99) +print (label_mibs) +print (label_bic) +print (label_gap) +print (label_aic) +print (label_mdl) +print (label_expl95) +print (label_expl99) + + +# ------------------------------------------- +# Method 3 +# apply rank estimation utilizing cross-validation +# using PCA and FA scores +# Note, on normal data sets this will take a long time +# ------------------------------------------- +# define a list of components to test +# here we use all components from above and add a few more for testing +ncomp_list = np.unique(np.concatenate([rank_all[rank_all > 0], [40, 50]])) +ncomp_list.sort() +cv = 5 # depends on data length +print ('>>> Please be patient, this might take a while ....') +print ('') +# PCA: test a list of numbers in a cross-validation scenario +rank_cv_pca = pca_rank_cv(data, ncomp_list, cv=cv, whiten=True) + +# FA: test a list of components in a cross-validation scenario +rank_cv_fa = fa_rank_cv(pc.T, ncomp_list, cv=cv) + +label_cv_pca = 'PCA (CV=%d): %d' % (cv, rank_cv_pca) +label_cv_fa = 'FA (CV=%d): %d' % (cv, rank_cv_fa) + + +# ---------------------- +# plot results (Scree plot) +# ---------------------- +labels = np.array([label_aic, label_bic, label_gap, label_mdl, label_mibs, label_expl95, label_expl99]) +comps = np.array([rank_aic, rank_bic, rank_gap, rank_mdl, rank_mibs, rank_expl95, rank_expl99]) +# sorting by increasing number of components +ixsort = comps.argsort() +comps = comps[ixsort] +labels = labels[ixsort] + +# components estimated using CV +label_cv = [label_cv_pca, label_cv_fa] +comps_cv = [rank_cv_pca, rank_cv_fa] + +# plot figure +cmap = cm.get_cmap('Dark2') # 8 colors +colors = cmap.colors[::-1] +xaxis = np.arange(n_features)+1 +fig = plt.figure(figsize=(10, 6)) +plt.plot(xaxis, np.cumsum(pca.explained_variance_ratio_ * 100), marker='o', color='black') +plt.title('Scree plot') +plt.xlabel('# components') +plt.ylabel('explained variance / %') +# plot vertical line and label for each method +methods = [] +for i in range(len(comps)): + if (comps[i] > 0): + hl = plt.axvline(x=comps[i], color=colors[i], label=labels[i], linestyle='--') + methods.append(hl) +legend1 = plt.legend(handles=methods, loc='lower right') +ax = plt.gca().add_artist(legend1) +# plot vertical line and label for CV methods +l1 = plt.axvline(x=comps_cv[0], color='blue', label=label_cv[0], linewidth=3) +l2 = plt.axvline(x=comps_cv[1], color='red', label=label_cv[1], linewidth=3) +methods_cv = [l1,l2] +legend2 = plt.legend(handles=methods_cv, loc='center right') diff --git a/docs/build/html/_downloads/413f5b80f5a0c93ea2f98cd372226a70/plot_brain_connectome.ipynb b/docs/build/html/_downloads/413f5b80f5a0c93ea2f98cd372226a70/plot_brain_connectome.ipynb new file mode 100644 index 00000000..e731e2d7 --- /dev/null +++ b/docs/build/html/_downloads/413f5b80f5a0c93ea2f98cd372226a70/plot_brain_connectome.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Plot brain connectome\n\nPlot connectivity on a glass brain using 'plot_connectome' function from\nNilearn (https://nilearn.github.io/).\n\nAuthor: Praveen Sripad \n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import os.path as op\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport mne\nfrom mne.datasets import sample\n\nfrom nilearn import plotting\n\nfrom jumeg.connectivity import generate_random_connectivity_matrix\n\ndata_path = sample.data_path()\nsubjects_dir = op.join(data_path, 'subjects')\nsubject = 'fsaverage'\n\naparc = mne.read_labels_from_annot(subject, subjects_dir=subjects_dir,\n parc='aparc')\n\n# nodes in one hemisphere can be plotted as well\naparc_lh = [lab for lab in aparc if lab.hemi == 'lh']\n\ncoords = []\n\n# plot 10 nodes from left hemisphere only for better viz\nfor lab in aparc_lh[:10]:\n if lab.name == 'unknown-lh':\n continue\n # get the center of mass\n com = lab.center_of_mass('fsaverage')\n # obtain mni coordinated to the vertex from left hemi\n coords_ = mne.vertex_to_mni(com, hemis=0, subject=subject,\n subjects_dir=subjects_dir)\n coords.append(coords_)\n\nn_nodes = np.array(coords).shape[0]\n\n# make a random connectivity matrix\ncon = generate_random_connectivity_matrix(size=(n_nodes, n_nodes),\n symmetric=True)\n\n# plot the connectome on a glass brain background\nplotting.plot_connectome(con, coords)\nplt.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.16" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/docs/build/html/_downloads/456be38d745b17e2a5ea39eaa0fd0eb1/plot_generic_grouped_connectivity_circle.py b/docs/build/html/_downloads/456be38d745b17e2a5ea39eaa0fd0eb1/plot_generic_grouped_connectivity_circle.py new file mode 100644 index 00000000..8d4e6dc1 --- /dev/null +++ b/docs/build/html/_downloads/456be38d745b17e2a5ea39eaa0fd0eb1/plot_generic_grouped_connectivity_circle.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 + +""" +============= +Generic Grouped Connectivity Circle +============= + +Script exposing circle plots with outer ring. + +Author: Praveen Sripad + +""" +import os.path as op +from jumeg.connectivity import (plot_generic_grouped_circle, + plot_fica_grouped_circle, + generate_random_connectivity_matrix) +from jumeg import get_jumeg_path + +# load the yaml grouping of Freesurfer labels +yaml_fname = op.join(get_jumeg_path(), 'data/rsn_desikan_aparc_cortex_grouping.yaml') + +# make a random matrix +con = generate_random_connectivity_matrix(size=(34, 34), symmetric=True) + +# load the label names in the original order +# this should be same order as the connectivity matrix +labels_fname = op.join(get_jumeg_path(), 'data/fica_names.txt') +with open(labels_fname, 'r') as f: + orig_labels = [line.rstrip('\n') for line in f] + +# plot the connectivity circle grouped +plot_generic_grouped_circle(yaml_fname, con, orig_labels, + node_order_size=34, + out_fname='fig_fica_circle.png', + show=False, n_lines=20, + title='Groups') + +# plot the connectivity circle with outer group labels ring +plot_fica_grouped_circle(yaml_fname, con, orig_labels, + node_order_size=34, + out_fname='fig_fica_circle_with_names.png', + show=False, n_lines=20, + title='Groups + Labels') diff --git a/docs/build/html/_downloads/486d9a98fcbfe134cf419c5b5064fe6b/do_MLICA.ipynb b/docs/build/html/_downloads/486d9a98fcbfe134cf419c5b5064fe6b/do_MLICA.ipynb new file mode 100644 index 00000000..535c23d4 --- /dev/null +++ b/docs/build/html/_downloads/486d9a98fcbfe134cf419c5b5064fe6b/do_MLICA.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Do MLICA\n\nCompute ICA object based on filtered and downsampled data.\nIdentify ECG and EOG artifacts using the pre-trained DCNN model\nand compare results using correlation & ctps analysis.\n\nApply ICA object to filtered and unfiltered data.\n\nAhmad Hasasneh, Nikolas Kampel, Praveen Sripad, N. Jon Shah, and Juergen Dammers\n\"Deep Learning Approach for Automatic Classification of Ocular and Cardiac\nArtifacts in MEG Data\"\nJournal of Engineering, vol. 2018, Article ID 1350692,10 pages, 2018.\nhttps://doi.org/10.1155/2018/1350692\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import os.path as op\nimport matplotlib.pylab as plt\nplt.ion()\nimport numpy as np\nimport mne\nfrom jumeg.decompose.ica_replace_mean_std import ICA, ica_update_mean_std\nfrom keras.models import load_model\nfrom jumeg.jumeg_noise_reducer import noise_reducer\nfrom jumeg.jumeg_preprocessing import get_ics_cardiac, get_ics_ocular\nfrom jumeg.jumeg_plot import plot_performance_artifact_rejection\nfrom jumeg.jumeg_utils import get_jumeg_path\n\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n# settings\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\nmodel_thresh = 0.8 # >0.5 ..0.9\nn_components = 40 # 30 .. 60\nnjobs = 'cuda'\nsfreq_new = 250 # downsampling to 250 Hz\nflow_raw, flow_high = 2, 45 # high pass filter prevents from false positives\nflow_ecg, fhigh_ecg = 8, 20\nflow_eog, fhigh_eog = 1, 20\necg_thresh, eog_thresh = 0.3, 0.3\necg_ch = 'ECG 001'\neog1_ch = 'EOG 001'\neog2_ch = 'EOG 002'\nreject = {'mag': 5e-12}\n\n# number time samples is fixed to 15000\nnsamples_chop = 15000\nix_t1 = 0 # time index: here we use the first chop\nix_t2 = ix_t1 + nsamples_chop\n\n# ----------------------------------------------\n# load DCNN model for artifact rejection\n# the details of the model is provided in:\n# x_validation_shuffle_v4_split_23.txt\n# model was trained on 4D data from Juelich\n# ----------------------------------------------\nmodel_path = op.join(get_jumeg_path(), 'data')\nmodel_name = op.join(model_path, \"dcnn_model.hdf5\")\nmodel = load_model(model_name)\n\n# ----------------------------------------------\n# read example data file\n# ----------------------------------------------\npath_data = '/data/megraid22/Common/DeepLearning/cau_data_validation/'\nraw_fname = op.join(path_data, '109925_CAU01A_100715_0842_2_c,rfDC,t1,n_bcc,nr-raw.fif')\nraw = mne.io.Raw(raw_fname, preload=True)\npicks = mne.pick_types(raw.info, meg=True, eeg=False, eog=False,\n stim=False, exclude='bads')\n\n\n# ----------------------------------------------\n# filtering and down sampling\n# ----------------------------------------------\n# filter prior to ICA\nraw_filtered = raw.copy().filter(flow_raw, flow_high, picks=picks, filter_length='auto',\n l_trans_bandwidth='auto', h_trans_bandwidth='auto',\n n_jobs=njobs, method='fir', phase='zero',\n fir_window='hamming')\n# downsample data\nraw_ds = raw_filtered.copy().resample(sfreq_new, npad='auto', window='boxcar', stim_picks=None,\n n_jobs=njobs, events=None)\n\n# ----------------------------------------------\n# crop data to get first chop\n# ----------------------------------------------\n# get times to crop\ndt = raw_ds.times[1] # time period between two time samples\ntmin = ix_t1 * dt\ntmax = ix_t2 * dt - dt # subtract one sample\n# crop all raw objects\nraw_chop = raw.copy().crop(tmin=tmin, tmax=tmax) # raw\nraw_filtered_chop = raw_filtered.copy().crop(tmin=tmin, tmax=tmax) # raw filtered\nraw_ds_chop = raw_ds.copy().crop(tmin=tmin, tmax=tmax) # raw filtered downsampled\nraw_filtered.close()\n\n# ----------------------------------------------\n# apply ICA\n# ----------------------------------------------\nica = ICA(method='fastica', n_components=n_components, random_state=42,\n max_pca_components=None, max_iter=5000, verbose=None)\n# do the ICA decomposition on downsampled raw\nica.fit(raw_ds_chop, picks=picks, reject=reject, verbose=None)\nsources = ica.get_sources(raw_ds_chop)._data # get sources\nsources = np.reshape(sources, (n_components,nsamples_chop, 1)) # reshape sources\n\n# ----------------------------------------------\n# model prediction\n# identification of artifact components\n# ----------------------------------------------\n# compute base functions\nmm = np.float32(np.dot(ica.mixing_matrix_[:, :ica.n_components_].T,\n ica.pca_components_[:ica.n_components_, :ica.max_pca_components]))\n# get model prediction\nmodel_scores = model.predict([mm, sources], verbose=1)\n# get ICs\nbads_MLICA = list(np.where(model_scores[:,0] > model_thresh)[0])\n\n# ----------------------------------------------\n# order ICs for visualization\n# ----------------------------------------------\nvar_order = sources.std(axis=1).flatten().argsort()[::-1]\ngood_ics = np.setdiff1d(var_order, bads_MLICA)\nic_order = list(np.concatenate([bads_MLICA, good_ics]))\n# store components in ica object\nica.exclude = list(bads_MLICA)\n\n\n# ----------------------------------------------\n# compare MLICA results with correlation and ctps\n# ----------------------------------------------\nprint('Identifying components..')\n# get ECG/EOG related components using JuMEG\nic_ecg = get_ics_cardiac(raw_filtered_chop, ica, flow=flow_ecg, fhigh=fhigh_ecg,\n thresh=ecg_thresh, tmin=-0.5, tmax=0.5,\n name_ecg=ecg_ch, use_CTPS=True)[0] # returns both ICs and scores (take only ICs)\nic_eog = get_ics_ocular(raw_filtered_chop, ica, flow=flow_eog, fhigh=fhigh_eog,\n thresh=eog_thresh, name_eog_hor=eog1_ch,\n name_eog_ver=eog2_ch, score_func='pearsonr')\nbads_corr_ctps = list(ic_ecg) + list(ic_eog)\nbads_corr_ctps = list(set(bads_corr_ctps)) # remove potential duplicates\nbads_corr_ctps.sort()\nprint('Bad components from MLICA:', bads_MLICA)\nprint('Bad components from correlation & ctps:', bads_corr_ctps)\n\n\n# ----------------------------------------------\n# plot results\n# ----------------------------------------------\n# plot sources\nfig = ica.plot_sources(raw_filtered_chop, picks=ic_order, title='MLICA', show=False)\n#fig.savefig('MLICA_ica-sources.png')\n\n# plot artifact rejection performance\nfnout_fig = '109925_CAU01A_100715_0842_2_c,rfDC,0-45hz,ar-perf'\nica_filtered_chop = ica_update_mean_std(raw_filtered_chop, ica, picks=picks, reject=reject)\nraw_filtered_chop_clean = ica_filtered_chop.apply(raw_filtered_chop, exclude=ica.exclude,\n n_pca_components=None)\nica_unfiltered_chop = ica_update_mean_std(raw_chop, ica, picks=picks, reject=reject)\nraw_unfiltered_chop_clean = ica_unfiltered_chop.apply(raw_chop, exclude=ica.exclude, n_pca_components=None)\nplot_performance_artifact_rejection(raw.copy().crop(tmin=tmin, tmax=tmax), ica_unfiltered_chop, fnout_fig,\n meg_clean=raw_unfiltered_chop_clean,\n show=True, verbose=False,\n name_ecg=ecg_ch,\n name_eog=eog2_ch)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.16" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/docs/build/html/_downloads/4af84a0c2a4c12d3401d304b19369b0e/plot_compute_epochs_surrogates.py b/docs/build/html/_downloads/4af84a0c2a4c12d3401d304b19369b0e/plot_compute_epochs_surrogates.py new file mode 100644 index 00000000..ab982f6c --- /dev/null +++ b/docs/build/html/_downloads/4af84a0c2a4c12d3401d304b19369b0e/plot_compute_epochs_surrogates.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python + +''' +============= +Surrogate Connectivity Generation +============= + +Example to show surrogate generation on Epochs using the jumeg Surrogates +module. +''' + +import os.path as op +import numpy as np +import matplotlib.pyplot as pl +from mne.datasets import sample +import mne + +from jumeg.jumeg_surrogates import Surrogates, check_power_spectrum + +data_path = sample.data_path() +subjects_dir = op.join(data_path, 'subjects') + +fname_raw = op.join(data_path, 'MEG/sample/sample_audvis_filt-0-40_raw.fif') +fname_event = op.join(data_path, 'MEG/sample/sample_audvis_filt-0-40_raw-eve.fif') + +epochs_testing = False + +raw = mne.io.read_raw_fif(fname_raw) +events = mne.read_events(fname_event) + +# add a bad channel +raw.info['bads'] += ['MEG 2443'] + +# pick MEG channels +picks = mne.pick_types(raw.info, meg='mag', eeg=False, stim=False, eog=False, + exclude='bads') + +# Define epochs for left-auditory condition +event_id, tmin, tmax = 1, -0.2, 0.5 +epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks, + baseline=(None, 0), reject=dict(mag=4e-12)) + +# initialize the Surrogates object +surr_epochs = Surrogates(epochs) + +n_surr = 10 # number of surrogates +mode = 'randomize_phase' +mysurr = surr_epochs.compute_surrogates(n_surr=n_surr, + mode=mode, return_generator=False) + +# get one epochs for plotting +# for epochs, a generator is always returned +first_surr_epoch = next(mysurr) + +# visualize surrogates +fig, (ax1, ax2) = pl.subplots(2, 1) +epochs.average().plot(axes=ax1, show=False, titles='Evoked') +first_surr_epoch.average().plot(axes=ax2, show=False, titles='Surrogate Evoked') +pl.show() diff --git a/docs/build/html/_downloads/4bc28a484de6c83cdb79e55e781165d2/plot_perform_mft_volume.ipynb b/docs/build/html/_downloads/4bc28a484de6c83cdb79e55e781165d2/plot_perform_mft_volume.ipynb new file mode 100644 index 00000000..3881bd9a --- /dev/null +++ b/docs/build/html/_downloads/4bc28a484de6c83cdb79e55e781165d2/plot_perform_mft_volume.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Jumeg MFT volume.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import os.path as op\nimport numpy as np\nimport mne\nfrom mne.datasets import sample\nfrom jumeg.mft import (apply_mft, jumeg_mft_plot)\n\ndata_path = sample.data_path()\nsubject = 'sample'\nsubjects_dir = op.join(data_path, 'subjects')\nfwdname = op.join(data_path, 'MEG/sample/sample_audvis-meg-vol-7-fwd.fif')\nevoname = op.join(data_path, 'MEG/sample/sample_audvis-ave.fif')\nevocondition = 'Left Auditory'\nrawname = op.join(data_path, 'MEG/sample/sample_audvis_10s-raw.fif')\nt1_fname = op.join(subjects_dir, 'sample/mri/T1.mgz')\n\n# Set up pick list: MEG - bad channels\nwant_meg = 'mag'\nwant_ref = False\nwant_eeg = False\nwant_stim = False\nexclude = 'bads'\ninclude = []\n\nprint(\"########## MFT parameter:\")\nmftpar = {'prbfct': 'Gauss',\n 'prbcnt': np.array([[-1.039, 0.013, 0.062], [-0.039, 0.013, 0.062]]),\n 'prbhw': np.array([[0.040, 0.040, 0.040], [0.040, 0.040, 0.040]])}\n# mftpar = { 'prbfct': 'uniform',\n# 'prbcnt': None,\n# 'prbhw': None}\nmftpar.update({'iter': 4, 'currexp': 1.0})\nmftpar.update({'regtype': 'PzetaE', 'zetareg': 1.00})\n# mftpar.update({ 'regtype':'classic', 'zetareg':1.0})\nmftpar.update({'solver': 'lu', 'svrelcut': 5.e-4})\n\nprint(\"mftpar['prbcnt' ] = \", mftpar['prbcnt'])\nprint(\"mftpar['prbhw' ] = \", mftpar['prbhw'])\nprint(\"mftpar['iter' ] = \", mftpar['iter'])\nprint(\"mftpar['regtype' ] = \", mftpar['regtype'])\nprint(\"mftpar['zetareg' ] = \", mftpar['zetareg'])\nprint(\"mftpar['solver' ] = \", mftpar['solver'])\nprint(\"mftpar['svrelcut'] = \", mftpar['svrelcut'])\ncdmcut = 0.10\nprint(\"cdmcut = \", cdmcut)\n\nprint(\"##########################\")\nprint(\"##### Read fwd-soln:\")\nprint(\"##########################\")\nfwd = mne.read_forward_solution(fwdname, verbose=True)\n\n# Select magnetometer channels:\nfwdmag = mne.io.pick.pick_types_forward(fwd, meg=want_meg, ref_meg=False,\n eeg=False, exclude=exclude)\n\nprint(\" \")\nprint(\"########## Some geo-numbers:\")\nlhinds = np.where(fwdmag['source_rr'][:, 0] <= 0.)\nrhinds = np.where(fwdmag['source_rr'][:, 0] > 0.)\nypinds = np.where(fwdmag['source_rr'][:, 1] > 0.)\nyninds = np.where(fwdmag['source_rr'][:, 1] <= 0.)\nlhfinds = np.array(np.setdiff1d(lhinds[0], ypinds[0]))\nlhbinds = np.array(np.setdiff1d(lhinds[0], yninds[0]))\nrhfinds = np.array(np.setdiff1d(rhinds[0], ypinds[0]))\nrhbinds = np.array(np.setdiff1d(rhinds[0], yninds[0]))\nprint(\"> Discriminating lh/rh by sign of fwdmag['source_rr'][:,0]:\")\nprint(\"> lhinds[0].shape[0] = \", lhinds[0].shape[0], \" rhinds[0].shape[0] = \", rhinds[0].shape[0])\ninvmri_head_t = mne.transforms.invert_transform(fwdmag['info']['mri_head_t'])\nmrsrc = np.zeros(fwdmag['source_rr'].shape)\nmrsrc = mne.transforms.apply_trans(invmri_head_t['trans'], fwdmag['source_rr'], move=True)\nlhmrinds = np.where(mrsrc[:, 0] <= 0.)\nrhmrinds = np.where(mrsrc[:, 0] > 0.)\nprint(\"> Discriminating lh/rh by sign of fwdmag['source_rr'][:,0] in MR coords:\")\nprint(\"> lhmrinds[0].shape[0] = \", lhmrinds[0].shape[0], \" rhmrinds[0].shape[0] = \", rhmrinds[0].shape[0])\n\nprint(\"########## prepare to put labels into label-files:\")\nmylablist = []\n# mylab = mne.Label(lhinds[0],pos=fwdmag['source_rr'][lhinds[0],:],hemi='lh',name='test_lh', verbose=True)\n# mylablist.append(mylab)\n# mylab = mne.Label(rhinds[0],pos=fwdmag['source_rr'][rhinds[0],:],hemi='rh',name='test_rh', verbose=True)\n# mylablist.append(mylab)\n\n# mylab = mne.Label(lhfinds,pos=fwdmag['source_rr'][lhfinds,:],hemi='lhf',name='test_lhf', verbose=True)\n# mylablist.append(mylab)\n# mylab = mne.Label(lhbinds,pos=fwdmag['source_rr'][lhbinds,:],hemi='lhb',name='test_lhb', verbose=True)\n# mylablist.append(mylab)\n# mylab = mne.Label(rhfinds,pos=fwdmag['source_rr'][rhfinds,:],hemi='rhf',name='test_rhf', verbose=True)\n# mylablist.append(mylab)\n# mylab = mne.Label(rhbinds,pos=fwdmag['source_rr'][rhbinds,:],hemi='rhb',name='test_rhb', verbose=True)\n# mylablist.append(mylab)\n\nprint(\"##################################\")\nprint(\"##### Calling apply_mft(mylablist)\")\nprint(\"##################################\")\nfwdmag, qualmft, stc_mft = apply_mft(fwdname, evoname, evocondition=evocondition,\n subject=subject, meg=want_meg,\n calccdm='all', cdmcut=cdmcut, cdmlabels=mylablist,\n mftpar=mftpar, verbose='verbose')\n\nevo = mne.read_evokeds(evoname, condition=evocondition, baseline=(None, 0))\ntmin = -0.2\ntstep = 1. / evo.info['sfreq']\nstcdata = stc_mft.data\n\n# plotting routines\njumeg_mft_plot.plot_global_cdv_dist(stcdata)\n# print \">>>>> skipping jumeg_mft_plot.plot_visualize_mft_sources() (fails due to old PySurfer-version)\"\njumeg_mft_plot.plot_visualize_mft_sources(fwdmag, stcdata, tmin=tmin, tstep=tstep,\n subject=subject, subjects_dir=subjects_dir)\njumeg_mft_plot.plot_cdv_distribution(fwdmag, stcdata)\njumeg_mft_plot.plot_max_amplitude_data(fwdmag, stcdata, tmin=tmin, tstep=tstep,\n subject=subject)\njumeg_mft_plot.plot_max_cdv_data(stc_mft, lhmrinds, rhmrinds)\njumeg_mft_plot.plot_cdvsum_data(stc_mft, lhmrinds, rhmrinds)\njumeg_mft_plot.plot_quality_data(qualmft, stc_mft)\njumeg_mft_plot.plot_cdm_data(qualmft, stc_mft)\n\njumeg_mft_plot.plot_cdm_data(qualmft, stc_mft, cdmlabels=mylablist)\njumeg_mft_plot.plot_jlong_labeldata(qualmft, stc_mft, mylablist)\njumeg_mft_plot.plot_jtotal_labeldata(qualmft, stc_mft, mylablist)\n\njumeg_mft_plot.plot_cdm_data(qualmft, stc_mft)\njumeg_mft_plot.plot_jlong_data(qualmft, stc_mft)\n\nprint(\"Done.\")" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.16" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/docs/build/html/_downloads/503834aab09a1044220a0405b005cc77/plot_interpolate_bads.ipynb b/docs/build/html/_downloads/503834aab09a1044220a0405b005cc77/plot_interpolate_bads.ipynb new file mode 100644 index 00000000..0b4f0a43 --- /dev/null +++ b/docs/build/html/_downloads/503834aab09a1044220a0405b005cc77/plot_interpolate_bads.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Plot and interpolate bads\n\nUse suggest_bads to automatically identify bad MEG channels\nand use interpolate_bads based on the center of mass of the\nsensors for bad channel correction.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import os.path as op\n\nimport mne\nfrom mne.datasets import sample\nfrom jumeg import suggest_bads\nfrom jumeg import interpolate_bads\n\ndata_path = sample.data_path()\nsubjects_dir = op.join(data_path, 'subjects')\n\nraw_fname = op.join(data_path, 'MEG/sample/sample_audvis_raw.fif')\n\nraw = mne.io.Raw(raw_fname, preload=True)\nmybads, raw = suggest_bads(raw, show_raw=False, summary_plot=False)\n\n# origin = None causes the method to use the sensor center of mass as origin\ninterpolate_bads(raw, origin=None, reset_bads=True)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.16" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/docs/build/html/_downloads/5337f55c415255930b3228fc90912b2c/plot_suggest_bads.ipynb b/docs/build/html/_downloads/5337f55c415255930b3228fc90912b2c/plot_suggest_bads.ipynb new file mode 100644 index 00000000..53fd4960 --- /dev/null +++ b/docs/build/html/_downloads/5337f55c415255930b3228fc90912b2c/plot_suggest_bads.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Plot suggest bads.\n\nExample code to use the jumeg suggest bads functionality.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import os.path as op\nimport mne\nfrom mne.datasets import sample\nfrom jumeg import suggest_bads\n\n# provide the path of the filename:\ndata_path = sample.data_path()\nsubjects_dir = op.join(data_path, 'subjects')\nraw_fname = op.join(data_path, 'MEG/sample/sample_audvis_raw.fif')\n\nraw = mne.io.Raw(raw_fname, preload=True)\n\nmybads, raw = suggest_bads(raw, show_raw=False, summary_plot=False)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.16" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/docs/build/html/_downloads/553a405c1f3308a28580a48c1d55f5ef/plot_destriux_atlas_based_connectivity.py b/docs/build/html/_downloads/553a405c1f3308a28580a48c1d55f5ef/plot_destriux_atlas_based_connectivity.py new file mode 100644 index 00000000..aa17154d --- /dev/null +++ b/docs/build/html/_downloads/553a405c1f3308a28580a48c1d55f5ef/plot_destriux_atlas_based_connectivity.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python + +""" +============= +Plot Destriux Atlas +============= + +Read grouped aparc labels from yaml file. + +Plot grouped connectivity circle with these grouped labels +for the Destriux atlas. +""" + +import os.path as op +from jumeg import get_jumeg_path +from jumeg.connectivity import (plot_grouped_connectivity_circle, + generate_random_connectivity_matrix) +import yaml + +grouping_yaml_fname = op.join(get_jumeg_path(), 'data/destriux_aparc_cortex_based_grouping.yaml') +label_names_yaml_fname = op.join(get_jumeg_path(), 'data/destriux_label_names.yaml') + +with open(label_names_yaml_fname, 'r') as f: + label_names = yaml.safe_load(f)['label_names'] + +# make a random matrix with 148 nodes +con = generate_random_connectivity_matrix(size=(148, 148), symmetric=True) +con[con < 0.5] = 0. + +# plot grouped connnectivity +plot_grouped_connectivity_circle(grouping_yaml_fname, con, label_names, + labels_mode=None, colorbar_pos=(0.1, 0.1), + replacer_dict=None, + out_fname='fig_destriux_circle.png', + n_lines=50, colorbar=True) diff --git a/docs/build/html/_downloads/573b6255e48cf5654800cbce050573eb/plot_label_distances.py b/docs/build/html/_downloads/573b6255e48cf5654800cbce050573eb/plot_label_distances.py new file mode 100644 index 00000000..367abd6a --- /dev/null +++ b/docs/build/html/_downloads/573b6255e48cf5654800cbce050573eb/plot_label_distances.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python + +""" +========== +Plot label distances +========== + +Script to plot label distances on circle and connectome plots. +""" + +import os.path as op + +import mne +from mne.datasets import sample +from mne_connectivity import degree + +from jumeg import get_jumeg_path +from jumeg.connectivity import (get_label_distances, + plot_grouped_connectivity_circle) +import yaml + +from nilearn import plotting + +data_path = sample.data_path() +subjects_dir = op.join(data_path, 'subjects') +subject = 'sample' + +parc = 'aparc' + +yaml_cortex_fname = op.join(get_jumeg_path(), 'data/desikan_%s_cortex_based_grouping.yaml' % parc) + +labels_fname = op.join(get_jumeg_path(), 'data/desikan_label_names.yaml') +with open(labels_fname, 'r') as f: + label_names = yaml.safe_load(f)['label_names'] + +replacer_dict_fname = op.join(get_jumeg_path(), 'data/replacer_dictionaries.yaml') +with open(replacer_dict_fname, 'r') as f: + replacer_dict = yaml.safe_load(f)['replacer_dict_%s' % parc] + +# compute distances between center of masses (COMs) of the labels +# we also get the MNI coordinates of the COMs in millimetres +con, coords, _, _ = get_label_distances(subject, subjects_dir, parc=parc) + +# forget long range connections, plot short neighbouring connections +neighbor_range = 30. # millimetres +con[con > neighbor_range] = 0. + +cortex_colors = ['m', 'b', 'y', 'c', 'r', 'g', + 'g', 'r', 'c', 'y', 'b', 'm'] + +out_fname = 'fig_label_com_distances_circle_%0.1f_%s.png' % (neighbor_range, parc) +plot_grouped_connectivity_circle(yaml_cortex_fname, con, label_names, + replacer_dict=replacer_dict, + yaml_color_fname=None, labels_mode='replace', + cortex_colors=cortex_colors, + out_fname=out_fname, colorbar_pos=(0.1, 0.1), + n_lines=None, colorbar=True, + colormap='Reds') + +# compute the degree +degs = degree(con, threshold_prop=1) + +# show the label ROIs and short range connections using nilearn glass brain +fig = plotting.plot_connectome(con, coords, node_size=degs, + edge_threshold='99%', + node_color='cornflowerblue', + display_mode='ortho', + title='%s' % parc) + +fig.savefig('fig_%s_labels_distance_degrees.png' % parc) diff --git a/docs/build/html/_downloads/58d415520c63a81b42a71c16289c05a7/plot_surrogate_methods.ipynb b/docs/build/html/_downloads/58d415520c63a81b42a71c16289c05a7/plot_surrogate_methods.ipynb new file mode 100644 index 00000000..d927e5b2 --- /dev/null +++ b/docs/build/html/_downloads/58d415520c63a81b42a71c16289c05a7/plot_surrogate_methods.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Plot surrogate methods\n\nPlotting vrious methods used to generate surrogates.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\nimport mne\nfrom jumeg.jumeg_surrogates import Surrogates, check_power_spectrum\nimport matplotlib.pyplot as pl\n\nmysurr = Surrogates.SimpleTestData()\n\n# do shuffling\nshuffled = mysurr.shuffle_time_points(mysurr.original_data)\n\npl.figure('shuffled')\npl.title('shuffled')\npl.plot(mysurr.original_data[0])\npl.plot(shuffled[0], color='r')\n\n# do shifting\nshifted = mysurr.shift_data(mysurr.original_data)\n\npl.figure('shifted')\npl.title('Shifted')\npl.plot(mysurr.original_data[0])\npl.plot(shifted[0], color='r')\n\n# do phase randomization\nphase_random = mysurr.randomize_phase(mysurr.original_data)\n\npl.figure('phase_randomize')\npl.title('phase_randomize')\npl.plot(mysurr.original_data[0])\npl.plot(phase_random[0], color='r')\n\n# do phase randomize as in scot\nphase_random_scot = mysurr.randomize_phase_scot(mysurr.original_data)\n\npl.figure('phase_randomize_scot')\npl.title('phase_randomize_scot')\npl.plot(mysurr.original_data[0])\npl.plot(phase_random_scot[0], color='r')\n\ncheck_power_spectrum(mysurr.original_data, phase_random)\ncheck_power_spectrum(mysurr.original_data, phase_random_scot)\n\npl.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.16" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/docs/build/html/_downloads/5e3fdbce7816dcceeb2419f0cd45b3f6/plot_grouped_connectivity_circle.ipynb b/docs/build/html/_downloads/5e3fdbce7816dcceeb2419f0cd45b3f6/plot_grouped_connectivity_circle.ipynb new file mode 100644 index 00000000..45be082c --- /dev/null +++ b/docs/build/html/_downloads/5e3fdbce7816dcceeb2419f0cd45b3f6/plot_grouped_connectivity_circle.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Plot grouped connectivity circle.\n\nExample showing how to read grouped aparc labels from yaml file and plot\ngrouped connectivity circle with these labels.\n\nAuthor: Praveen Sripad \n Christian Kiefer \n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import os.path as op\nfrom jumeg import get_jumeg_path\nfrom jumeg.connectivity import (plot_grouped_connectivity_circle,\n generate_random_connectivity_matrix)\nimport yaml\n\nlabels_fname = get_jumeg_path() + '/data/desikan_label_names.yaml'\nyaml_cortex_fname = get_jumeg_path() + '/data/desikan_aparc_cortex_based_grouping.yaml'\nyaml_cluster_fname = get_jumeg_path() + '/data/desikan_aparc_cluster_based_grouping_example.yaml'\nreplacer_dict_fname = get_jumeg_path() + '/data/replacer_dictionaries.yaml'\n\nwith open(labels_fname, 'r') as f:\n label_names = yaml.safe_load(f)['label_names']\n\nwith open(replacer_dict_fname, 'r') as f:\n replacer_dict = yaml.safe_load(f)['replacer_dict_aparc']\n\n# make a random matrix with 68 nodes\ncon = generate_random_connectivity_matrix(size=(68, 68), symmetric=True)\n\n# plot simple connectivity circle with cortex based grouping and colors\nplot_grouped_connectivity_circle(yaml_cortex_fname, con, label_names,\n labels_mode='replace', replacer_dict=replacer_dict,\n out_fname='fig_grouped_con_circle_cortex.png',\n colorbar_pos=(0.1, 0.1), n_lines=10, colorbar=True,\n colormap='viridis')\n\n# plot connectivity circle with cluster-based grouping but same node colors as above\nplot_grouped_connectivity_circle(yaml_cluster_fname, con, label_names,\n labels_mode=None, replacer_dict=None,\n yaml_color_fname=yaml_cortex_fname,\n out_fname='fig_grouped_con_circle_cluster.png',\n colorbar_pos=(0.1, 0.1), n_lines=10, colorbar=True,\n colormap='viridis')" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.16" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/docs/build/html/_downloads/670b9583aa6b2fb6d7296d6dc4e9eaf5/plot_grouped_connectivity_circle.py b/docs/build/html/_downloads/670b9583aa6b2fb6d7296d6dc4e9eaf5/plot_grouped_connectivity_circle.py new file mode 100644 index 00000000..be83cb29 --- /dev/null +++ b/docs/build/html/_downloads/670b9583aa6b2fb6d7296d6dc4e9eaf5/plot_grouped_connectivity_circle.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python + +""" +============= +Plot grouped connectivity circle. +============= + +Example showing how to read grouped aparc labels from yaml file and plot +grouped connectivity circle with these labels. + +Author: Praveen Sripad + Christian Kiefer + +""" +import os.path as op +from jumeg import get_jumeg_path +from jumeg.connectivity import (plot_grouped_connectivity_circle, + generate_random_connectivity_matrix) +import yaml + +labels_fname = get_jumeg_path() + '/data/desikan_label_names.yaml' +yaml_cortex_fname = get_jumeg_path() + '/data/desikan_aparc_cortex_based_grouping.yaml' +yaml_cluster_fname = get_jumeg_path() + '/data/desikan_aparc_cluster_based_grouping_example.yaml' +replacer_dict_fname = get_jumeg_path() + '/data/replacer_dictionaries.yaml' + +with open(labels_fname, 'r') as f: + label_names = yaml.safe_load(f)['label_names'] + +with open(replacer_dict_fname, 'r') as f: + replacer_dict = yaml.safe_load(f)['replacer_dict_aparc'] + +# make a random matrix with 68 nodes +con = generate_random_connectivity_matrix(size=(68, 68), symmetric=True) + +# plot simple connectivity circle with cortex based grouping and colors +plot_grouped_connectivity_circle(yaml_cortex_fname, con, label_names, + labels_mode='replace', replacer_dict=replacer_dict, + out_fname='fig_grouped_con_circle_cortex.png', + colorbar_pos=(0.1, 0.1), n_lines=10, colorbar=True, + colormap='viridis') + +# plot connectivity circle with cluster-based grouping but same node colors as above +plot_grouped_connectivity_circle(yaml_cluster_fname, con, label_names, + labels_mode=None, replacer_dict=None, + yaml_color_fname=yaml_cortex_fname, + out_fname='fig_grouped_con_circle_cluster.png', + colorbar_pos=(0.1, 0.1), n_lines=10, colorbar=True, + colormap='viridis') diff --git a/docs/build/html/_downloads/6d79818512247aa7861067e4a0a58cce/plot_shuffle_time_slices.py b/docs/build/html/_downloads/6d79818512247aa7861067e4a0a58cce/plot_shuffle_time_slices.py new file mode 100644 index 00000000..600c0c90 --- /dev/null +++ b/docs/build/html/_downloads/6d79818512247aa7861067e4a0a58cce/plot_shuffle_time_slices.py @@ -0,0 +1,68 @@ +""" +==================================================== +Shuffle channels' data in the time domain and plot. +==================================================== +""" +# Author: Eberhard Eich +# Praveen Sripad +# +# License: BSD (3-clause) + +import os.path as op +import numpy as np + +import mne +from mne.datasets import sample + +from jumeg.jumeg_utils import (get_files_from_list, time_shuffle_slices, + channel_indices_from_list) + +data_path = sample.data_path() +raw_fname = op.join(data_path, 'MEG/sample/sample_audvis_raw.fif') + +# shuffle all MEG channels that begin with number 11 +shflchanlist = ['MEG 11..'] + +# shuffle the whole length of the data +tmin, tmax = 0., None + +# apply the shuffling +# time_shuffle_slices(raw_fname, shufflechans=shflchanlist, tmin=tmin, tmax=tmax) + +plot_things = True +if plot_things: + permname = op.join(op.dirname(raw_fname), + op.basename(raw_fname).split('-')[0]) + ',tperm-raw.fif' + + rawraw = mne.io.Raw(raw_fname,preload=True) + shflpick = channel_indices_from_list(rawraw.info['ch_names'][:], + shflchanlist) + procdperm = mne.io.Raw(permname, preload=True) + + figraw = rawraw.plot_psd(fmin=0., fmax=300., tmin=0., color=(1,0,0), picks=shflpick) + axisraw = figraw.gca() + axisraw.set_ylim([-300., -250.]) + # procdnr.plot_psd(fmin=0.,fmax=300., color=(0,0,1), picks=shflpick) + figshfl = procdperm.plot_psd(fmin=0., fmax=300., tmin=0., color=(1,0,0), picks=shflpick) + axisshfl = figshfl.gca() + axisshfl.set_ylim([-300., -250.]) + + megpick = mne.pick_types(rawraw.info, meg=True, ref_meg=False, eeg=False, eog=False, stim=False) + + figraw1 = rawraw.plot_psd(fmin=0., fmax=300., tmin=0., color=(0,0,1), picks=megpick) + axisraw1 = figraw1.gca() + axisraw1.set_ylim([-300., -250.]) + + figshfl1 = procdperm.plot_psd(fmin=0., fmax=300., tmin=0., color=(0,0,1), picks=megpick) + axisshfl1 = figshfl1.gca() + axisshfl1.set_ylim([-300., -250.]) + + megnochgpick = np.setdiff1d(megpick, shflpick) + + figraw2 = rawraw.plot_psd(fmin=0., fmax=300., tmin=0., color=(0,1,0), picks=megnochgpick) + axisraw2 = figraw2.gca() + axisraw2.set_ylim([-300., -250.]) + + figshfl2 = procdperm.plot_psd(fmin=0., fmax=300., tmin=0., color=(0,1,0), picks=megnochgpick) + axisshfl2 = figshfl2.gca() + axisshfl2.set_ylim([-300., -250.]) diff --git a/docs/build/html/_downloads/6e4ed2190089ce674edcedc0fbde1e65/plot_data_distribution.py b/docs/build/html/_downloads/6e4ed2190089ce674edcedc0fbde1e65/plot_data_distribution.py new file mode 100644 index 00000000..4702278f --- /dev/null +++ b/docs/build/html/_downloads/6e4ed2190089ce674edcedc0fbde1e65/plot_data_distribution.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python +''' +========== +Plot data distribution +========== + +Example script to plot a given data distribution compared with a standard +Gaussian distribution. +''' + +import os.path as op +import matplotlib.pyplot as plt +import mne +from mne.datasets import sample +from jumeg.jumeg_plot import plot_histo_fit_gaussian + +data_path = sample.data_path() +subjects_dir = op.join(data_path, 'subjects') + +fname_raw = op.join(data_path, 'MEG/sample/sample_audvis_filt-0-40_raw.fif') +fname_event = op.join(data_path, 'MEG/sample/sample_audvis_filt-0-40_raw-eve.fif') + +raw = mne.io.read_raw_fif(fname_raw) +events = mne.read_events(fname_event) + +# add a bad channel +raw.info['bads'] += ['MEG 2443'] + +# pick MEG channels +picks = mne.pick_types(raw.info, meg='mag', eeg=False, stim=False, eog=False, + exclude='bads') + +# Define epochs for left-auditory condition +event_id, tmin, tmax = 1, -0.2, 0.5 +epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks, + baseline=(None, 0), reject=dict(mag=4e-12)) + +data = epochs.get_data() + +fig = plot_histo_fit_gaussian(data, nbins=100, fnout=None, show=True) diff --git a/docs/build/html/_downloads/728b0f3a75d3e016e45cc56032c1333e/plot_standard_resting_network_on_aparc_annot_map.ipynb b/docs/build/html/_downloads/728b0f3a75d3e016e45cc56032c1333e/plot_standard_resting_network_on_aparc_annot_map.ipynb new file mode 100644 index 00000000..e2b93356 --- /dev/null +++ b/docs/build/html/_downloads/728b0f3a75d3e016e45cc56032c1333e/plot_standard_resting_network_on_aparc_annot_map.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Standard RSNs on the connectivity circle\n\nPlot the visualization of the standard resting state network on the\nconnectivity circle plot showing the Freesurfer aparc annotation map.\n\nThis provides a quick visualization of the primary connections of the standard\nresting state network.\n\nUses the standard RSNs provided by [1]\n[1] P. Garc\u00e9s, M. C. Mart\u00edn-Buro, and F. Maest\u00fa,\n\u201cQuantifying the Test-Retest Reliability of Magnetoencephalography\nResting-State Functional Connectivity,\u201d Brain Connect., vol. 6, no. 6,\npp. 448\u2013460, 2016.\n\nAuthor: Praveen Sripad \n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import os.path as op\nimport numpy as np\nimport mne\n\nfrom mne.datasets import sample\nfrom jumeg.jumeg_utils import get_jumeg_path\nfrom jumeg.connectivity import make_annot_from_csv\nfrom jumeg.connectivity import plot_grouped_connectivity_circle\n\ndata_path = sample.data_path()\nsubject = 'sample'\nsubjects_dir = op.join(data_path, 'subjects')\nparc_fname = 'standard_garces_2016'\ncsv_fname = op.join(get_jumeg_path(), 'data', 'standard_rsns.csv')\n\n# set make_annot to True to save the annotation to disk\nlabels, coords, foci = make_annot_from_csv(subject, subjects_dir, csv_fname,\n parc_fname=parc_fname,\n make_annot=False,\n return_label_coords=True)\n\naparc = mne.read_labels_from_annot('sample', subjects_dir=subjects_dir)\naparc_names = [apa.name for apa in aparc]\nlh_aparc = [mylab for mylab in aparc if mylab.hemi == 'lh']\nrh_aparc = [mylab for mylab in aparc if mylab.hemi == 'rh']\n\n# get the appropriate resting state labels\nrst_aparc = []\nfor i, rst_label in enumerate(labels):\n myfoci = foci[i] # get the vertex\n if rst_label.hemi == 'lh': # vertex hemi is stored in the rst_label\n for mylab in lh_aparc:\n if myfoci in mylab.vertices:\n print('Left: ', rst_label.name, myfoci, mylab, aparc.index(mylab))\n rst_aparc.append(mylab)\n elif rst_label.hemi == 'rh':\n for mylab in rh_aparc:\n if myfoci in mylab.vertices:\n print('Right: ', rst_label.name, myfoci, mylab, aparc.index(mylab))\n rst_aparc.append(mylab)\n else:\n print('ERROR: ', rst_label)\n\n# only 16 labels in aparc show up, there are no vertices in the left hemi for\n# Frontoinsular_Median cingulate-lh\nrst_indices = [aparc.index(rst) for rst in rst_aparc]\n\nnetworks = {'Visual': ['lateraloccipital-lh', 'lateraloccipital-rh'],\n 'Sensorimotor': ['supramarginal-lh', 'supramarginal-rh'],\n 'Auditory': ['inferiortemporal-lh', 'middletemporal-rh'],\n 'DMN': ['precuneus-lh', 'inferiorparietal-lh',\n 'inferiorparietal-rh', 'medialorbitofrontal-lh'],\n 'Left_FP': ['inferiorparietal-lh', 'superiortemporal-lh'],\n 'Right_FP': ['inferiorparietal-rh', 'superiortemporal-rh'],\n 'Frontoinsular': ['inferiortemporal-lh', 'inferiortemporal-rh']}\n\n# make a temporary connectivity matrix\nn_nodes = 68\ncon = np.zeros((n_nodes, n_nodes))\n\nrst_combindices = [[16, 31], [50, 14], [50, 15], [50, 28], [14, 15],\n [14, 28], [15, 28], [22, 23], [14, 60], [62, 63],\n [15, 61],\n [16, 17]]\n\n# assign different values to different networks manually\ncon[16, 31] = 0.4 # Auditory\ncon[50, 14] = con[50, 15] = con[50, 28] = con[14, 15] = con[14, 28] = con[15, 28] = 0.5 # DMN\ncon[22, 23] = 0.6 # Visual\ncon[14, 60] = 0.7 # Left FP\ncon[62, 63] = 0.8 # Sensorimotor\ncon[15, 61] = 0.9 # Right FP\ncon[16, 17] = 1 # Frontoinsular\n\ncon += con.T # since we only add the combinations\n\n# plot the connectivity circle showing standard RSNs\nfrom matplotlib.colors import ListedColormap\ncmap = ListedColormap(['m', 'k', 'b', 'y', 'r', 'c', 'g'])\nyaml_fname = get_jumeg_path() + '/data/desikan_aparc_cortex_based_grouping.yaml'\n\nplot_grouped_connectivity_circle(yaml_fname, con, aparc_names, n_lines=12,\n labels_mode=None, colormap=cmap, colorbar=True,\n replacer_dict=None, indices=None,\n out_fname='fig_rsn_circle_plot.png')" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.16" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/docs/build/html/_downloads/750a05b437aaa7a73d607c5794d70771/plot_inter_and_intra_lobe_causality.py b/docs/build/html/_downloads/750a05b437aaa7a73d607c5794d70771/plot_inter_and_intra_lobe_causality.py new file mode 100644 index 00000000..74e3a11e --- /dev/null +++ b/docs/build/html/_downloads/750a05b437aaa7a73d607c5794d70771/plot_inter_and_intra_lobe_causality.py @@ -0,0 +1,86 @@ +""" +============= +Group Causality Matrix +============= + +Group a causality matrix by lobes and plot the resulting +inter- and intra-lobe causality. + +Author: Christian Kiefer +""" + +import os +import os.path as op + +import numpy as np +import matplotlib.pyplot as plt +import mne + +from mne.datasets import sample + +print(__doc__) + +data_path = sample.data_path() + +from jumeg.connectivity.con_utils import group_con_matrix_by_lobe +from jumeg.connectivity.con_viz import plot_grouped_causality_circle +from jumeg.jumeg_utils import get_jumeg_path + +############################################################################### +# Load the grouping files +############################################################################### + +grouping_yaml_fname = op.join(get_jumeg_path(), 'data', + 'desikan_aparc_cortex_based_grouping_ck.yaml') +lobe_grouping_yaml_fname = op.join(get_jumeg_path(), 'data', + 'lobes_grouping.yaml') + +############################################################################### +# Load anatomical labels +############################################################################### + +subjects_dir = op.join(data_path, 'subjects') +os.environ['SUBJECTS_DIR'] = subjects_dir + +full_labels = mne.read_labels_from_annot(subject='fsaverage', parc='aparc', + hemi='both', subjects_dir=subjects_dir) + +full_label_names = [full_label.name for full_label in full_labels if full_label.name.find('unknown') == -1] + +############################################################################### +# create random causality matrix +############################################################################### + +# create causality matrix +np.random.seed(42) +cau = np.random.uniform(-0.99, 0.01, (len(full_label_names), len(full_label_names))) + +cau[cau < 0] = 0 +cau = cau / 0.01 # values between 0 and 1 + +cau_grp, grp_label_names = group_con_matrix_by_lobe(con=cau, label_names=full_label_names, + grouping_yaml_fname=grouping_yaml_fname) + +############################################################################### +# Compare original matrix with grouped matrix plot +############################################################################### + +fig = plot_grouped_causality_circle(cau, grouping_yaml_fname, full_label_names, + title='original causality matrix', n_lines=None, + labels_mode=None, replacer_dict=None, out_fname=None, + colormap='magma_r', colorbar=True, colorbar_pos=(-0.25, 0.05), + arrowstyle='->,head_length=0.7,head_width=0.4', + figsize=(9.1, 6), vmin=0., vmax=1.0, ignore_diagonal=True, + show=True) + +plt.close(fig) + +fig = plot_grouped_causality_circle(cau_grp, lobe_grouping_yaml_fname, grp_label_names, + title='test', n_lines=None, labels_mode=None, + replacer_dict=None, out_fname=None, colormap='magma_r', + colorbar=True, colorbar_pos=(-0.25, 0.05), + arrowstyle='->,head_length=0.7,head_width=0.4', + figsize=(9.1, 6), vmin=0., ignore_diagonal=False, + show=True) + +plt.close(fig) diff --git a/docs/build/html/_downloads/788bd55683970df0cd1b8c32916e1553/plot_causality_circle.py b/docs/build/html/_downloads/788bd55683970df0cd1b8c32916e1553/plot_causality_circle.py new file mode 100644 index 00000000..a76c2263 --- /dev/null +++ b/docs/build/html/_downloads/788bd55683970df0cd1b8c32916e1553/plot_causality_circle.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python3 + +""" +============= +Plot Causality Matrix +============= + +Example showing how to plot a causality matrix on a circle plot. +""" + +import numpy as np + +from jumeg import get_jumeg_path +from jumeg.connectivity import plot_grouped_causality_circle +import yaml + +# load the yaml grouping of Freesurfer labels +yaml_fname = get_jumeg_path() + '/data/desikan_aparc_cortex_based_grouping.yaml' +labels_fname = get_jumeg_path() + '/data/desikan_label_names.yaml' +replacer_dict_fname = get_jumeg_path() + '/data/replacer_dictionaries.yaml' + +with open(labels_fname, 'r') as f: + label_names = yaml.safe_load(f)['label_names'] + +with open(replacer_dict_fname, 'r') as f: + replacer_dict = yaml.safe_load(f)['replacer_dict_aparc'] + +# make a random causality matrix +n_nodes = 68 # currently needs to be always this number +caus = np.random.random((n_nodes, n_nodes)) +caus[np.diag_indices_from(caus)] = 0. +caus[caus < 0.7] = 0. + +plot_grouped_causality_circle(caus, yaml_fname, label_names, n_lines=10, + labels_mode='replace', replacer_dict=replacer_dict, + out_fname='fig_causality_circle.png', + colormap='Blues', colorbar=True, + figsize=(6, 6), show=False, + arrowstyle='->,head_length=1,head_width=1') diff --git a/docs/build/html/_downloads/797503bea9dbbf294fb097dc44d00896/plot_annot_standard_rsns.ipynb b/docs/build/html/_downloads/797503bea9dbbf294fb097dc44d00896/plot_annot_standard_rsns.ipynb new file mode 100644 index 00000000..5f0c96ed --- /dev/null +++ b/docs/build/html/_downloads/797503bea9dbbf294fb097dc44d00896/plot_annot_standard_rsns.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Visualise Standard RSNs\n\nGrow and visualize standard resting state ROIs from literature.\n\n1. Read ROIs of standard regions involved in resting state networks from literature.\n (the data is provided as a csv file with list of regions with seed MNI coordinates)\n2. Grow labels of 1cm radius (approx) in the surface source space.\n3. Make annotation and visualize the labels.\n\nUses RSNs provided by [1]\n[1] P. Garc\u00e9s, M. C. Mart\u00edn-Buro, and F. Maest\u00fa,\n\u201cQuantifying the Test-Retest Reliability of Magnetoencephalography\nResting-State Functional Connectivity,\u201d Brain Connect., vol. 6, no. 6, pp. 448\u2013460, 2016.\n\nAuthor: Praveen Sripad \n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import os.path as op\nimport numpy as np\nimport mne\n\nfrom mne.datasets import sample\nfrom jumeg.jumeg_utils import get_jumeg_path\nfrom jumeg.connectivity import make_annot_from_csv\n\nfrom nilearn import plotting\nfrom mne.viz import Brain\n\ndata_path = sample.data_path()\nsubject = 'sample'\nsubjects_dir = op.join(data_path, 'subjects')\nparc_fname = 'standard_garces_2016'\ncsv_fname = op.join(get_jumeg_path(), 'data', 'standard_rsns.csv')\n\n# set make_annot to True to save the annotation to disk\nlabels, coords, _ = make_annot_from_csv(subject, subjects_dir, csv_fname,\n parc_fname=parc_fname, make_annot=False,\n return_label_coords=True)\n\n# to plot mni coords on glass brain\nn_nodes = np.array(coords).shape[0]\n# make a random zero valued connectivity matrix\ncon = np.zeros((n_nodes, n_nodes))\n# plot the connectome on a glass brain background\nplotting.plot_connectome(con, coords)\nplotting.show()\n\n# plot the brain surface, foci and labels\nBrain = mne.viz.get_brain_class()\nbrain = Brain(subject, hemi='both', surf='white', subjects_dir=subjects_dir)\n\nfor mni_coord, mylabel in zip(coords, labels):\n brain.add_foci(mni_coord, coords_as_verts=False, hemi=mylabel.hemi,\n color='red', scale_factor=0.6)\n brain.add_label(mylabel, hemi=mylabel.hemi)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.16" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/docs/build/html/_downloads/7a6f0b867a520c2c354e932467eac373/plot_shuffle_time_slices.ipynb b/docs/build/html/_downloads/7a6f0b867a520c2c354e932467eac373/plot_shuffle_time_slices.ipynb new file mode 100644 index 00000000..8cab4bd5 --- /dev/null +++ b/docs/build/html/_downloads/7a6f0b867a520c2c354e932467eac373/plot_shuffle_time_slices.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Shuffle channels' data in the time domain and plot.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Author: Eberhard Eich\n# Praveen Sripad\n#\n# License: BSD (3-clause)\n\nimport os.path as op\nimport numpy as np\n\nimport mne\nfrom mne.datasets import sample\n\nfrom jumeg.jumeg_utils import (get_files_from_list, time_shuffle_slices,\n channel_indices_from_list)\n\ndata_path = sample.data_path()\nraw_fname = op.join(data_path, 'MEG/sample/sample_audvis_raw.fif')\n\n# shuffle all MEG channels that begin with number 11\nshflchanlist = ['MEG 11..']\n\n# shuffle the whole length of the data\ntmin, tmax = 0., None\n\n# apply the shuffling\n# time_shuffle_slices(raw_fname, shufflechans=shflchanlist, tmin=tmin, tmax=tmax)\n\nplot_things = True\nif plot_things:\n permname = op.join(op.dirname(raw_fname),\n op.basename(raw_fname).split('-')[0]) + ',tperm-raw.fif'\n\n rawraw = mne.io.Raw(raw_fname,preload=True)\n shflpick = channel_indices_from_list(rawraw.info['ch_names'][:],\n shflchanlist)\n procdperm = mne.io.Raw(permname, preload=True)\n\n figraw = rawraw.plot_psd(fmin=0., fmax=300., tmin=0., color=(1,0,0), picks=shflpick)\n axisraw = figraw.gca()\n axisraw.set_ylim([-300., -250.])\n # procdnr.plot_psd(fmin=0.,fmax=300., color=(0,0,1), picks=shflpick)\n figshfl = procdperm.plot_psd(fmin=0., fmax=300., tmin=0., color=(1,0,0), picks=shflpick)\n axisshfl = figshfl.gca()\n axisshfl.set_ylim([-300., -250.])\n\n megpick = mne.pick_types(rawraw.info, meg=True, ref_meg=False, eeg=False, eog=False, stim=False)\n\n figraw1 = rawraw.plot_psd(fmin=0., fmax=300., tmin=0., color=(0,0,1), picks=megpick)\n axisraw1 = figraw1.gca()\n axisraw1.set_ylim([-300., -250.])\n\n figshfl1 = procdperm.plot_psd(fmin=0., fmax=300., tmin=0., color=(0,0,1), picks=megpick)\n axisshfl1 = figshfl1.gca()\n axisshfl1.set_ylim([-300., -250.])\n\n megnochgpick = np.setdiff1d(megpick, shflpick)\n\n figraw2 = rawraw.plot_psd(fmin=0., fmax=300., tmin=0., color=(0,1,0), picks=megnochgpick)\n axisraw2 = figraw2.gca()\n axisraw2.set_ylim([-300., -250.])\n\n figshfl2 = procdperm.plot_psd(fmin=0., fmax=300., tmin=0., color=(0,1,0), picks=megnochgpick)\n axisshfl2 = figshfl2.gca()\n axisshfl2.set_ylim([-300., -250.])" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.16" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/docs/build/html/_downloads/85704cb3d64d407130b06aa8e28474b7/plot_communities.py b/docs/build/html/_downloads/85704cb3d64d407130b06aa8e28474b7/plot_communities.py new file mode 100644 index 00000000..814829f0 --- /dev/null +++ b/docs/build/html/_downloads/85704cb3d64d407130b06aa8e28474b7/plot_communities.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python + +""" +============= +Plot network communities +============= + +Plot Networkx Communities on a connectome plot. + +Author: Praveen Sripad +""" + +import os.path as op +import numpy as np +import matplotlib.pyplot as plt + +import mne +from mne.datasets import sample +from jumeg.connectivity.con_utils import make_communities +from jumeg.connectivity import generate_random_connectivity_matrix + +from nilearn import plotting + +data_path = sample.data_path() +subjects_dir = op.join(data_path, 'subjects') +subject = 'fsaverage' +aparc = mne.read_labels_from_annot(subject, subjects_dir=subjects_dir, + parc='aparc') + +# make a random connectivity matrix +con = generate_random_connectivity_matrix(size=(34, 34), symmetric=True) + +top_nodes_list, n_communities = make_communities(con) + +# FIXME better colouring +# cmaps_list = ['Pastel1', 'Pastel2', 'Paired', 'Accent', +# 'Dark2', 'Set1', 'Set2', 'Set3', +# 'tab10', 'tab20', 'tab20b', 'tab20c'] +# color_list = plt.cm.Pastel1(np.linspace(0, 1, len(top_nodes_list))) + +color_list = ['red', 'orange', 'green', 'purple', 'navy', 'blue'] +cmaps_list = ['Reds', 'Oranges', 'Greens', 'Purples', 'PuBu', 'Blues'] + +fig = plt.figure(facecolor='w', edgecolor='w') + +for top_nodes, col, cmap in zip(top_nodes_list, color_list, cmaps_list): + + coords = [] + community_ = [aparc[tp] for tp in top_nodes] + + for lab in community_: + if lab.name == 'unknown-lh': + continue + print(lab.name) + # get the center of mass + com = lab.center_of_mass('fsaverage') + if lab.name.endswith('lh'): + # obtain mni coordinated to the vertex from left hemi + coords_ = mne.vertex_to_mni(com, hemis=0, subject=subject, + subjects_dir=subjects_dir) + else: + coords_ = mne.vertex_to_mni(com, hemis=1, subject=subject, + subjects_dir=subjects_dir) + coords.append(coords_) + + n_nodes = np.array(coords).shape[0] + # make a dummy connectivity matrix + # FIXME use the existing con matrix with indices chosen instead + con_ = np.ones((n_nodes, n_nodes)) / 2. + con_[np.diag_indices(n_nodes)] = 0. + con_[np.triu_indices(n_nodes, k=1)] = 0. + con_ += con_.T + + # plot the connectome on a glass brain background + plotting.plot_connectome(con_, coords, node_color=col, edge_cmap=cmap, + figure=fig, edge_vmin=0., edge_vmax=1.) + +plt.show() +# plt.savefig('fig_communities.png') diff --git a/docs/build/html/_downloads/87e37bd16413e1937436ee7686f30260/plot_degree_circle.ipynb b/docs/build/html/_downloads/87e37bd16413e1937436ee7686f30260/plot_degree_circle.ipynb new file mode 100644 index 00000000..c61c6632 --- /dev/null +++ b/docs/build/html/_downloads/87e37bd16413e1937436ee7686f30260/plot_degree_circle.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Plot degree circle\n\nPlot degree values for a given set of nodes in a simple circle plot.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import os.path as op\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport mne\nfrom mne_connectivity import degree\nfrom jumeg import get_jumeg_path\nfrom jumeg.connectivity import plot_degree_circle\n\nimport bct\n\norig_labels_fname = op.join(get_jumeg_path(), 'data/desikan_label_names.yaml')\nyaml_fname = op.join(get_jumeg_path(), 'data/desikan_aparc_cortex_based_grouping.yaml')\ncon_fname = op.join(get_jumeg_path(), 'data/sample,aparc-con.npy')\n\ncon = np.load(con_fname)\ncon_ = con[0, :, :, 2] + con[0, :, :, 2].T\n\n# compute the degree\ndegrees = degree(con_, threshold_prop=0.2)\n\nfig, ax = plot_degree_circle(degrees, yaml_fname, orig_labels_fname)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.16" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/docs/build/html/_downloads/8ddba056db025e042233906e31e4ccbc/plot_noise_reducer.py b/docs/build/html/_downloads/8ddba056db025e042233906e31e4ccbc/plot_noise_reducer.py new file mode 100644 index 00000000..a91a6d70 --- /dev/null +++ b/docs/build/html/_downloads/8ddba056db025e042233906e31e4ccbc/plot_noise_reducer.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python +''' +==================== +Plot noise reducer +==================== + +Script to show the application of noise reducer on jusample data. +''' + +import os +import os.path as op +import numpy as np +import matplotlib.pyplot as plt +from jumeg.jumeg_noise_reducer import noise_reducer + +import mne + +plt.ion() + +# load the jumeg sample data (has to be BTI) +if os.environ.get('JUSAMPLE_MEG_PATH'): + data_dir = os.environ['JUSAMPLE_MEG_PATH'] +else: + print('Data unavailable, skipping.') + sys.exit() + +subject = '207184' +raw_fname = op.join(data_dir, 'recordings', subject, + 'sample_207184_rest_EC-raw.fif') + +raw = mne.io.Raw(raw_fname, preload=True) + +fig, (ax1, ax2, ax3, ax4, ax5) = plt.subplots(5, 1, sharex=True, sharey=True) + +picks = mne.pick_types(raw.info, meg='mag', exclude='bads') +raw.plot_psd(fmin=0., fmax=100., tmin=None, tmax=60., + n_fft=None, picks=picks, ax=ax1); +ax1.set_title('Original') + +# notch filter +raw_notch = raw.copy().notch_filter(np.arange(50, 251, 50), picks=picks, + filter_length='auto', + notch_widths=None, n_jobs=4, method='fir', + phase='zero-double', + fir_window='hamming', fir_design='firwin') +raw_notch.plot_psd(fmin=0., fmax=100., tmin=None, tmax=60., + n_fft=None, picks=picks, ax=ax2); +ax2.set_title('Notch filter 50Hz applied') + +# powerline removal using noise_reducer +raw_nr_notch = noise_reducer(raw_fname, raw=raw.copy(), detrending=False, + reflp=None, refhp=None, refnotch=[50., 100., 150.], + return_raw=True, verbose=False) +raw_nr_notch.plot_psd(fmin=0., fmax=100., tmin=None, tmax=60., + n_fft=None, picks=picks, ax=ax3); +ax3.set_title('Noise reducer notch filter 50Hz applied') + + +# remove high freq noise (>0.1Hz) from ref channels +raw_nr2 = noise_reducer(raw_fname, raw=raw_nr_notch, detrending=False, + reflp=None, refhp=0.1, refnotch=None, + return_raw=True, verbose=False) +raw_nr2.plot_psd(fmin=0., fmax=100., tmin=None, tmax=60., + n_fft=None, picks=picks, ax=ax4); +ax4.set_title('Noise reducer high pass filtered 0.1Hz') + +# remove low freq noise (<5Hz) from ref channels +raw_nr = noise_reducer(raw_fname, raw=raw_nr2, detrending=False, + reflp=5., refhp=None, refnotch=None, + return_raw=True, verbose=False) +raw_nr.plot_psd(fmin=0., fmax=100., tmin=None, tmax=60., + n_fft=None, picks=picks, ax=ax5); +ax5.set_title('Noise reducer low pass filtered 5Hz') + +plt.tight_layout() +plt.show() diff --git a/docs/build/html/_downloads/8df67dced1ecf400a9b21a7bf94207fe/plot_surrogate_methods.py b/docs/build/html/_downloads/8df67dced1ecf400a9b21a7bf94207fe/plot_surrogate_methods.py new file mode 100644 index 00000000..0956e7e0 --- /dev/null +++ b/docs/build/html/_downloads/8df67dced1ecf400a9b21a7bf94207fe/plot_surrogate_methods.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python +''' +========== +Plot surrogate methods +========== + +Plotting vrious methods used to generate surrogates. +''' + +import numpy as np +import mne +from jumeg.jumeg_surrogates import Surrogates, check_power_spectrum +import matplotlib.pyplot as pl + +mysurr = Surrogates.SimpleTestData() + +# do shuffling +shuffled = mysurr.shuffle_time_points(mysurr.original_data) + +pl.figure('shuffled') +pl.title('shuffled') +pl.plot(mysurr.original_data[0]) +pl.plot(shuffled[0], color='r') + +# do shifting +shifted = mysurr.shift_data(mysurr.original_data) + +pl.figure('shifted') +pl.title('Shifted') +pl.plot(mysurr.original_data[0]) +pl.plot(shifted[0], color='r') + +# do phase randomization +phase_random = mysurr.randomize_phase(mysurr.original_data) + +pl.figure('phase_randomize') +pl.title('phase_randomize') +pl.plot(mysurr.original_data[0]) +pl.plot(phase_random[0], color='r') + +# do phase randomize as in scot +phase_random_scot = mysurr.randomize_phase_scot(mysurr.original_data) + +pl.figure('phase_randomize_scot') +pl.title('phase_randomize_scot') +pl.plot(mysurr.original_data[0]) +pl.plot(phase_random_scot[0], color='r') + +check_power_spectrum(mysurr.original_data, phase_random) +check_power_spectrum(mysurr.original_data, phase_random_scot) + +pl.show() diff --git a/docs/build/html/_downloads/940e88cb8ee66ff2ea9bede4f6d0ce09/plot_suggest_bads.py b/docs/build/html/_downloads/940e88cb8ee66ff2ea9bede4f6d0ce09/plot_suggest_bads.py new file mode 100644 index 00000000..b9453f3e --- /dev/null +++ b/docs/build/html/_downloads/940e88cb8ee66ff2ea9bede4f6d0ce09/plot_suggest_bads.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +''' +==================== +Plot suggest bads. +==================== + +Example code to use the jumeg suggest bads functionality. +''' + +import os.path as op +import mne +from mne.datasets import sample +from jumeg import suggest_bads + +# provide the path of the filename: +data_path = sample.data_path() +subjects_dir = op.join(data_path, 'subjects') +raw_fname = op.join(data_path, 'MEG/sample/sample_audvis_raw.fif') + +raw = mne.io.Raw(raw_fname, preload=True) + +mybads, raw = suggest_bads(raw, show_raw=False, summary_plot=False) diff --git a/docs/build/html/_downloads/988f149f457b577ffba6a528d1a07829/plot_compare_jumeg_filters.py b/docs/build/html/_downloads/988f149f457b577ffba6a528d1a07829/plot_compare_jumeg_filters.py new file mode 100644 index 00000000..f7a450a7 --- /dev/null +++ b/docs/build/html/_downloads/988f149f457b577ffba6a528d1a07829/plot_compare_jumeg_filters.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python +# coding: utf-8 + +''' +==================== +Filtering in jumeg. +==================== + +Comparison of the various filters available for use in mne/jumeg. +''' + +import os.path as op + +import numpy as np +import matplotlib.pyplot as plt + +import mne +from mne.datasets import sample + +from jumeg.filter import jumeg_filter + +data_path = sample.data_path() +raw_fname = op.join(data_path, 'MEG/sample/sample_audvis_raw.fif') + +# load the raw data +raw = mne.io.Raw(raw_fname, preload=True) +picks = mne.pick_types(raw.info, meg='mag', exclude='bads') +print('Sampling frequency is %f' % raw.info['sfreq']) + +# plot the raw psd +fig = raw.plot_psd(tmin=0.0, tmax=160., fmin=0, fmax=np.inf, + picks=picks, ax=None, color='black', area_mode='std', + area_alpha=0.33, n_overlap=0, dB=True, average=True, + show=False, n_jobs=4, line_alpha=None, + spatial_colors=None, xscale='linear', verbose='ERROR'); +fig.suptitle('Original sprectrum') + +l_freq, h_freq = 1., 45. + +# apply FIR filter +fir_filt = raw.copy().filter(l_freq, h_freq, picks=picks, filter_length='auto', + l_trans_bandwidth='auto', h_trans_bandwidth='auto', + n_jobs=4, method='fir', iir_params=None, phase='zero', + fir_window='hamming', verbose='ERROR') + +# apply IIR filter +filter_type = 'butter' +filt_method = 'fft' +iir_params={'ftype': filter_type, 'order': 4} + +# apply IIR filter +iir_filt = raw.copy().filter(l_freq, h_freq, picks=picks, filter_length='auto', + l_trans_bandwidth='auto', h_trans_bandwidth='auto', + n_jobs=4, method='iir', iir_params=iir_params, phase='zero', + fir_window='hamming', verbose='ERROR') + +# apply the jumeg filter using mne +filt_ju_mne = jumeg_filter(filter_method='mne', filter_type='bp', fcut1=l_freq, fcut2=h_freq, + remove_dcoffset=True, sampling_frequency=raw.info['sfreq'], + filter_window='hamming', notch=np.array([50., 60.]), + notch_width=1.0, order=4, njobs=4, + mne_filter_method='fft',mne_filter_length='10s', + trans_bandwith=0.5) +ju_mne_filt = raw.copy() # make a copy +ju_mne_filt._data = filt_ju_mne.apply_filter(ju_mne_filt._data, picks) + +# apply the jumeg filter using bw +filt_ju_bw = jumeg_filter(filter_method='bw', filter_type='bp', fcut1=l_freq, fcut2=h_freq, + remove_dcoffset=True, sampling_frequency=raw.info['sfreq'], + filter_window='hamming', notch=np.array([50., 60.]), + notch_width=1.0, order=4, njobs=4, + mne_filter_method='fft',mne_filter_length='10s', + trans_bandwith=0.5) +filt_ju_bw.verbose = False +ju_bw_filt = raw.copy() # make a copy +filt_ju_bw.apply_filter(ju_bw_filt._data, picks) + +fig, (ax1, ax2) = plt.subplots(1, 2) + +# plot the jumeg MNE and jumeg Butterworth filtered raw psds +ju_mne_filt.plot_psd(tmin=0.0, tmax=160., fmin=0, fmax=70., n_fft=None, + picks=picks, ax=ax1, color='blue', area_mode='std', + area_alpha=0.33, n_overlap=0, dB=True, average=True, + show=False, n_jobs=4, line_alpha=None, + spatial_colors=None, xscale='linear', verbose=None); + +ju_bw_filt.plot_psd(tmin=0.0, tmax=160., fmin=0, fmax=70., n_fft=None, + picks=picks, ax=ax1, color='green', area_mode='std', + area_alpha=0.33, n_overlap=0, dB=True, average=True, + show=False, n_jobs=4, line_alpha=None, + spatial_colors=None, xscale='linear', verbose=None); + +ax1.set_xlim(0., 75.); +ax1.set_title('jumeg MNE (blue)/jumeg BW (green)'); + +# plot the MNE FIR and IIR filterered raw psds +fir_filt.plot_psd(tmin=0.0, tmax=160., fmin=0, fmax=70., n_fft=None, + picks=picks, ax=ax2, color='red', area_mode='std', + area_alpha=0.33, n_overlap=0, dB=True, average=True, + show=False, n_jobs=4, line_alpha=None, + spatial_colors=None, xscale='linear', verbose='ERROR'); + +iir_filt.plot_psd(tmin=0.0, tmax=160., fmin=0., fmax=70., n_fft=None, + picks=picks, ax=ax2, color='yellow', area_mode='std', + area_alpha=0.33, n_overlap=0, dB=True, average=True, + show=False, n_jobs=4, line_alpha=None, + spatial_colors=None, xscale='linear', verbose='ERROR'); +ax2.set_xlim(0., 75.); +ax2.set_title('MNE FIR (red)/ MNE IIR (yellow)'); + +fig.tight_layout() +plt.show() + +# Recommendation: Presently, it is best to use the MNE FIR filter for our +# filtering requirements. The jumeg filter module (which wraps around mne +# filter) may be used when the MNE band_pass_filter needs to be combined with +# the notch_filter. In cases where the notch frequencies are removed using the +# noise reducer, the mne FIR filter can be directly used. diff --git a/docs/build/html/_downloads/9c31ae393e1a24842273a773606e228d/plot_labelled_connectivity_circle.py b/docs/build/html/_downloads/9c31ae393e1a24842273a773606e228d/plot_labelled_connectivity_circle.py new file mode 100644 index 00000000..5d2ea765 --- /dev/null +++ b/docs/build/html/_downloads/9c31ae393e1a24842273a773606e228d/plot_labelled_connectivity_circle.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python3 + +""" +========== +Plot labelled connectivity circle +========== + +Example exposing the plot_labelled_group_connectivity_circle function. + +Author: Praveen Sripad + +""" +import os.path as op +from jumeg.connectivity import (plot_labelled_group_connectivity_circle, + generate_random_connectivity_matrix) +from jumeg import get_jumeg_path +import yaml + +# load the yaml grouping of Freesurfer labels +yaml_fname = op.join(get_jumeg_path(), 'data/rsn_desikan_aparc_cortex_grouping.yaml') +label_names_yaml_fname = op.join(get_jumeg_path(), 'data/desikan_label_names.yaml') + +with open(label_names_yaml_fname, 'r') as f: + label_names = yaml.safe_load(f)['label_names'] + +# make a random matrix with 68 nodes +con = generate_random_connectivity_matrix(size=(68, 68), symmetric=True) + +# plotting within a subplot +plot_labelled_group_connectivity_circle(yaml_fname, con, label_names, + out_fname='fig_rsn_circle.png', + show=False, n_lines=20, + fontsize_names=6, + title='test RSN circ labels') diff --git a/docs/build/html/_downloads/a324c3c446ad875d8a959af9e0191bd8/plot_generate_surrogate_connectivity.ipynb b/docs/build/html/_downloads/a324c3c446ad875d8a959af9e0191bd8/plot_generate_surrogate_connectivity.ipynb new file mode 100644 index 00000000..e97f6e5b --- /dev/null +++ b/docs/build/html/_downloads/a324c3c446ad875d8a959af9e0191bd8/plot_generate_surrogate_connectivity.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\nSurrogate computation\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import os.path as op\nimport numpy as np\nimport matplotlib.pyplot as pl\n\nimport mne\nfrom mne_connectivity import spectral_connectivity_epochs\nfrom mne.datasets import sample\nfrom mne.minimum_norm import read_inverse_operator, apply_inverse_epochs\n\nfrom jumeg.jumeg_surrogates import Surrogates\n\ndata_path = sample.data_path()\nsubjects_dir = op.join(data_path, 'subjects')\n\nfname_inv = op.join(data_path, 'MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif')\nfname_raw = op.join(data_path, 'MEG/sample/sample_audvis_filt-0-40_raw.fif')\nfname_event = op.join(data_path, 'MEG/sample/sample_audvis_filt-0-40_raw-eve.fif')\n\nraw = mne.io.read_raw_fif(fname_raw)\nevents = mne.read_events(fname_event)\ninverse_operator = read_inverse_operator(fname_inv)\n\n# add a bad channel\nraw.info['bads'] += ['MEG 2443']\n\n# pick MEG channels\npicks = mne.pick_types(raw.info, meg=True, eeg=False, stim=False, eog=False,\n exclude='bads')\n\n# Define epochs for left-auditory condition\nevent_id, tmin, tmax = 1, -0.2, 0.5\nepochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,\n baseline=(None, 0), reject=dict(mag=4e-12, grad=4000e-13))\n\nsnr = 1.0 # use lower SNR for single epochs\nlambda2 = 1.0 / snr ** 2\nmethod = \"dSPM\" # use dSPM method (could also be MNE or sLORETA)\nstcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, method,\n pick_ori=\"normal\", return_generator=False)\n\n# get labels for FreeSurfer 'aparc' cortical parcellation with 34 labels/hemi\nlabels = mne.read_labels_from_annot('sample', parc='aparc',\n subjects_dir=subjects_dir)\nlabel_colors = [label.color for label in labels]\n\n# average the source estimates within each label using sign-flips to reduce\n# signal cancellations, also here we can return a generator\nsrc = inverse_operator['src']\nlabel_ts = mne.extract_label_time_course(stcs, labels, src, mode='mean_flip',\n return_generator=False)\n\n# compute surrogates on the first STC extracted for 68 labels\nn_surr = 5\nfmin = 8.\nfmax = 13.\nsfreq = raw.info['sfreq'] # the sampling frequency\ncon_methods = ['coh', 'plv', 'wpli']\nn_rois = len(labels)\nfull_surr_con = np.zeros((3, n_rois, n_rois, 1, n_surr))\n\nreal_con = spectral_connectivity_epochs(\n label_ts, method=con_methods, mode='fourier', sfreq=sfreq,\n fmin=fmin, fmax=fmax, faverage=True, n_jobs=4)\n\n# get the data from SpectralConnectivity object and expand it\nreal_con = np.array([c.get_data(output='dense') for c in real_con])\n\n# loop through each of the label_ts from each epoch (i.e. 71)\n# for my_label_ts in label_ts:\nsurr_ts = Surrogates(np.array(label_ts))\nsurr_ts.original_data.shape\nsurr_label_ts = surr_ts.compute_surrogates(n_surr=n_surr,\n return_generator=True)\n\nfor ind_surr, surr in enumerate(surr_label_ts):\n con = spectral_connectivity_epochs(\n surr, method=con_methods, mode='fourier', sfreq=sfreq,\n fmin=fmin, fmax=fmax, faverage=True, n_jobs=4)\n\n con = np.array([c.get_data(output='dense') for c in con])\n\n # con now a list of arrays\n # con shape (method, n_signals, n_signals, n_freqs)\n full_surr_con[:, :, :, :, ind_surr] = con\n assert full_surr_con.flatten().max() <= 1., 'Maximum connectivity is above 1.'\n assert full_surr_con.flatten().min() >= 0., 'Minimum connectivity is 0.'\n\nsurr_ts.clear_cache()\n\n# visualize the surrogates\n# pl.plot(label_ts[0][0, :], 'b')\n# for lts in surr_label_ts:\n# pl.plot(lts[0, :], 'r')\n# pl.title('Extracted label time courses - real vs surrogates')\n# pl.show()\n\n\ndef sanity_check_con_matrix(con):\n '''\n Check if the connectivity matrix provided satisfies necessary conditions.\n This is done to ensure that the data remains clean and spurious values are\n easily detected.\n Expected a connectivity matrix of shape\n (n_methods x n_rois x n_rois x n_freqs x n_surr)\n '''\n n_methods, n_rois, n_rois, n_freqs, n_surr = con.shape\n assert np.any(con), 'Matrix is not all zeros.'\n assert not (con == con[0]).all(), 'All rows are equal - methods not different.'\n for surr in range(1, n_surr):\n assert not (con[:, :, :, :, surr] == con[:, :, :, :, 0]).all(), 'All surrogates are equal.'\n assert not np.triu(con[0, :, :, 0, surr]).any(), 'Matrices not symmetric.'\n\n\nsanity_check_con_matrix(full_surr_con)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.16" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/docs/build/html/_downloads/ad3e7613bd8ea8238efd5a0185ac58c8/do_compare_ica_methods.ipynb b/docs/build/html/_downloads/ad3e7613bd8ea8238efd5a0185ac58c8/do_compare_ica_methods.ipynb new file mode 100644 index 00000000..c8cd5503 --- /dev/null +++ b/docs/build/html/_downloads/ad3e7613bd8ea8238efd5a0185ac58c8/do_compare_ica_methods.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Compare ICA methods\n\nCompute the ica object on filtered data based on the mne and on the\njumeg method.\nCompare pca_mean_ and pre_whitener_ for:\nmne & filtered data, jumeg & filtered data, jumeg & unfiltered data\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import os.path as op\nimport mne\nfrom mne.preprocessing.ica import ICA as ICA_mne\nfrom jumeg.decompose.ica_replace_mean_std import ICA as ICA_jumeg\nfrom jumeg.decompose.ica_replace_mean_std import apply_ica_replace_mean_std\nfrom mne.datasets import sample\n\nflow = 1.\nfhigh = 45.\n\nreject = {'mag': 5e-12}\n\ndata_path = sample.data_path()\nsubjects_dir = op.join(data_path, 'subjects')\n\nfname_raw = op.join(data_path, 'MEG/sample/sample_audvis_raw.fif')\n\nraw = mne.io.Raw(fname_raw, preload=True)\nraw_filt = raw.copy().filter(flow, fhigh, method='fir', n_jobs=2, fir_design='firwin', phase='zero')\n\n# use 60s of data\nraw_filt.crop(0, 60)\nraw.crop(0, 60)\nraw_unfilt = raw.copy()\n\npicks = mne.pick_types(raw.info, meg=True, exclude='bads')\n\nica_mne = ICA_mne(method='fastica', n_components=60, random_state=42,\n max_pca_components=None, max_iter=5000, verbose=False)\n\n# fit ica object from mne to filtered data\nica_mne.fit(raw_filt, picks=picks, reject=reject, verbose=True)\n\n# save mean and standard deviation of filtered MEG channels for the standard mne routine\npca_mean_filt_mne = ica_mne.pca_mean_.copy()\npca_pre_whitener_filt_mne = ica_mne.pre_whitener_.copy() # this is the standard deviation of MEG channels\n\n\nica_jumeg = ICA_jumeg(method='fastica', n_components=60, random_state=42,\n max_pca_components=None, max_iter=5000, verbose=False)\n\n# fit ica object from jumeg to filtered data\nica_jumeg.fit(raw_filt, picks=picks, reject=reject, verbose=True)\n\n# save mean and standard deviation of filtered MEG channels for the standard mne routine\npca_mean_filt_jumeg = ica_jumeg.pca_mean_.copy()\npca_pre_whitener_filt_jumeg = ica_jumeg.pre_whitener_.copy() # this is the standard deviation of MEG channels\n\n# use the same arguments for apply_ica_replace_mean_std as when you are initializing the ICA\n# object and when you are fitting it to the data\n# the ica object is modified in place!!\n\n# apply ica object from jumeg to unfiltered data while replacing the mean and std\nraw_clean = apply_ica_replace_mean_std(raw_unfilt, ica_jumeg, picks=picks, reject=reject, exclude=ica_mne.exclude,\n n_pca_components=None)\n\n# save mean and standard deviation of unfiltered MEG channels\npca_mean_replaced_unfilt_jumeg = ica_jumeg.pca_mean_\npca_pre_whitener_replaced_unfilt_jumeg = ica_jumeg.pre_whitener_\n\n# compare methods for filtered and unfiltered data\nfor idx in range(0, len(pca_mean_filt_mne)):\n print('%10.6f\\t%10.6f\\t%10.6f' % (pca_mean_filt_mne[idx], pca_mean_filt_jumeg[idx],\n pca_mean_replaced_unfilt_jumeg[idx]))\n if idx >= 9:\n break\n\nfor idx in range(0, len(pca_pre_whitener_filt_mne)):\n print(pca_pre_whitener_filt_mne[idx], pca_pre_whitener_filt_jumeg[idx],\\\n pca_pre_whitener_replaced_unfilt_jumeg[idx])\n if idx >= 9:\n break" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.16" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/docs/build/html/_downloads/b48da817960af40bd9f0efb42867a8c0/plot_communities.ipynb b/docs/build/html/_downloads/b48da817960af40bd9f0efb42867a8c0/plot_communities.ipynb new file mode 100644 index 00000000..563e1eed --- /dev/null +++ b/docs/build/html/_downloads/b48da817960af40bd9f0efb42867a8c0/plot_communities.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Plot network communities\n\nPlot Networkx Communities on a connectome plot.\n\nAuthor: Praveen Sripad \n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import os.path as op\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport mne\nfrom mne.datasets import sample\nfrom jumeg.connectivity.con_utils import make_communities\nfrom jumeg.connectivity import generate_random_connectivity_matrix\n\nfrom nilearn import plotting\n\ndata_path = sample.data_path()\nsubjects_dir = op.join(data_path, 'subjects')\nsubject = 'fsaverage'\naparc = mne.read_labels_from_annot(subject, subjects_dir=subjects_dir,\n parc='aparc')\n\n# make a random connectivity matrix\ncon = generate_random_connectivity_matrix(size=(34, 34), symmetric=True)\n\ntop_nodes_list, n_communities = make_communities(con)\n\n# FIXME better colouring\n# cmaps_list = ['Pastel1', 'Pastel2', 'Paired', 'Accent',\n# 'Dark2', 'Set1', 'Set2', 'Set3',\n# 'tab10', 'tab20', 'tab20b', 'tab20c']\n# color_list = plt.cm.Pastel1(np.linspace(0, 1, len(top_nodes_list)))\n\ncolor_list = ['red', 'orange', 'green', 'purple', 'navy', 'blue']\ncmaps_list = ['Reds', 'Oranges', 'Greens', 'Purples', 'PuBu', 'Blues']\n\nfig = plt.figure(facecolor='w', edgecolor='w')\n\nfor top_nodes, col, cmap in zip(top_nodes_list, color_list, cmaps_list):\n\n coords = []\n community_ = [aparc[tp] for tp in top_nodes]\n\n for lab in community_:\n if lab.name == 'unknown-lh':\n continue\n print(lab.name)\n # get the center of mass\n com = lab.center_of_mass('fsaverage')\n if lab.name.endswith('lh'):\n # obtain mni coordinated to the vertex from left hemi\n coords_ = mne.vertex_to_mni(com, hemis=0, subject=subject,\n subjects_dir=subjects_dir)\n else:\n coords_ = mne.vertex_to_mni(com, hemis=1, subject=subject,\n subjects_dir=subjects_dir)\n coords.append(coords_)\n\n n_nodes = np.array(coords).shape[0]\n # make a dummy connectivity matrix\n # FIXME use the existing con matrix with indices chosen instead\n con_ = np.ones((n_nodes, n_nodes)) / 2.\n con_[np.diag_indices(n_nodes)] = 0.\n con_[np.triu_indices(n_nodes, k=1)] = 0.\n con_ += con_.T\n\n # plot the connectome on a glass brain background\n plotting.plot_connectome(con_, coords, node_color=col, edge_cmap=cmap,\n figure=fig, edge_vmin=0., edge_vmax=1.)\n\nplt.show()\n# plt.savefig('fig_communities.png')" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.16" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/docs/build/html/_downloads/b6bae98afd5c4bf61555baf269e4b06c/plot_test_transform_mni_to_ras.ipynb b/docs/build/html/_downloads/b6bae98afd5c4bf61555baf269e4b06c/plot_test_transform_mni_to_ras.ipynb new file mode 100644 index 00000000..fe6086b2 --- /dev/null +++ b/docs/build/html/_downloads/b6bae98afd5c4bf61555baf269e4b06c/plot_test_transform_mni_to_ras.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\nTo plot a vertex point, convert it to MNI coordinates and then reconvert it back to RAS to obtain the vertex number.\n\nIt works when 'fsaverage' subject is used, but does not when any other subjects are used.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import os\nimport os.path as op\nimport mne\nfrom mne.datasets import sample\nfrom surfer import utils\n\nprint(__doc__)\n\ndata_path = sample.data_path()\nfname_inv = op.join(data_path, 'MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif')\nfname_evoked = op.join(data_path, 'MEG/sample/sample_audvis-ave.fif')\nsubjects_dir = op.join(data_path, 'subjects')\nos.environ['SUBJECTS_DIR'] = subjects_dir\n\nstc_fname = op.join(data_path, 'MEG/sample/sample_audvis-meg')\nstc = mne.read_source_estimate(stc_fname)\n\nmorph = mne.compute_source_morph(stc, subject_from='sample',\n subject_to='fsaverage', spacing=5, subjects_dir=subjects_dir)\nnew_stc = morph.apply(stc)\n\nsubject = 'fsaverage'\n\n# Plot brain in 3D with PySurfer if available\nbrain = new_stc.plot(subject, hemi='lh',\n subjects_dir=subjects_dir, backend='pyvistaqt')\nbrain.show_view('lateral')\n\n# use peak getter to move vizualization to the time point of the peak\nvertno_max, time_idx = new_stc.get_peak(hemi='lh', time_as_index=True)\n\nbrain.set_time_point(time_idx)\n\n# draw marker at maximum peaking vertex\nbrain.add_foci(vertno_max, coords_as_verts=True, hemi='lh', color='blue',\n scale_factor=0.6, map_surface='white')\n\nmni_coords = mne.vertex_to_mni(vertno_max, hemis=0, subject=subject,\n subjects_dir=subjects_dir)\nprint('The MNI coords are ', mni_coords)\n\n# my_trans = mne.read_trans(?)\n# src_pts = apply_trans(trans, some_tgt_pts)\n\nutils.coord_to_label(subject, mni_coords, label='mycoord',\n hemi='lh', n_steps=25, map_surface=\"white\")\nbrain.add_label('mycoord-lh.label', color=\"darkseagreen\", alpha=.8)\n\n# if the new mni_coords are computed\nbrain.add_foci(mni_coords, coords_as_verts=False, hemi='lh',\n color='red', scale_factor=0.6)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.16" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/docs/build/html/_downloads/b6df76fdd66cdda91b0547c0303a05c0/plot_perform_mft_surface_list.py b/docs/build/html/_downloads/b6df76fdd66cdda91b0547c0303a05c0/plot_perform_mft_surface_list.py new file mode 100644 index 00000000..f91fc1a5 --- /dev/null +++ b/docs/build/html/_downloads/b6df76fdd66cdda91b0547c0303a05c0/plot_perform_mft_surface_list.py @@ -0,0 +1,137 @@ +""" +==================== +Jumeg MFT example. +==================== + +Perform MFT on a surface based forward solution. +""" + +import os.path as op +import numpy as np +import mne +from mne.datasets import sample +from jumeg.mft import (apply_mft, jumeg_mft_plot) + +data_path = sample.data_path() +subject = 'sample' +subjects_dir = op.join(data_path, 'subjects') +fwdname = op.join(data_path, 'MEG/sample/sample_audvis-meg-oct-6-fwd.fif') +lblname = 'aparc' +evoname = op.join(data_path, 'MEG/sample/sample_audvis-ave.fif') +evocondition = 'Left Auditory' +rawname = op.join(data_path, 'MEG/sample/sample_audvis_10s-raw.fif') +t1_fname = op.join(subjects_dir, 'sample/mri/T1.mgz') + +# Set up pick list: MEG - bad channels +want_meg = 'mag' +want_ref = False +want_eeg = False +want_stim = False +exclude = 'bads' +include = [] + +print("########## MFT parameters:") +mftpar = {'prbfct': 'Gauss', + 'prbcnt': np.array([[0.039, 0.013, 0.062], [-0.039, 0.013, 0.062]]), + 'prbhw': np.array([[0.040, 0.040, 0.040], [0.040, 0.040, 0.040]])} +# mftpar = {'prbfct': 'uniform', +# 'prbcnt': None, +# 'prbhw': None} +mftpar.update({'iter': 2, 'currexp': 1.0}) +mftpar.update({'regtype': 'PzetaE', 'zetareg': 1.00}) +# mftpar.update({ 'regtype':'classic', 'zetareg':1.0}) +mftpar.update({'solver': 'lu', 'svrelcut': 5.e-4}) + +print("mftpar['prbcnt' ] = ", mftpar['prbcnt']) +print("mftpar['prbhw' ] = ", mftpar['prbhw']) +print("mftpar['iter' ] = ", mftpar['iter']) +print("mftpar['regtype' ] = ", mftpar['regtype']) +print("mftpar['zetareg' ] = ", mftpar['zetareg']) +print("mftpar['solver' ] = ", mftpar['solver']) +print("mftpar['svrelcut'] = ", mftpar['svrelcut']) +cdmcut = 0.10 +print("cdmcut = ", cdmcut) + +print("########## get labels:") +if lblname is not None: + labels = mne.read_labels_from_annot(subject, parc=lblname, + subjects_dir=subjects_dir) +else: + labels = None + +print("##########################") +print("##### Calling apply_mft()") +print("##########################") +iterlist = [0, 1, 2] +fwdmag, qualmft, stc_mftl = apply_mft(fwdname, evoname, evocondition=evocondition, + subject=subject, meg=want_meg, iterlist=iterlist, + calccdm='all', cdmcut=cdmcut, cdmlabels=labels, + mftpar=mftpar, verbose='verbose') + +evo = mne.read_evokeds(evoname, condition=evocondition, baseline=(None, 0)) +tstep = 1. / evo.info['sfreq'] + +if iterlist == None: + stc_mft = stc_mftl +else: + stc_mft = stc_mftl[-1] +stcdata = stc_mft.data +tmin = stc_mft.tmin + +print(" ") +print("########## Some geo-numbers:") +lhinds = np.where(fwdmag['source_rr'][:, 0] <= 0.) +rhinds = np.where(fwdmag['source_rr'][:, 0] > 0.) +print("> Discriminating lh/rh by sign of fwdmag['source_rr'][:,0]:") +print("> lhinds[0].shape[0] = ", lhinds[0].shape[0], " rhinds[0].shape[0] = ", rhinds[0].shape[0]) +invmri_head_t = mne.transforms.invert_transform(fwdmag['info']['mri_head_t']) +mrsrc = np.zeros(fwdmag['source_rr'].shape) +mrsrc = mne.transforms.apply_trans(invmri_head_t['trans'], fwdmag['source_rr'], move=True) +lhmrinds = np.where(mrsrc[:, 0] <= 0.) +rhmrinds = np.where(mrsrc[:, 0] > 0.) +print("> Discriminating lh/rh by sign of fwdmag['source_rr'][:,0] in MR coords:") +print("> lhmrinds[0].shape[0] = ", lhmrinds[0].shape[0], " rhmrinds[0].shape[0] = ", rhmrinds[0].shape[0]) + +# plotting routines +jumeg_mft_plot.plot_global_cdv_dist(stcdata) +jumeg_mft_plot.plot_visualize_mft_sources(fwdmag, stcdata, tmin=tmin, tstep=tstep, + subject=subject, subjects_dir=subjects_dir) +jumeg_mft_plot.plot_cdv_distribution(fwdmag, stcdata) +jumeg_mft_plot.plot_max_amplitude_data(fwdmag, stcdata, tmin=tmin, tstep=tstep, + subject=subject) +jumeg_mft_plot.plot_max_cdv_data(stc_mft, lhmrinds, rhmrinds) +jumeg_mft_plot.plot_cdvsum_data(stc_mft, lhmrinds, rhmrinds) +jumeg_mft_plot.plot_quality_data(qualmft, stc_mft) +jumeg_mft_plot.plot_cdm_data(qualmft, stc_mft, cdmlabels=labels) +jumeg_mft_plot.plot_jlong_labeldata(qualmft, stc_mft, labels) +jumeg_mft_plot.plot_jtotal_labeldata(qualmft, stc_mft, labels) + +jumeg_mft_plot.plot_jlong_data(qualmft, stc_mft) + +print_transforms = False +if print_transforms: + print("##### Transforms:") + print("fwdmag['info']['mri_head_t']:") + print(fwdmag['info']['mri_head_t']) + invmri_head_t = mne.transforms.invert_transform(fwdmag['info']['mri_head_t']) + print("Inverse of fwdmag['info']['mri_head_t']:") + print(invmri_head_t) + +write_tab_files = True +if write_tab_files: + tabfilenam = 'testtab_stc.dat' + time_idx = np.argmax(np.max(stcdata, axis=0)) + print("##### Creating %s with |cdv(time_idx=%d)|" % (tabfilenam, time_idx)) + tabfile = open(tabfilenam, mode='w') + cdvnmax = np.max(stcdata[:, time_idx]) + n_loc = stcdata.shape[0] + tabfile.write("# time_idx = %d\n" % time_idx) + tabfile.write("# max amplitude = %11.4e\n" % cdvnmax) + tabfile.write("# x/mm y/mm z/mm |cdv| index\n") + for ipnt in range(int(n_loc / 3)): + copnt = 1000. * fwdmag['source_rr'][ipnt] + tabfile.write(" %7.2f %7.2f %7.2f %11.4e %5d\n" % \ + (copnt[0], copnt[1], copnt[2], stcdata[ipnt, time_idx], ipnt)) + tabfile.close() + +print("Done.") diff --git a/docs/build/html/_downloads/b7aef1f36035a0808fcf7f51751a6f64/plot_destriux_atlas_based_connectivity.ipynb b/docs/build/html/_downloads/b7aef1f36035a0808fcf7f51751a6f64/plot_destriux_atlas_based_connectivity.ipynb new file mode 100644 index 00000000..976ae213 --- /dev/null +++ b/docs/build/html/_downloads/b7aef1f36035a0808fcf7f51751a6f64/plot_destriux_atlas_based_connectivity.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Plot Destriux Atlas\n\nRead grouped aparc labels from yaml file.\n\nPlot grouped connectivity circle with these grouped labels\nfor the Destriux atlas.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import os.path as op\nfrom jumeg import get_jumeg_path\nfrom jumeg.connectivity import (plot_grouped_connectivity_circle,\n generate_random_connectivity_matrix)\nimport yaml\n\ngrouping_yaml_fname = op.join(get_jumeg_path(), 'data/destriux_aparc_cortex_based_grouping.yaml')\nlabel_names_yaml_fname = op.join(get_jumeg_path(), 'data/destriux_label_names.yaml')\n\nwith open(label_names_yaml_fname, 'r') as f:\n label_names = yaml.safe_load(f)['label_names']\n\n# make a random matrix with 148 nodes\ncon = generate_random_connectivity_matrix(size=(148, 148), symmetric=True)\ncon[con < 0.5] = 0.\n\n# plot grouped connnectivity\nplot_grouped_connectivity_circle(grouping_yaml_fname, con, label_names,\n labels_mode=None, colorbar_pos=(0.1, 0.1),\n replacer_dict=None,\n out_fname='fig_destriux_circle.png',\n n_lines=50, colorbar=True)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.16" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/docs/build/html/_downloads/b81b00963d15008d3cfddafaf2e024c1/plot_generate_surrogate_stcs.py b/docs/build/html/_downloads/b81b00963d15008d3cfddafaf2e024c1/plot_generate_surrogate_stcs.py new file mode 100644 index 00000000..6df3704d --- /dev/null +++ b/docs/build/html/_downloads/b81b00963d15008d3cfddafaf2e024c1/plot_generate_surrogate_stcs.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python + +''' +============= +Generate surrogate STCs +============= + + +Example to show surrogate generation on STCs using the jumeg Surrogates +module. +''' + +import os.path as op +import numpy as np +import matplotlib.pyplot as pl + +from mne.datasets import sample +from mne.minimum_norm import read_inverse_operator, apply_inverse_epochs +import mne + +from jumeg.jumeg_surrogates import Surrogates, check_power_spectrum + +data_path = sample.data_path() +subjects_dir = op.join(data_path, 'subjects') + +fname_inv = op.join(data_path, 'MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif') +fname_raw = op.join(data_path, 'MEG/sample/sample_audvis_filt-0-40_raw.fif') +fname_event = op.join(data_path, 'MEG/sample/sample_audvis_filt-0-40_raw-eve.fif') + +stcs_testing = True + +raw = mne.io.read_raw_fif(fname_raw) +events = mne.read_events(fname_event) +inverse_operator = read_inverse_operator(fname_inv) + +# add a bad channel +raw.info['bads'] += ['MEG 2443'] + +# pick MEG channels +picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=False, eog=False, + exclude='bads') + +# define epochs for left-auditory condition +event_id, tmin, tmax = 1, -0.2, 0.5 +epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks, + baseline=(None, 0), reject=dict(mag=4e-12, grad=4000e-13)) + + +snr = 1.0 # use lower SNR for single epochs +lambda2 = 1.0 / snr ** 2 +method = "dSPM" # use dSPM method (could also be MNE or sLORETA) +stcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, method, + pick_ori="normal", return_generator=False) + +# compute surrogates for one STC +surr_stcs = Surrogates(stcs[0]) +mysurr = surr_stcs.compute_surrogates(n_surr=10, return_generator=False) + +# check if surrogates are correctly computed +assert not np.array_equal(mysurr[0].data, + mysurr[1].data), 'Surrogates mostly equal' +assert not np.array_equal(stcs[0].data, + mysurr[2].data), 'Surrogates equal to original' + +# visualize results by plotting 1 the average across voxels +# of original and surrogate STC +pl.plot(stcs[0].data.mean(axis=0)) +for i in mysurr: + pl.plot(i.data.mean(axis=0), color='r') +pl.title('Averaged real vs surrogate source time courses') +pl.show() diff --git a/docs/build/html/_downloads/bbd16d5327114c752932eb3a4949b572/plot_perform_mft_volume.py b/docs/build/html/_downloads/bbd16d5327114c752932eb3a4949b572/plot_perform_mft_volume.py new file mode 100644 index 00000000..016b57f3 --- /dev/null +++ b/docs/build/html/_downloads/bbd16d5327114c752932eb3a4949b572/plot_perform_mft_volume.py @@ -0,0 +1,130 @@ +""" +==================== +Jumeg MFT volume. +==================== +""" + +import os.path as op +import numpy as np +import mne +from mne.datasets import sample +from jumeg.mft import (apply_mft, jumeg_mft_plot) + +data_path = sample.data_path() +subject = 'sample' +subjects_dir = op.join(data_path, 'subjects') +fwdname = op.join(data_path, 'MEG/sample/sample_audvis-meg-vol-7-fwd.fif') +evoname = op.join(data_path, 'MEG/sample/sample_audvis-ave.fif') +evocondition = 'Left Auditory' +rawname = op.join(data_path, 'MEG/sample/sample_audvis_10s-raw.fif') +t1_fname = op.join(subjects_dir, 'sample/mri/T1.mgz') + +# Set up pick list: MEG - bad channels +want_meg = 'mag' +want_ref = False +want_eeg = False +want_stim = False +exclude = 'bads' +include = [] + +print("########## MFT parameter:") +mftpar = {'prbfct': 'Gauss', + 'prbcnt': np.array([[-1.039, 0.013, 0.062], [-0.039, 0.013, 0.062]]), + 'prbhw': np.array([[0.040, 0.040, 0.040], [0.040, 0.040, 0.040]])} +# mftpar = { 'prbfct': 'uniform', +# 'prbcnt': None, +# 'prbhw': None} +mftpar.update({'iter': 4, 'currexp': 1.0}) +mftpar.update({'regtype': 'PzetaE', 'zetareg': 1.00}) +# mftpar.update({ 'regtype':'classic', 'zetareg':1.0}) +mftpar.update({'solver': 'lu', 'svrelcut': 5.e-4}) + +print("mftpar['prbcnt' ] = ", mftpar['prbcnt']) +print("mftpar['prbhw' ] = ", mftpar['prbhw']) +print("mftpar['iter' ] = ", mftpar['iter']) +print("mftpar['regtype' ] = ", mftpar['regtype']) +print("mftpar['zetareg' ] = ", mftpar['zetareg']) +print("mftpar['solver' ] = ", mftpar['solver']) +print("mftpar['svrelcut'] = ", mftpar['svrelcut']) +cdmcut = 0.10 +print("cdmcut = ", cdmcut) + +print("##########################") +print("##### Read fwd-soln:") +print("##########################") +fwd = mne.read_forward_solution(fwdname, verbose=True) + +# Select magnetometer channels: +fwdmag = mne.io.pick.pick_types_forward(fwd, meg=want_meg, ref_meg=False, + eeg=False, exclude=exclude) + +print(" ") +print("########## Some geo-numbers:") +lhinds = np.where(fwdmag['source_rr'][:, 0] <= 0.) +rhinds = np.where(fwdmag['source_rr'][:, 0] > 0.) +ypinds = np.where(fwdmag['source_rr'][:, 1] > 0.) +yninds = np.where(fwdmag['source_rr'][:, 1] <= 0.) +lhfinds = np.array(np.setdiff1d(lhinds[0], ypinds[0])) +lhbinds = np.array(np.setdiff1d(lhinds[0], yninds[0])) +rhfinds = np.array(np.setdiff1d(rhinds[0], ypinds[0])) +rhbinds = np.array(np.setdiff1d(rhinds[0], yninds[0])) +print("> Discriminating lh/rh by sign of fwdmag['source_rr'][:,0]:") +print("> lhinds[0].shape[0] = ", lhinds[0].shape[0], " rhinds[0].shape[0] = ", rhinds[0].shape[0]) +invmri_head_t = mne.transforms.invert_transform(fwdmag['info']['mri_head_t']) +mrsrc = np.zeros(fwdmag['source_rr'].shape) +mrsrc = mne.transforms.apply_trans(invmri_head_t['trans'], fwdmag['source_rr'], move=True) +lhmrinds = np.where(mrsrc[:, 0] <= 0.) +rhmrinds = np.where(mrsrc[:, 0] > 0.) +print("> Discriminating lh/rh by sign of fwdmag['source_rr'][:,0] in MR coords:") +print("> lhmrinds[0].shape[0] = ", lhmrinds[0].shape[0], " rhmrinds[0].shape[0] = ", rhmrinds[0].shape[0]) + +print("########## prepare to put labels into label-files:") +mylablist = [] +# mylab = mne.Label(lhinds[0],pos=fwdmag['source_rr'][lhinds[0],:],hemi='lh',name='test_lh', verbose=True) +# mylablist.append(mylab) +# mylab = mne.Label(rhinds[0],pos=fwdmag['source_rr'][rhinds[0],:],hemi='rh',name='test_rh', verbose=True) +# mylablist.append(mylab) + +# mylab = mne.Label(lhfinds,pos=fwdmag['source_rr'][lhfinds,:],hemi='lhf',name='test_lhf', verbose=True) +# mylablist.append(mylab) +# mylab = mne.Label(lhbinds,pos=fwdmag['source_rr'][lhbinds,:],hemi='lhb',name='test_lhb', verbose=True) +# mylablist.append(mylab) +# mylab = mne.Label(rhfinds,pos=fwdmag['source_rr'][rhfinds,:],hemi='rhf',name='test_rhf', verbose=True) +# mylablist.append(mylab) +# mylab = mne.Label(rhbinds,pos=fwdmag['source_rr'][rhbinds,:],hemi='rhb',name='test_rhb', verbose=True) +# mylablist.append(mylab) + +print("##################################") +print("##### Calling apply_mft(mylablist)") +print("##################################") +fwdmag, qualmft, stc_mft = apply_mft(fwdname, evoname, evocondition=evocondition, + subject=subject, meg=want_meg, + calccdm='all', cdmcut=cdmcut, cdmlabels=mylablist, + mftpar=mftpar, verbose='verbose') + +evo = mne.read_evokeds(evoname, condition=evocondition, baseline=(None, 0)) +tmin = -0.2 +tstep = 1. / evo.info['sfreq'] +stcdata = stc_mft.data + +# plotting routines +jumeg_mft_plot.plot_global_cdv_dist(stcdata) +# print ">>>>> skipping jumeg_mft_plot.plot_visualize_mft_sources() (fails due to old PySurfer-version)" +jumeg_mft_plot.plot_visualize_mft_sources(fwdmag, stcdata, tmin=tmin, tstep=tstep, + subject=subject, subjects_dir=subjects_dir) +jumeg_mft_plot.plot_cdv_distribution(fwdmag, stcdata) +jumeg_mft_plot.plot_max_amplitude_data(fwdmag, stcdata, tmin=tmin, tstep=tstep, + subject=subject) +jumeg_mft_plot.plot_max_cdv_data(stc_mft, lhmrinds, rhmrinds) +jumeg_mft_plot.plot_cdvsum_data(stc_mft, lhmrinds, rhmrinds) +jumeg_mft_plot.plot_quality_data(qualmft, stc_mft) +jumeg_mft_plot.plot_cdm_data(qualmft, stc_mft) + +jumeg_mft_plot.plot_cdm_data(qualmft, stc_mft, cdmlabels=mylablist) +jumeg_mft_plot.plot_jlong_labeldata(qualmft, stc_mft, mylablist) +jumeg_mft_plot.plot_jtotal_labeldata(qualmft, stc_mft, mylablist) + +jumeg_mft_plot.plot_cdm_data(qualmft, stc_mft) +jumeg_mft_plot.plot_jlong_data(qualmft, stc_mft) + +print("Done.") diff --git a/docs/build/html/_downloads/bd1ccb21bb215d6927165fdc98a48ee4/plot_custom_grouped_connectivity_circle.py b/docs/build/html/_downloads/bd1ccb21bb215d6927165fdc98a48ee4/plot_custom_grouped_connectivity_circle.py new file mode 100644 index 00000000..29b01a22 --- /dev/null +++ b/docs/build/html/_downloads/bd1ccb21bb215d6927165fdc98a48ee4/plot_custom_grouped_connectivity_circle.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python + +""" +============= +Plot Custom Grouped Circle +============= + +Example how to create a custom label groups and plot grouped connectivity +circle with these labels. + +Author: Praveen Sripad + Christian Kiefer +""" + +import os.path as op +import matplotlib.pyplot as plt +from jumeg import get_jumeg_path +from jumeg.connectivity import (plot_grouped_connectivity_circle, + generate_random_connectivity_matrix) + +import yaml + +labels_fname = op.join(get_jumeg_path(), 'data/desikan_label_names.yaml') +replacer_dict_fname = op.join(get_jumeg_path(), 'data/replacer_dictionaries.yaml') + +with open(labels_fname, 'r') as f: + label_names = yaml.safe_load(f)['label_names'] + +with open(replacer_dict_fname, 'r') as f: + replacer_dict = yaml.safe_load(f)['replacer_dict_aparc'] + +# make a random matrix with 68 nodes +con = generate_random_connectivity_matrix(size=(68, 68), symmetric=True) + +# make groups based on lobes +occipital = ['lateraloccipital', 'lingual', 'cuneus', 'pericalcarine'] +parietal = ['superiorparietal', 'inferiorparietal', 'precuneus', + 'postcentral', 'supramarginal'] +temporal = ['bankssts', 'temporalpole', 'superiortemporal', 'middletemporal', + 'transversetemporal', 'inferiortemporal', 'fusiform', + 'entorhinal', 'parahippocampal'] +insula = ['insula'] +cingulate = ['rostralanteriorcingulate', 'caudalanteriorcingulate', + 'posteriorcingulate', 'isthmuscingulate'] +frontal = ['superiorfrontal', 'rostralmiddlefrontal', 'caudalmiddlefrontal', + 'parsopercularis', 'parsorbitalis', 'parstriangularis', + 'lateralorbitofrontal', 'medialorbitofrontal', 'precentral', + 'paracentral', 'frontalpole'] + +# we need a list of dictionaries, one dict for each group to denote grouping +label_groups = [{'occipital': occipital}, {'parietal': parietal}, + {'temporal': temporal}, {'insula': insula}, + {'cingulate': cingulate}, + {'frontal': frontal}] + +n_colors = len(label_groups) +cmap = plt.get_cmap('Pastel1') +cortex_colors = cmap.colors[:n_colors] + cmap.colors[:n_colors][::-1] + +# plot simple connectivity circle with cortex based grouping and colors +plot_grouped_connectivity_circle(label_groups, con, label_names, + labels_mode='replace', + replacer_dict=replacer_dict, + cortex_colors=cortex_colors, vmin=0., vmax=1., + out_fname='fig_grouped_con_circle_cortex.png', + colorbar_pos=(0.1, 0.1), n_lines=50, colorbar=True, + colormap='viridis') diff --git a/docs/build/html/_downloads/bd6fb30c4de3cecd4985c36599d541fd/do_compare_ica_methods.py b/docs/build/html/_downloads/bd6fb30c4de3cecd4985c36599d541fd/do_compare_ica_methods.py new file mode 100644 index 00000000..aa4098fd --- /dev/null +++ b/docs/build/html/_downloads/bd6fb30c4de3cecd4985c36599d541fd/do_compare_ica_methods.py @@ -0,0 +1,83 @@ +""" +========== +Compare ICA methods +========== + +Compute the ica object on filtered data based on the mne and on the +jumeg method. +Compare pca_mean_ and pre_whitener_ for: +mne & filtered data, jumeg & filtered data, jumeg & unfiltered data +""" + +import os.path as op +import mne +from mne.preprocessing.ica import ICA as ICA_mne +from jumeg.decompose.ica_replace_mean_std import ICA as ICA_jumeg +from jumeg.decompose.ica_replace_mean_std import apply_ica_replace_mean_std +from mne.datasets import sample + +flow = 1. +fhigh = 45. + +reject = {'mag': 5e-12} + +data_path = sample.data_path() +subjects_dir = op.join(data_path, 'subjects') + +fname_raw = op.join(data_path, 'MEG/sample/sample_audvis_raw.fif') + +raw = mne.io.Raw(fname_raw, preload=True) +raw_filt = raw.copy().filter(flow, fhigh, method='fir', n_jobs=2, fir_design='firwin', phase='zero') + +# use 60s of data +raw_filt.crop(0, 60) +raw.crop(0, 60) +raw_unfilt = raw.copy() + +picks = mne.pick_types(raw.info, meg=True, exclude='bads') + +ica_mne = ICA_mne(method='fastica', n_components=60, random_state=42, + max_pca_components=None, max_iter=5000, verbose=False) + +# fit ica object from mne to filtered data +ica_mne.fit(raw_filt, picks=picks, reject=reject, verbose=True) + +# save mean and standard deviation of filtered MEG channels for the standard mne routine +pca_mean_filt_mne = ica_mne.pca_mean_.copy() +pca_pre_whitener_filt_mne = ica_mne.pre_whitener_.copy() # this is the standard deviation of MEG channels + + +ica_jumeg = ICA_jumeg(method='fastica', n_components=60, random_state=42, + max_pca_components=None, max_iter=5000, verbose=False) + +# fit ica object from jumeg to filtered data +ica_jumeg.fit(raw_filt, picks=picks, reject=reject, verbose=True) + +# save mean and standard deviation of filtered MEG channels for the standard mne routine +pca_mean_filt_jumeg = ica_jumeg.pca_mean_.copy() +pca_pre_whitener_filt_jumeg = ica_jumeg.pre_whitener_.copy() # this is the standard deviation of MEG channels + +# use the same arguments for apply_ica_replace_mean_std as when you are initializing the ICA +# object and when you are fitting it to the data +# the ica object is modified in place!! + +# apply ica object from jumeg to unfiltered data while replacing the mean and std +raw_clean = apply_ica_replace_mean_std(raw_unfilt, ica_jumeg, picks=picks, reject=reject, exclude=ica_mne.exclude, + n_pca_components=None) + +# save mean and standard deviation of unfiltered MEG channels +pca_mean_replaced_unfilt_jumeg = ica_jumeg.pca_mean_ +pca_pre_whitener_replaced_unfilt_jumeg = ica_jumeg.pre_whitener_ + +# compare methods for filtered and unfiltered data +for idx in range(0, len(pca_mean_filt_mne)): + print('%10.6f\t%10.6f\t%10.6f' % (pca_mean_filt_mne[idx], pca_mean_filt_jumeg[idx], + pca_mean_replaced_unfilt_jumeg[idx])) + if idx >= 9: + break + +for idx in range(0, len(pca_pre_whitener_filt_mne)): + print(pca_pre_whitener_filt_mne[idx], pca_pre_whitener_filt_jumeg[idx],\ + pca_pre_whitener_replaced_unfilt_jumeg[idx]) + if idx >= 9: + break diff --git a/docs/build/html/_downloads/c1cc30f1797ae60c2483e04541eb834b/plot_circle_lines_and_blobs.ipynb b/docs/build/html/_downloads/c1cc30f1797ae60c2483e04541eb834b/plot_circle_lines_and_blobs.ipynb new file mode 100644 index 00000000..899abe1c --- /dev/null +++ b/docs/build/html/_downloads/c1cc30f1797ae60c2483e04541eb834b/plot_circle_lines_and_blobs.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Plot centrality indices on connectivity circle plot\n\nScript to show functionality to plot centrality indices along with\nconnectivity circle plot.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import os.path as op\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport mne\nfrom mne_connectivity import degree\nfrom jumeg import get_jumeg_path\nfrom jumeg.connectivity import plot_degree_circle, plot_lines_and_blobs\n\nimport bct\nimport yaml\n\norig_labels_fname = op.join(get_jumeg_path(), 'data/desikan_label_names.yaml')\nyaml_fname = op.join(get_jumeg_path(), 'data/desikan_aparc_cortex_based_grouping.yaml')\ncon_fname = op.join(get_jumeg_path(), 'data/sample,aparc-con.npy')\n\nreplacer_dict_fname = op.join(get_jumeg_path(), 'data/replacer_dictionaries.yaml')\n\nwith open(replacer_dict_fname, 'r') as f:\n replacer_dict = yaml.safe_load(f)['replacer_dict_aparc']\n\n# real connectivity\ncon = np.load(con_fname)\ncon = con[0, :, :, 2] + con[0, :, :, 2].T\ndegrees = degree(con, threshold_prop=0.2)\n\neigenvec_centrality = bct.eigenvector_centrality_und(con)\n\nfig, ax = plot_lines_and_blobs(con, degrees, yaml_fname,\n orig_labels_fname, replacer_dict=replacer_dict,\n figsize=(8, 8), show_node_labels=False,\n show_group_labels=True, n_lines=100,\n out_fname=None, degsize=10)\nax.set_title('Eigen vector centrality: Coh,alpha')\nfig.tight_layout()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.16" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/docs/build/html/_downloads/c41430a98314738751bb833828af6f7a/plot_compute_label_distances.ipynb b/docs/build/html/_downloads/c41430a98314738751bb833828af6f7a/plot_compute_label_distances.ipynb new file mode 100644 index 00000000..39183bd7 --- /dev/null +++ b/docs/build/html/_downloads/c41430a98314738751bb833828af6f7a/plot_compute_label_distances.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Compute Label Distances\n\nScript show how to compute and visualize distance between label center of\nmasses for a given subject.\n\nAuthor: Praveen Sripad \n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import os.path as op\nfrom jumeg.connectivity import get_label_distances\nfrom surfer import Brain\nfrom nilearn import plotting\nfrom mne.datasets import sample\n\ndata_path = sample.data_path()\nsubjects_dir = op.join(data_path, 'subjects')\nsubject = 'sample'\nparc = 'aparc_sub'\n\n# compute the distances between COM's of the labels\nrounded_coms, coords, coms_lh, coms_rh = get_label_distances(subject,\n subjects_dir,\n parc=parc)\n# np.save('%s_distances.npy' % subject, rounded_com)\n\n# get maximum distance between ROIs\nprint('Max distance between ROIs', rounded_coms.ravel().max())\n\n# do plotting using PySurfer\nbrain = Brain(subject, hemi='both', surf='inflated', subjects_dir=subjects_dir)\nbrain.add_foci(coms_lh, coords_as_verts=True, hemi='lh')\nbrain.add_foci(coms_rh, coords_as_verts=True, hemi='rh')\nbrain.save_montage('%s_%s_coms.png' % (subject, parc),\n order=['lat', 'ven', 'med'],\n orientation='h', border_size=15, colorbar='auto',\n row=-1, col=-1)\nbrain.close()\n\n# show the label ROIs using Nilearn plotting\nfig = plotting.plot_connectome(rounded_coms, coords,\n edge_threshold='99%', node_color='cornflowerblue',\n title='%s - label distances' % parc)\nfig.savefig('fig_%s_label_distances.png' % parc)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.16" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/docs/build/html/_downloads/c64794a2fe5bf746f72d0dda76f6f4ed/plot_simulated_connectivity.ipynb b/docs/build/html/_downloads/c64794a2fe5bf746f72d0dda76f6f4ed/plot_simulated_connectivity.ipynb new file mode 100644 index 00000000..5cd30513 --- /dev/null +++ b/docs/build/html/_downloads/c64794a2fe5bf746f72d0dda76f6f4ed/plot_simulated_connectivity.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Simulating Connectivity \n\nSimple implementations of connectivity measures.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Authors : pravsripad@gmail.com\n# daniel.vandevelden@yahoo.de\n\nimport os.path as op\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as pl\nimport matplotlib.mlab as mlab\n\nn_epochs = 120\nsfreq, duration = 1000., 1000\ntimes = np.arange(0, duration, 1 / sfreq)\namp , amp2 , nse_amp = 1., 1., 0.5\nnfft = 512\n\nnse1 = np.random.rand(times.size) * nse_amp\nnse2 = np.random.rand(times.size) * nse_amp\nx = amp * np.sin(2 * np.pi * 200 * times) + nse1\ny = amp * np.sin(2 * np.pi * 200 * times + np.pi/5) + nse2\n\nshift = 100 # integer\nassert shift < sfreq * duration, 'Choose a smaller shift.'\n#y = amp2 * np.roll(x, shift) + nse2\n\n# coherence using mlab function\ncohxy, freqs = mlab.cohere(x, y, Fs=sfreq, NFFT=nfft)\n\nn_freqs = int(nfft/2 + 1)\n\ndef compute_mean_psd_csd(x, y, n_epochs, nfft, sfreq):\n '''Computes mean of PSD and CSD for signals.'''\n x2 = np.array_split(x, n_epochs)\n y2 = np.array_split(y, n_epochs)\n\n Rxy = np.zeros((n_epochs, n_freqs), dtype=complex)\n Rxx = np.zeros((n_epochs, n_freqs), dtype=complex)\n Ryy = np.zeros((n_epochs, n_freqs), dtype=complex)\n\n for i in range(n_epochs):\n Rxy[i], freqs = mlab.csd(x2[i], y2[i], NFFT=nfft, Fs=sfreq)\n Rxx[i], _ = mlab.psd(x2[i], NFFT=nfft, Fs=sfreq)\n Ryy[i], _ = mlab.psd(y2[i], NFFT=nfft, Fs=sfreq)\n\n Rxy_mean = np.mean(Rxy, axis=0)\n Rxx_mean = np.mean(Rxx, axis=0)\n Ryy_mean = np.mean(Ryy, axis=0)\n\n return freqs, Rxy, Rxy_mean, np.real(Rxx_mean), np.real(Ryy_mean)\n\ndef my_coherence(n_freqs, Rxy_mean, Rxx_mean, Ryy_mean):\n ''' Computes coherence. '''\n\n coh = np.zeros((n_freqs))\n for i in range(0, n_freqs):\n coh[i] = np.abs(Rxy_mean[i]) / np.sqrt(Rxx_mean[i] * Ryy_mean[i])\n\n return coh\n\ndef my_imcoh(n_freqs, Rxy_mean, Rxx_mean, Ryy_mean):\n ''' Computes imaginary coherence. '''\n\n imcoh = np.zeros((n_freqs))\n for i in range(0, n_freqs):\n imcoh[i] = np.imag(Rxy_mean[i]) / np.sqrt(Rxx_mean[i] * Ryy_mean[i])\n\n return imcoh\n\ndef my_cohy(n_freqs, Rxy_mean, Rxx_mean, Ryy_mean):\n ''' Computes coherency. '''\n\n cohy = np.zeros((n_freqs))\n for i in range(0, n_freqs):\n cohy[i] = np.real(Rxy_mean[i]) / np.sqrt(Rxx_mean[i] * Ryy_mean[i])\n\n return cohy\n\ndef my_plv(n_freqs, Rxy, Rxy_mean):\n ''' Computes PLV. '''\n\n Rxy_plv = np.zeros((n_epochs, n_freqs), dtype=complex)\n for i in range(0, n_epochs):\n Rxy_plv[i] = Rxy[i] / np.abs(Rxy[i])\n\n plv = np.abs(np.mean(Rxy_plv, axis=0))\n return plv\n\ndef my_pli(n_freqs, Rxy, Rxy_mean):\n ''' Computes PLI. '''\n Rxy_pli = np.zeros((n_epochs, n_freqs), dtype=complex)\n for i in range(0, n_epochs):\n Rxy_pli[i] = np.sign(np.imag(Rxy[i]))\n\n pli = np.abs(np.mean(Rxy_pli, axis=0))\n return pli\n\ndef my_wpli(n_freqs, Rxy, Rxy_mean):\n ''' Computes WPLI. '''\n Rxy_wpli_1 = np.zeros((n_epochs, n_freqs), dtype=complex)\n Rxy_wpli_2 = np.zeros((n_epochs, n_freqs), dtype=complex)\n for i in range(0, n_epochs):\n Rxy_wpli_1[i] = np.imag(Rxy[i])\n Rxy_wpli_2[i] = np.abs(np.imag(Rxy[i]))\n\n # handle divide by zero\n denom = np.mean(Rxy_wpli_2, axis=0)\n idx_denom = np.where(denom == 0.)\n denom[idx_denom] = 1.\n wpli = np.abs(np.mean(Rxy_wpli_1, axis=0)) / denom\n wpli[idx_denom] = 0.\n return wpli\n\n\ndef my_con(x, y, n_epochs, nfft, sfreq, con_name='coh'):\n '''Computes connectivity measure mentioned on provided signal pair and its surrogates.'''\n\n freqs, Rxy, Rxy_mean, Rxx_mean, Ryy_mean = compute_mean_psd_csd(x, y, n_epochs, nfft, sfreq)\n\n # compute surrogates\n x_surr = x.copy() \n y_surr = y.copy()\n np.random.shuffle(x_surr)\n np.random.shuffle(y_surr)\n freqs_surro, Rxy_s, Rxy_s_mean, Rxx_s_mean, Ryy_s_mean = compute_mean_psd_csd(x_surr, y_surr, n_epochs, nfft, sfreq)\n\n if con_name == 'coh':\n coh = my_coherence(n_freqs, Rxy_mean, Rxx_mean, Ryy_mean)\n coh_surro = my_coherence(n_freqs, Rxy_s_mean, Rxx_s_mean, Ryy_s_mean)\n return coh, coh_surro, freqs, freqs_surro\n\n if con_name == 'imcoh':\n imcoh = my_imcoh(n_freqs, Rxy_mean, Rxx_mean, Ryy_mean)\n imcoh_surro = my_imcoh(n_freqs, Rxy_s_mean, Rxx_s_mean, Ryy_s_mean)\n return imcoh, imcoh_surro, freqs, freqs_surro\n\n if con_name == 'cohy':\n cohy = my_cohy(n_freqs, Rxy_mean, Rxx_mean, Ryy_mean)\n cohy_surro = my_cohy(n_freqs, Rxy_s_mean, Rxx_s_mean, Ryy_s_mean)\n return cohy, cohy_surro, freqs, freqs_surro\n\n if con_name == 'plv':\n plv = my_plv(n_freqs, Rxy, Rxy_mean)\n plv_surro = my_plv(n_freqs, Rxy_s, Rxy_s_mean)\n return plv, plv_surro, freqs, freqs_surro\n\n if con_name == 'pli':\n pli = my_pli(n_freqs, Rxy, Rxy_mean)\n pli_surro = my_pli(n_freqs, Rxy_s, Rxy_s_mean)\n return pli, pli_surro, freqs, freqs_surro\n\n if con_name == 'wpli':\n wpli = my_wpli(n_freqs, Rxy, Rxy_mean)\n wpli_surro = my_wpli(n_freqs, Rxy_s, Rxy_s_mean)\n return wpli, wpli_surro, freqs, freqs_surro\n\n if con_name == '':\n print('Please provide the connectivity method to use.')\n sys.exit()\n else:\n print('Connectivity method unrecognized.')\n sys.exit()\n\ncon_name = 'wpli'\ncon, con_surro, freqs, freqs_surro = my_con(x, y, n_epochs, nfft, sfreq, con_name)\n\n# coherence using mlab function\n#cohxy, freqs = mlab.cohere(x, y, Fs=sfreq, NFFT=nfft)\n#pl.plot(freqs, cohxy)\n\n# plot results\npl.figure('Connectivity')\npl.plot(freqs, con)\npl.plot(freqs_surro, con_surro)\npl.legend(['Con', 'Surrogates'])\npl.tight_layout()\npl.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.16" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/docs/build/html/_downloads/cca1eef05669dc79b2935c67c97fab8f/plot_inter_and_intra_lobe_causality.ipynb b/docs/build/html/_downloads/cca1eef05669dc79b2935c67c97fab8f/plot_inter_and_intra_lobe_causality.ipynb new file mode 100644 index 00000000..c0796b50 --- /dev/null +++ b/docs/build/html/_downloads/cca1eef05669dc79b2935c67c97fab8f/plot_inter_and_intra_lobe_causality.ipynb @@ -0,0 +1,115 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Group Causality Matrix\n\nGroup a causality matrix by lobes and plot the resulting\ninter- and intra-lobe causality.\n\nAuthor: Christian Kiefer \n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import os\nimport os.path as op\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport mne\n\nfrom mne.datasets import sample\n\nprint(__doc__)\n\ndata_path = sample.data_path()\n\nfrom jumeg.connectivity.con_utils import group_con_matrix_by_lobe\nfrom jumeg.connectivity.con_viz import plot_grouped_causality_circle\nfrom jumeg.jumeg_utils import get_jumeg_path" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Load the grouping files\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "grouping_yaml_fname = op.join(get_jumeg_path(), 'data',\n 'desikan_aparc_cortex_based_grouping_ck.yaml')\nlobe_grouping_yaml_fname = op.join(get_jumeg_path(), 'data',\n 'lobes_grouping.yaml')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Load anatomical labels\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "subjects_dir = op.join(data_path, 'subjects')\nos.environ['SUBJECTS_DIR'] = subjects_dir\n\nfull_labels = mne.read_labels_from_annot(subject='fsaverage', parc='aparc',\n hemi='both', subjects_dir=subjects_dir)\n\nfull_label_names = [full_label.name for full_label in full_labels if full_label.name.find('unknown') == -1]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## create random causality matrix\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# create causality matrix\nnp.random.seed(42)\ncau = np.random.uniform(-0.99, 0.01, (len(full_label_names), len(full_label_names)))\n\ncau[cau < 0] = 0\ncau = cau / 0.01 # values between 0 and 1\n\ncau_grp, grp_label_names = group_con_matrix_by_lobe(con=cau, label_names=full_label_names,\n grouping_yaml_fname=grouping_yaml_fname)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Compare original matrix with grouped matrix plot\n\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "fig = plot_grouped_causality_circle(cau, grouping_yaml_fname, full_label_names,\n title='original causality matrix', n_lines=None,\n labels_mode=None, replacer_dict=None, out_fname=None,\n colormap='magma_r', colorbar=True, colorbar_pos=(-0.25, 0.05),\n arrowstyle='->,head_length=0.7,head_width=0.4',\n figsize=(9.1, 6), vmin=0., vmax=1.0, ignore_diagonal=True,\n show=True)\n\nplt.close(fig)\n\nfig = plot_grouped_causality_circle(cau_grp, lobe_grouping_yaml_fname, grp_label_names,\n title='test', n_lines=None, labels_mode=None,\n replacer_dict=None, out_fname=None, colormap='magma_r',\n colorbar=True, colorbar_pos=(-0.25, 0.05),\n arrowstyle='->,head_length=0.7,head_width=0.4',\n figsize=(9.1, 6), vmin=0., ignore_diagonal=False,\n show=True)\n\nplt.close(fig)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.16" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/docs/build/html/_downloads/d1fabb73f4fa58e5840c9920de5e984c/plot_custom_grouped_connectivity_circle.ipynb b/docs/build/html/_downloads/d1fabb73f4fa58e5840c9920de5e984c/plot_custom_grouped_connectivity_circle.ipynb new file mode 100644 index 00000000..6286e2d2 --- /dev/null +++ b/docs/build/html/_downloads/d1fabb73f4fa58e5840c9920de5e984c/plot_custom_grouped_connectivity_circle.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Plot Custom Grouped Circle\n\nExample how to create a custom label groups and plot grouped connectivity\ncircle with these labels.\n\nAuthor: Praveen Sripad \n Christian Kiefer \n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import os.path as op\nimport matplotlib.pyplot as plt\nfrom jumeg import get_jumeg_path\nfrom jumeg.connectivity import (plot_grouped_connectivity_circle,\n generate_random_connectivity_matrix)\n\nimport yaml\n\nlabels_fname = op.join(get_jumeg_path(), 'data/desikan_label_names.yaml')\nreplacer_dict_fname = op.join(get_jumeg_path(), 'data/replacer_dictionaries.yaml')\n\nwith open(labels_fname, 'r') as f:\n label_names = yaml.safe_load(f)['label_names']\n\nwith open(replacer_dict_fname, 'r') as f:\n replacer_dict = yaml.safe_load(f)['replacer_dict_aparc']\n\n# make a random matrix with 68 nodes\ncon = generate_random_connectivity_matrix(size=(68, 68), symmetric=True)\n\n# make groups based on lobes\noccipital = ['lateraloccipital', 'lingual', 'cuneus', 'pericalcarine']\nparietal = ['superiorparietal', 'inferiorparietal', 'precuneus',\n 'postcentral', 'supramarginal']\ntemporal = ['bankssts', 'temporalpole', 'superiortemporal', 'middletemporal',\n 'transversetemporal', 'inferiortemporal', 'fusiform',\n 'entorhinal', 'parahippocampal']\ninsula = ['insula']\ncingulate = ['rostralanteriorcingulate', 'caudalanteriorcingulate',\n 'posteriorcingulate', 'isthmuscingulate']\nfrontal = ['superiorfrontal', 'rostralmiddlefrontal', 'caudalmiddlefrontal',\n 'parsopercularis', 'parsorbitalis', 'parstriangularis',\n 'lateralorbitofrontal', 'medialorbitofrontal', 'precentral',\n 'paracentral', 'frontalpole']\n\n# we need a list of dictionaries, one dict for each group to denote grouping\nlabel_groups = [{'occipital': occipital}, {'parietal': parietal},\n {'temporal': temporal}, {'insula': insula},\n {'cingulate': cingulate},\n {'frontal': frontal}]\n\nn_colors = len(label_groups)\ncmap = plt.get_cmap('Pastel1')\ncortex_colors = cmap.colors[:n_colors] + cmap.colors[:n_colors][::-1]\n\n# plot simple connectivity circle with cortex based grouping and colors\nplot_grouped_connectivity_circle(label_groups, con, label_names,\n labels_mode='replace',\n replacer_dict=replacer_dict,\n cortex_colors=cortex_colors, vmin=0., vmax=1.,\n out_fname='fig_grouped_con_circle_cortex.png',\n colorbar_pos=(0.1, 0.1), n_lines=50, colorbar=True,\n colormap='viridis')" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.16" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/docs/build/html/_downloads/d5c0e071ad54cf4b9f9603f9009d1ce1/plot_brain_connectome.py b/docs/build/html/_downloads/d5c0e071ad54cf4b9f9603f9009d1ce1/plot_brain_connectome.py new file mode 100644 index 00000000..af60f709 --- /dev/null +++ b/docs/build/html/_downloads/d5c0e071ad54cf4b9f9603f9009d1ce1/plot_brain_connectome.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python + +""" +============= +Plot brain connectome +============= + +Plot connectivity on a glass brain using 'plot_connectome' function from +Nilearn (https://nilearn.github.io/). + +Author: Praveen Sripad +""" + +import os.path as op +import numpy as np +import matplotlib.pyplot as plt + +import mne +from mne.datasets import sample + +from nilearn import plotting + +from jumeg.connectivity import generate_random_connectivity_matrix + +data_path = sample.data_path() +subjects_dir = op.join(data_path, 'subjects') +subject = 'fsaverage' + +aparc = mne.read_labels_from_annot(subject, subjects_dir=subjects_dir, + parc='aparc') + +# nodes in one hemisphere can be plotted as well +aparc_lh = [lab for lab in aparc if lab.hemi == 'lh'] + +coords = [] + +# plot 10 nodes from left hemisphere only for better viz +for lab in aparc_lh[:10]: + if lab.name == 'unknown-lh': + continue + # get the center of mass + com = lab.center_of_mass('fsaverage') + # obtain mni coordinated to the vertex from left hemi + coords_ = mne.vertex_to_mni(com, hemis=0, subject=subject, + subjects_dir=subjects_dir) + coords.append(coords_) + +n_nodes = np.array(coords).shape[0] + +# make a random connectivity matrix +con = generate_random_connectivity_matrix(size=(n_nodes, n_nodes), + symmetric=True) + +# plot the connectome on a glass brain background +plotting.plot_connectome(con, coords) +plt.show() diff --git a/docs/build/html/_downloads/d7247b3a446053a7e80e017ac5eb24b4/plot_interpolate_bads.py b/docs/build/html/_downloads/d7247b3a446053a7e80e017ac5eb24b4/plot_interpolate_bads.py new file mode 100644 index 00000000..1f05ac02 --- /dev/null +++ b/docs/build/html/_downloads/d7247b3a446053a7e80e017ac5eb24b4/plot_interpolate_bads.py @@ -0,0 +1,27 @@ +""" +==================== +Plot and interpolate bads +==================== + +Use suggest_bads to automatically identify bad MEG channels +and use interpolate_bads based on the center of mass of the +sensors for bad channel correction. +""" + +import os.path as op + +import mne +from mne.datasets import sample +from jumeg import suggest_bads +from jumeg import interpolate_bads + +data_path = sample.data_path() +subjects_dir = op.join(data_path, 'subjects') + +raw_fname = op.join(data_path, 'MEG/sample/sample_audvis_raw.fif') + +raw = mne.io.Raw(raw_fname, preload=True) +mybads, raw = suggest_bads(raw, show_raw=False, summary_plot=False) + +# origin = None causes the method to use the sensor center of mass as origin +interpolate_bads(raw, origin=None, reset_bads=True) diff --git a/docs/build/html/_downloads/dd278fb25d15f5e6a12562a958c0eda0/plot_simulated_connectivity.py b/docs/build/html/_downloads/dd278fb25d15f5e6a12562a958c0eda0/plot_simulated_connectivity.py new file mode 100644 index 00000000..42bb2335 --- /dev/null +++ b/docs/build/html/_downloads/dd278fb25d15f5e6a12562a958c0eda0/plot_simulated_connectivity.py @@ -0,0 +1,185 @@ +#!/usr/bin/env python + +''' +========== +Simulating Connectivity +========== + +Simple implementations of connectivity measures. +''' + +# Authors : pravsripad@gmail.com +# daniel.vandevelden@yahoo.de + +import os.path as op +import sys +import numpy as np +import matplotlib.pyplot as pl +import matplotlib.mlab as mlab + +n_epochs = 120 +sfreq, duration = 1000., 1000 +times = np.arange(0, duration, 1 / sfreq) +amp , amp2 , nse_amp = 1., 1., 0.5 +nfft = 512 + +nse1 = np.random.rand(times.size) * nse_amp +nse2 = np.random.rand(times.size) * nse_amp +x = amp * np.sin(2 * np.pi * 200 * times) + nse1 +y = amp * np.sin(2 * np.pi * 200 * times + np.pi/5) + nse2 + +shift = 100 # integer +assert shift < sfreq * duration, 'Choose a smaller shift.' +#y = amp2 * np.roll(x, shift) + nse2 + +# coherence using mlab function +cohxy, freqs = mlab.cohere(x, y, Fs=sfreq, NFFT=nfft) + +n_freqs = int(nfft/2 + 1) + +def compute_mean_psd_csd(x, y, n_epochs, nfft, sfreq): + '''Computes mean of PSD and CSD for signals.''' + x2 = np.array_split(x, n_epochs) + y2 = np.array_split(y, n_epochs) + + Rxy = np.zeros((n_epochs, n_freqs), dtype=complex) + Rxx = np.zeros((n_epochs, n_freqs), dtype=complex) + Ryy = np.zeros((n_epochs, n_freqs), dtype=complex) + + for i in range(n_epochs): + Rxy[i], freqs = mlab.csd(x2[i], y2[i], NFFT=nfft, Fs=sfreq) + Rxx[i], _ = mlab.psd(x2[i], NFFT=nfft, Fs=sfreq) + Ryy[i], _ = mlab.psd(y2[i], NFFT=nfft, Fs=sfreq) + + Rxy_mean = np.mean(Rxy, axis=0) + Rxx_mean = np.mean(Rxx, axis=0) + Ryy_mean = np.mean(Ryy, axis=0) + + return freqs, Rxy, Rxy_mean, np.real(Rxx_mean), np.real(Ryy_mean) + +def my_coherence(n_freqs, Rxy_mean, Rxx_mean, Ryy_mean): + ''' Computes coherence. ''' + + coh = np.zeros((n_freqs)) + for i in range(0, n_freqs): + coh[i] = np.abs(Rxy_mean[i]) / np.sqrt(Rxx_mean[i] * Ryy_mean[i]) + + return coh + +def my_imcoh(n_freqs, Rxy_mean, Rxx_mean, Ryy_mean): + ''' Computes imaginary coherence. ''' + + imcoh = np.zeros((n_freqs)) + for i in range(0, n_freqs): + imcoh[i] = np.imag(Rxy_mean[i]) / np.sqrt(Rxx_mean[i] * Ryy_mean[i]) + + return imcoh + +def my_cohy(n_freqs, Rxy_mean, Rxx_mean, Ryy_mean): + ''' Computes coherency. ''' + + cohy = np.zeros((n_freqs)) + for i in range(0, n_freqs): + cohy[i] = np.real(Rxy_mean[i]) / np.sqrt(Rxx_mean[i] * Ryy_mean[i]) + + return cohy + +def my_plv(n_freqs, Rxy, Rxy_mean): + ''' Computes PLV. ''' + + Rxy_plv = np.zeros((n_epochs, n_freqs), dtype=complex) + for i in range(0, n_epochs): + Rxy_plv[i] = Rxy[i] / np.abs(Rxy[i]) + + plv = np.abs(np.mean(Rxy_plv, axis=0)) + return plv + +def my_pli(n_freqs, Rxy, Rxy_mean): + ''' Computes PLI. ''' + Rxy_pli = np.zeros((n_epochs, n_freqs), dtype=complex) + for i in range(0, n_epochs): + Rxy_pli[i] = np.sign(np.imag(Rxy[i])) + + pli = np.abs(np.mean(Rxy_pli, axis=0)) + return pli + +def my_wpli(n_freqs, Rxy, Rxy_mean): + ''' Computes WPLI. ''' + Rxy_wpli_1 = np.zeros((n_epochs, n_freqs), dtype=complex) + Rxy_wpli_2 = np.zeros((n_epochs, n_freqs), dtype=complex) + for i in range(0, n_epochs): + Rxy_wpli_1[i] = np.imag(Rxy[i]) + Rxy_wpli_2[i] = np.abs(np.imag(Rxy[i])) + + # handle divide by zero + denom = np.mean(Rxy_wpli_2, axis=0) + idx_denom = np.where(denom == 0.) + denom[idx_denom] = 1. + wpli = np.abs(np.mean(Rxy_wpli_1, axis=0)) / denom + wpli[idx_denom] = 0. + return wpli + + +def my_con(x, y, n_epochs, nfft, sfreq, con_name='coh'): + '''Computes connectivity measure mentioned on provided signal pair and its surrogates.''' + + freqs, Rxy, Rxy_mean, Rxx_mean, Ryy_mean = compute_mean_psd_csd(x, y, n_epochs, nfft, sfreq) + + # compute surrogates + x_surr = x.copy() + y_surr = y.copy() + np.random.shuffle(x_surr) + np.random.shuffle(y_surr) + freqs_surro, Rxy_s, Rxy_s_mean, Rxx_s_mean, Ryy_s_mean = compute_mean_psd_csd(x_surr, y_surr, n_epochs, nfft, sfreq) + + if con_name == 'coh': + coh = my_coherence(n_freqs, Rxy_mean, Rxx_mean, Ryy_mean) + coh_surro = my_coherence(n_freqs, Rxy_s_mean, Rxx_s_mean, Ryy_s_mean) + return coh, coh_surro, freqs, freqs_surro + + if con_name == 'imcoh': + imcoh = my_imcoh(n_freqs, Rxy_mean, Rxx_mean, Ryy_mean) + imcoh_surro = my_imcoh(n_freqs, Rxy_s_mean, Rxx_s_mean, Ryy_s_mean) + return imcoh, imcoh_surro, freqs, freqs_surro + + if con_name == 'cohy': + cohy = my_cohy(n_freqs, Rxy_mean, Rxx_mean, Ryy_mean) + cohy_surro = my_cohy(n_freqs, Rxy_s_mean, Rxx_s_mean, Ryy_s_mean) + return cohy, cohy_surro, freqs, freqs_surro + + if con_name == 'plv': + plv = my_plv(n_freqs, Rxy, Rxy_mean) + plv_surro = my_plv(n_freqs, Rxy_s, Rxy_s_mean) + return plv, plv_surro, freqs, freqs_surro + + if con_name == 'pli': + pli = my_pli(n_freqs, Rxy, Rxy_mean) + pli_surro = my_pli(n_freqs, Rxy_s, Rxy_s_mean) + return pli, pli_surro, freqs, freqs_surro + + if con_name == 'wpli': + wpli = my_wpli(n_freqs, Rxy, Rxy_mean) + wpli_surro = my_wpli(n_freqs, Rxy_s, Rxy_s_mean) + return wpli, wpli_surro, freqs, freqs_surro + + if con_name == '': + print('Please provide the connectivity method to use.') + sys.exit() + else: + print('Connectivity method unrecognized.') + sys.exit() + +con_name = 'wpli' +con, con_surro, freqs, freqs_surro = my_con(x, y, n_epochs, nfft, sfreq, con_name) + +# coherence using mlab function +#cohxy, freqs = mlab.cohere(x, y, Fs=sfreq, NFFT=nfft) +#pl.plot(freqs, cohxy) + +# plot results +pl.figure('Connectivity') +pl.plot(freqs, con) +pl.plot(freqs_surro, con_surro) +pl.legend(['Con', 'Surrogates']) +pl.tight_layout() +pl.show() diff --git a/docs/build/html/_downloads/de46ae9b6690abebc2a58ded49329a96/plot_perform_mft_surface_list.ipynb b/docs/build/html/_downloads/de46ae9b6690abebc2a58ded49329a96/plot_perform_mft_surface_list.ipynb new file mode 100644 index 00000000..f0e0bde3 --- /dev/null +++ b/docs/build/html/_downloads/de46ae9b6690abebc2a58ded49329a96/plot_perform_mft_surface_list.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Jumeg MFT example.\n\nPerform MFT on a surface based forward solution.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import os.path as op\nimport numpy as np\nimport mne\nfrom mne.datasets import sample\nfrom jumeg.mft import (apply_mft, jumeg_mft_plot)\n\ndata_path = sample.data_path()\nsubject = 'sample'\nsubjects_dir = op.join(data_path, 'subjects')\nfwdname = op.join(data_path, 'MEG/sample/sample_audvis-meg-oct-6-fwd.fif')\nlblname = 'aparc'\nevoname = op.join(data_path, 'MEG/sample/sample_audvis-ave.fif')\nevocondition = 'Left Auditory'\nrawname = op.join(data_path, 'MEG/sample/sample_audvis_10s-raw.fif')\nt1_fname = op.join(subjects_dir, 'sample/mri/T1.mgz')\n\n# Set up pick list: MEG - bad channels\nwant_meg = 'mag'\nwant_ref = False\nwant_eeg = False\nwant_stim = False\nexclude = 'bads'\ninclude = []\n\nprint(\"########## MFT parameters:\")\nmftpar = {'prbfct': 'Gauss',\n 'prbcnt': np.array([[0.039, 0.013, 0.062], [-0.039, 0.013, 0.062]]),\n 'prbhw': np.array([[0.040, 0.040, 0.040], [0.040, 0.040, 0.040]])}\n# mftpar = {'prbfct': 'uniform',\n# 'prbcnt': None,\n# 'prbhw': None}\nmftpar.update({'iter': 2, 'currexp': 1.0})\nmftpar.update({'regtype': 'PzetaE', 'zetareg': 1.00})\n# mftpar.update({ 'regtype':'classic', 'zetareg':1.0})\nmftpar.update({'solver': 'lu', 'svrelcut': 5.e-4})\n\nprint(\"mftpar['prbcnt' ] = \", mftpar['prbcnt'])\nprint(\"mftpar['prbhw' ] = \", mftpar['prbhw'])\nprint(\"mftpar['iter' ] = \", mftpar['iter'])\nprint(\"mftpar['regtype' ] = \", mftpar['regtype'])\nprint(\"mftpar['zetareg' ] = \", mftpar['zetareg'])\nprint(\"mftpar['solver' ] = \", mftpar['solver'])\nprint(\"mftpar['svrelcut'] = \", mftpar['svrelcut'])\ncdmcut = 0.10\nprint(\"cdmcut = \", cdmcut)\n\nprint(\"########## get labels:\")\nif lblname is not None:\n labels = mne.read_labels_from_annot(subject, parc=lblname,\n subjects_dir=subjects_dir)\nelse:\n labels = None\n\nprint(\"##########################\")\nprint(\"##### Calling apply_mft()\")\nprint(\"##########################\")\niterlist = [0, 1, 2]\nfwdmag, qualmft, stc_mftl = apply_mft(fwdname, evoname, evocondition=evocondition,\n subject=subject, meg=want_meg, iterlist=iterlist,\n calccdm='all', cdmcut=cdmcut, cdmlabels=labels,\n mftpar=mftpar, verbose='verbose')\n\nevo = mne.read_evokeds(evoname, condition=evocondition, baseline=(None, 0))\ntstep = 1. / evo.info['sfreq']\n\nif iterlist == None:\n stc_mft = stc_mftl\nelse:\n stc_mft = stc_mftl[-1]\nstcdata = stc_mft.data\ntmin = stc_mft.tmin\n\nprint(\" \")\nprint(\"########## Some geo-numbers:\")\nlhinds = np.where(fwdmag['source_rr'][:, 0] <= 0.)\nrhinds = np.where(fwdmag['source_rr'][:, 0] > 0.)\nprint(\"> Discriminating lh/rh by sign of fwdmag['source_rr'][:,0]:\")\nprint(\"> lhinds[0].shape[0] = \", lhinds[0].shape[0], \" rhinds[0].shape[0] = \", rhinds[0].shape[0])\ninvmri_head_t = mne.transforms.invert_transform(fwdmag['info']['mri_head_t'])\nmrsrc = np.zeros(fwdmag['source_rr'].shape)\nmrsrc = mne.transforms.apply_trans(invmri_head_t['trans'], fwdmag['source_rr'], move=True)\nlhmrinds = np.where(mrsrc[:, 0] <= 0.)\nrhmrinds = np.where(mrsrc[:, 0] > 0.)\nprint(\"> Discriminating lh/rh by sign of fwdmag['source_rr'][:,0] in MR coords:\")\nprint(\"> lhmrinds[0].shape[0] = \", lhmrinds[0].shape[0], \" rhmrinds[0].shape[0] = \", rhmrinds[0].shape[0])\n\n# plotting routines\njumeg_mft_plot.plot_global_cdv_dist(stcdata)\njumeg_mft_plot.plot_visualize_mft_sources(fwdmag, stcdata, tmin=tmin, tstep=tstep,\n subject=subject, subjects_dir=subjects_dir)\njumeg_mft_plot.plot_cdv_distribution(fwdmag, stcdata)\njumeg_mft_plot.plot_max_amplitude_data(fwdmag, stcdata, tmin=tmin, tstep=tstep,\n subject=subject)\njumeg_mft_plot.plot_max_cdv_data(stc_mft, lhmrinds, rhmrinds)\njumeg_mft_plot.plot_cdvsum_data(stc_mft, lhmrinds, rhmrinds)\njumeg_mft_plot.plot_quality_data(qualmft, stc_mft)\njumeg_mft_plot.plot_cdm_data(qualmft, stc_mft, cdmlabels=labels)\njumeg_mft_plot.plot_jlong_labeldata(qualmft, stc_mft, labels)\njumeg_mft_plot.plot_jtotal_labeldata(qualmft, stc_mft, labels)\n\njumeg_mft_plot.plot_jlong_data(qualmft, stc_mft)\n\nprint_transforms = False\nif print_transforms:\n print(\"##### Transforms:\")\n print(\"fwdmag['info']['mri_head_t']:\")\n print(fwdmag['info']['mri_head_t'])\n invmri_head_t = mne.transforms.invert_transform(fwdmag['info']['mri_head_t'])\n print(\"Inverse of fwdmag['info']['mri_head_t']:\")\n print(invmri_head_t)\n\nwrite_tab_files = True\nif write_tab_files:\n tabfilenam = 'testtab_stc.dat'\n time_idx = np.argmax(np.max(stcdata, axis=0))\n print(\"##### Creating %s with |cdv(time_idx=%d)|\" % (tabfilenam, time_idx))\n tabfile = open(tabfilenam, mode='w')\n cdvnmax = np.max(stcdata[:, time_idx])\n n_loc = stcdata.shape[0]\n tabfile.write(\"# time_idx = %d\\n\" % time_idx)\n tabfile.write(\"# max amplitude = %11.4e\\n\" % cdvnmax)\n tabfile.write(\"# x/mm y/mm z/mm |cdv| index\\n\")\n for ipnt in range(int(n_loc / 3)):\n copnt = 1000. * fwdmag['source_rr'][ipnt]\n tabfile.write(\" %7.2f %7.2f %7.2f %11.4e %5d\\n\" % \\\n (copnt[0], copnt[1], copnt[2], stcdata[ipnt, time_idx], ipnt))\n tabfile.close()\n\nprint(\"Done.\")" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.16" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/docs/build/html/_downloads/e2fd449dc8928bab76ab22937709c2f1/plot_compute_epochs_surrogates.ipynb b/docs/build/html/_downloads/e2fd449dc8928bab76ab22937709c2f1/plot_compute_epochs_surrogates.ipynb new file mode 100644 index 00000000..9fda5e5e --- /dev/null +++ b/docs/build/html/_downloads/e2fd449dc8928bab76ab22937709c2f1/plot_compute_epochs_surrogates.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Surrogate Connectivity Generation\n\nExample to show surrogate generation on Epochs using the jumeg Surrogates\nmodule.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import os.path as op\nimport numpy as np\nimport matplotlib.pyplot as pl\nfrom mne.datasets import sample\nimport mne\n\nfrom jumeg.jumeg_surrogates import Surrogates, check_power_spectrum\n\ndata_path = sample.data_path()\nsubjects_dir = op.join(data_path, 'subjects')\n\nfname_raw = op.join(data_path, 'MEG/sample/sample_audvis_filt-0-40_raw.fif')\nfname_event = op.join(data_path, 'MEG/sample/sample_audvis_filt-0-40_raw-eve.fif')\n\nepochs_testing = False\n\nraw = mne.io.read_raw_fif(fname_raw)\nevents = mne.read_events(fname_event)\n\n# add a bad channel\nraw.info['bads'] += ['MEG 2443']\n\n# pick MEG channels\npicks = mne.pick_types(raw.info, meg='mag', eeg=False, stim=False, eog=False,\n exclude='bads')\n\n# Define epochs for left-auditory condition\nevent_id, tmin, tmax = 1, -0.2, 0.5\nepochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,\n baseline=(None, 0), reject=dict(mag=4e-12))\n\n# initialize the Surrogates object\nsurr_epochs = Surrogates(epochs)\n\nn_surr = 10 # number of surrogates\nmode = 'randomize_phase'\nmysurr = surr_epochs.compute_surrogates(n_surr=n_surr,\n mode=mode, return_generator=False)\n\n# get one epochs for plotting\n# for epochs, a generator is always returned\nfirst_surr_epoch = next(mysurr)\n\n# visualize surrogates\nfig, (ax1, ax2) = pl.subplots(2, 1)\nepochs.average().plot(axes=ax1, show=False, titles='Evoked')\nfirst_surr_epoch.average().plot(axes=ax2, show=False, titles='Surrogate Evoked')\npl.show()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.16" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/docs/build/html/_downloads/e981743ec0e46c5e364d48506d82a228/plot_circle_lines_and_blobs.py b/docs/build/html/_downloads/e981743ec0e46c5e364d48506d82a228/plot_circle_lines_and_blobs.py new file mode 100644 index 00000000..21b41448 --- /dev/null +++ b/docs/build/html/_downloads/e981743ec0e46c5e364d48506d82a228/plot_circle_lines_and_blobs.py @@ -0,0 +1,43 @@ +''' +============= +Plot centrality indices on connectivity circle plot +============= + +Script to show functionality to plot centrality indices along with +connectivity circle plot. +''' + +import os.path as op +import numpy as np +import matplotlib.pyplot as plt +import mne +from mne_connectivity import degree +from jumeg import get_jumeg_path +from jumeg.connectivity import plot_degree_circle, plot_lines_and_blobs + +import bct +import yaml + +orig_labels_fname = op.join(get_jumeg_path(), 'data/desikan_label_names.yaml') +yaml_fname = op.join(get_jumeg_path(), 'data/desikan_aparc_cortex_based_grouping.yaml') +con_fname = op.join(get_jumeg_path(), 'data/sample,aparc-con.npy') + +replacer_dict_fname = op.join(get_jumeg_path(), 'data/replacer_dictionaries.yaml') + +with open(replacer_dict_fname, 'r') as f: + replacer_dict = yaml.safe_load(f)['replacer_dict_aparc'] + +# real connectivity +con = np.load(con_fname) +con = con[0, :, :, 2] + con[0, :, :, 2].T +degrees = degree(con, threshold_prop=0.2) + +eigenvec_centrality = bct.eigenvector_centrality_und(con) + +fig, ax = plot_lines_and_blobs(con, degrees, yaml_fname, + orig_labels_fname, replacer_dict=replacer_dict, + figsize=(8, 8), show_node_labels=False, + show_group_labels=True, n_lines=100, + out_fname=None, degsize=10) +ax.set_title('Eigen vector centrality: Coh,alpha') +fig.tight_layout() diff --git a/docs/build/html/_downloads/ed7fc5f6f5d38de40666229eccab8f03/do_granger_causality.py b/docs/build/html/_downloads/ed7fc5f6f5d38de40666229eccab8f03/do_granger_causality.py new file mode 100644 index 00000000..c239677a --- /dev/null +++ b/docs/build/html/_downloads/ed7fc5f6f5d38de40666229eccab8f03/do_granger_causality.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python3 + +''' +============= +Granger Causality Analysis +============= + +Perform Granger based causality analysis using Generalized Parital Directed +Coherence on example dataset. + +Uses the data and example from mne-python combined with the Scot package +to perform the Granger Causality analysis. + +Author: Praveen Sripad +''' + +import numpy as np +from scipy import stats + +import mne +from mne.datasets import sample +from mne.minimum_norm import apply_inverse_epochs, read_inverse_operator +from jumeg.jumeg_utils import get_jumeg_path +from jumeg.connectivity.causality import (compute_order, do_mvar_evaluation, + prepare_causality_matrix) +from jumeg.connectivity import (plot_grouped_connectivity_circle, + plot_grouped_causality_circle) + +import scot +import scot.connectivity_statistics as scs +from scot.connectivity import connectivity +import yaml + +import time +t_start = time.time() + +print(('Scot version -', scot.__version__)) + +yaml_fname = get_jumeg_path() + '/data/desikan_aparc_cortex_based_grouping.yaml' +labels_fname = get_jumeg_path() + '/data/desikan_label_names.yaml' + +data_path = sample.data_path() +subjects_dir = data_path + '/subjects' +fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif' +fname_raw = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif' +fname_event = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif' + +# Load data +inverse_operator = read_inverse_operator(fname_inv) +raw = mne.io.read_raw_fif(fname_raw) +events = mne.read_events(fname_event) + +# Add a bad channel +raw.info['bads'] += ['MEG 2443'] + +# Pick MEG channels +picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=False, eog=True, + exclude='bads') + +# Define epochs for left-auditory condition +event_id, tmin, tmax = 1, -0.2, 0.5 +epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks, + baseline=(None, 0), reject=dict(mag=4e-12, grad=4000e-13, + eog=150e-6)) +if not epochs.preload: + epochs.load_data() + +# parameters, lots of parameters +snr = 1.0 +lambda2 = 1.0 / snr ** 2 +method = "MNE" # use MNE method (could also be MNE or sLORETA) +stcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, method, + pick_ori="normal", return_generator=True) + +# Get labels for FreeSurfer 'aparc' cortical parcellation with 34 labels/hemi +labels = mne.read_labels_from_annot('sample', parc='aparc', + subjects_dir=subjects_dir) +label_colors = [label.color for label in labels] + +# Average the source estimates within each label using sign-flips to reduce +# signal cancellations, also here we return a generator +src = inverse_operator['src'] +label_ts = mne.extract_label_time_course(stcs, labels, src, mode='mean_flip', + return_generator=False) +label_ts_ = np.array(label_ts) + +bands = ['alpha'] +freqs = [(8, 13)] +gcmethod = 'GPDC' +n_surr = 1 # number of surrogates +surr_thresh = 95 # percentile of surr threshold used +n_jobs = 1 +nfft = 512 + +# normalize the representative ts +print('\nperform normalization using zscoring...') +label_ts = stats.zscore(label_ts_, axis=2) + +morder = 15 # set fixed model order + +# set this to find the optimal model order using the BIC criterion +# be advised, this takes a long time !! +# morder, bic = compute_order(label_ts, m_max=100) # code provided by Qunxi +# print('the model order based on BIC is..', morder) + +# evaluate the chosen model order +print(('\nShape of label_ts -', label_ts.shape)) +# mvar needs (trials, channels, samples) +print(('\nRunning for model order - ', morder)) + +thr_cons, whit_min, whit_max = 0.8, 1., 3. +is_white, consistency, is_stable = do_mvar_evaluation(label_ts, morder, + whit_max, whit_min, + thr_cons) +print(('model_order, whiteness, consistency, stability: %d, %s, %f, %s\n' + % (morder, str(is_white), consistency, str(is_stable)))) + +# compute the Granger Partial Directed Coherence values +print('computing GPDC connectivity...') + +mvar = scot.var.VAR(morder) +# result : array, shape (`repeats`, n_channels, n_channels, nfft) +surr = scs.surrogate_connectivity(gcmethod, label_ts, mvar, nfft=nfft, + n_jobs=n_jobs, repeats=n_surr) + +mvar.fit(label_ts) +# mvar coefficients (n_channels, n_channels * model_order) +# mvar covariance matrix (n_channels, n_channels) +# result : array, shape (n_channels, n_channels, `nfft`) +cau = connectivity(gcmethod, mvar.coef, mvar.rescov, nfft=nfft) + +# get the band averaged, thresholded connectivity matrix +caus, max_cons, max_surrs = prepare_causality_matrix( + cau, surr, freqs, nfft=nfft, + sfreq=epochs.info['sfreq'], surr_thresh=surr_thresh) + +print(('Shape of causality matrix: ', caus.shape)) + +# read the label names used for plotting +# with open(labels_fname, 'r') as f: +# label_names = pickle.load(f) + +with open(labels_fname, 'r') as f: + label_names = yaml.safe_load(f)['label_names'] + +plot_grouped_causality_circle(caus[0], yaml_fname, label_names, n_lines=10, + labels_mode=None, replacer_dict=None, + out_fname='causality_sample.png', + colormap='Blues', colorbar=True, + arrowstyle='->,head_length=1,head_width=1', + figsize=(10, 6), show=False) + +t_end = time.time() +total_time_taken = t_end - t_start +print(('Total time taken in minutes: %f' % (total_time_taken / 60.))) diff --git a/docs/build/html/_downloads/ee5fcd6f3cbcdc343e5183b74955041d/plot_connectivity_between_standard_rsns.py b/docs/build/html/_downloads/ee5fcd6f3cbcdc343e5183b74955041d/plot_connectivity_between_standard_rsns.py new file mode 100644 index 00000000..9c8e22b0 --- /dev/null +++ b/docs/build/html/_downloads/ee5fcd6f3cbcdc343e5183b74955041d/plot_connectivity_between_standard_rsns.py @@ -0,0 +1,123 @@ +''' +Modified MNE-Python example script to show connectivity between standard +resting state network labels obtained from [1]. + +[1] P. Garcés, M. C. Martín-Buro, and F. Maestú, +“Quantifying the Test-Retest Reliability of Magnetoencephalography +Resting-State Functional Connectivity,” Brain Connect., vol. 6, no. 6, pp. +448–460, 2016. + +Author: Praveen sripad +''' + +import os.path as op + +import numpy as np +import matplotlib.pyplot as plt + +import mne +from mne.datasets import sample +from mne.minimum_norm import apply_inverse_epochs, read_inverse_operator +from mne.viz import circular_layout + +from mne_connectivity import spectral_connectivity_epochs +from mne_connectivity.viz import plot_connectivity_circle + +data_path = sample.data_path() +subjects_dir = op.join(data_path, 'subjects') +fname_inv = op.join(data_path, 'MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif') +fname_raw = op.join(data_path, 'MEG/sample/sample_audvis_filt-0-40_raw.fif') +fname_event = op.join(data_path, 'MEG/sample/sample_audvis_filt-0-40_raw-eve.fif') + +# Load data +inverse_operator = read_inverse_operator(fname_inv) +raw = mne.io.read_raw_fif(fname_raw) +events = mne.read_events(fname_event) + +# Add a bad channel +raw.info['bads'] += ['MEG 2443'] + +# Pick MEG channels +picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=False, eog=True, + exclude='bads') + +# Define epochs for left-auditory condition +event_id, tmin, tmax = 1, -0.2, 0.5 +epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks, + baseline=(None, 0), reject=dict(mag=4e-12, grad=4000e-13, + eog=150e-6)) +if not epochs.preload: + epochs.load_data() + +# Compute inverse solution and for each epoch. By using "return_generator=True" +# stcs will be a generator object instead of a list. +snr = 1.0 # use lower SNR for single epochs +lambda2 = 1.0 / snr ** 2 +method = "MNE" # use dSPM method (could also be MNE or sLORETA) +stcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, method, + pick_ori="normal", return_generator=True) + +# Get labels for FreeSurfer 'aparc' cortical parcellation with 34 labels/hemi +labels = mne.read_labels_from_annot('sample', parc='standard_garces_2016', + subjects_dir=subjects_dir) +labels = [lab for lab in labels if not lab.name.startswith('unknown')] +label_colors = [label.color for label in labels] + +# Average the source estimates within each label using sign-flips to reduce +# signal cancellations, also here we return a generator +src = inverse_operator['src'] +label_ts = mne.extract_label_time_course(stcs, labels, src, mode='mean_flip', + return_generator=True) + +fmin = 8. +fmax = 13. +sfreq = raw.info['sfreq'] # the sampling frequency +con_methods = ['coh', 'wpli'] +con = spectral_connectivity_epochs( + label_ts, method=con_methods, mode='multitaper', sfreq=sfreq, fmin=fmin, + fmax=fmax, faverage=True, mt_adaptive=True, n_jobs=4) + +# con is a 3D array, get the connectivity for the first (and only) freq. band +# for each method +con_res = dict() +for method, c in zip(con_methods, con): + con_res[method] = c.get_data(output='dense')[:, :, 0] + +# Now, we visualize the connectivity using a circular graph layout +# First, we reorder the labels based on their location in the left hemi +label_names = [label.name for label in labels] + +from jumeg import get_jumeg_path +yaml_fname = get_jumeg_path() + '/data/standard_garces_rsns_grouping.yaml' + +import yaml +with open(yaml_fname, 'r') as f: + xlabels = yaml.safe_load(f) + +# the yaml file has been hand curated to follow the same order as label_names +# if not the node order has to be changed appropriately +node_order = list() +node_order.extend(label_names) + +group_bound = [len(list(key.values())[0]) for key in xlabels] +group_bound = [0] + group_bound +group_boundaries = [sum(group_bound[:i+1]) for i in range(len(group_bound))] +group_boundaries.pop() + +rsn_colors = ['m', 'b', 'y', 'c', 'r', 'g', 'w'] + +group_bound.pop(0) +label_colors = [] +for ind, rep in enumerate(group_bound): + label_colors += [rsn_colors[ind]] * rep +assert len(label_colors) == len(node_order), 'Number of colours do not match' + +from mne.viz.circle import circular_layout +node_angles = circular_layout(label_names, label_names, start_pos=90, + group_boundaries=group_boundaries) + +# Plot the graph using node colors from the FreeSurfer parcellation. +plot_connectivity_circle(con_res['wpli'], label_names, n_lines=300, + node_angles=node_angles, node_colors=label_colors, + title='Connectivity between standard RSNs') +# plt.savefig('circle.png', facecolor='black') diff --git a/docs/build/html/_downloads/f9fe17957fef779faee87834a8a877fc/plot_compare_jumeg_filters.ipynb b/docs/build/html/_downloads/f9fe17957fef779faee87834a8a877fc/plot_compare_jumeg_filters.ipynb new file mode 100644 index 00000000..5c6db26d --- /dev/null +++ b/docs/build/html/_downloads/f9fe17957fef779faee87834a8a877fc/plot_compare_jumeg_filters.ipynb @@ -0,0 +1,43 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n# Filtering in jumeg.\n\nComparison of the various filters available for use in mne/jumeg.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import os.path as op\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport mne\nfrom mne.datasets import sample\n\nfrom jumeg.filter import jumeg_filter\n\ndata_path = sample.data_path()\nraw_fname = op.join(data_path, 'MEG/sample/sample_audvis_raw.fif')\n\n# load the raw data\nraw = mne.io.Raw(raw_fname, preload=True)\npicks = mne.pick_types(raw.info, meg='mag', exclude='bads')\nprint('Sampling frequency is %f' % raw.info['sfreq'])\n\n# plot the raw psd\nfig = raw.plot_psd(tmin=0.0, tmax=160., fmin=0, fmax=np.inf,\n picks=picks, ax=None, color='black', area_mode='std',\n area_alpha=0.33, n_overlap=0, dB=True, average=True,\n show=False, n_jobs=4, line_alpha=None,\n spatial_colors=None, xscale='linear', verbose='ERROR');\nfig.suptitle('Original sprectrum')\n\nl_freq, h_freq = 1., 45.\n\n# apply FIR filter\nfir_filt = raw.copy().filter(l_freq, h_freq, picks=picks, filter_length='auto',\n l_trans_bandwidth='auto', h_trans_bandwidth='auto',\n n_jobs=4, method='fir', iir_params=None, phase='zero',\n fir_window='hamming', verbose='ERROR')\n\n# apply IIR filter\nfilter_type = 'butter'\nfilt_method = 'fft'\niir_params={'ftype': filter_type, 'order': 4}\n\n# apply IIR filter\niir_filt = raw.copy().filter(l_freq, h_freq, picks=picks, filter_length='auto',\n l_trans_bandwidth='auto', h_trans_bandwidth='auto',\n n_jobs=4, method='iir', iir_params=iir_params, phase='zero',\n fir_window='hamming', verbose='ERROR')\n\n# apply the jumeg filter using mne\nfilt_ju_mne = jumeg_filter(filter_method='mne', filter_type='bp', fcut1=l_freq, fcut2=h_freq,\n remove_dcoffset=True, sampling_frequency=raw.info['sfreq'],\n filter_window='hamming', notch=np.array([50., 60.]),\n notch_width=1.0, order=4, njobs=4,\n mne_filter_method='fft',mne_filter_length='10s',\n trans_bandwith=0.5)\nju_mne_filt = raw.copy() # make a copy\nju_mne_filt._data = filt_ju_mne.apply_filter(ju_mne_filt._data, picks)\n\n# apply the jumeg filter using bw\nfilt_ju_bw = jumeg_filter(filter_method='bw', filter_type='bp', fcut1=l_freq, fcut2=h_freq,\n remove_dcoffset=True, sampling_frequency=raw.info['sfreq'],\n filter_window='hamming', notch=np.array([50., 60.]),\n notch_width=1.0, order=4, njobs=4,\n mne_filter_method='fft',mne_filter_length='10s',\n trans_bandwith=0.5)\nfilt_ju_bw.verbose = False\nju_bw_filt = raw.copy() # make a copy\nfilt_ju_bw.apply_filter(ju_bw_filt._data, picks)\n\nfig, (ax1, ax2) = plt.subplots(1, 2)\n\n# plot the jumeg MNE and jumeg Butterworth filtered raw psds\nju_mne_filt.plot_psd(tmin=0.0, tmax=160., fmin=0, fmax=70., n_fft=None,\n picks=picks, ax=ax1, color='blue', area_mode='std',\n area_alpha=0.33, n_overlap=0, dB=True, average=True,\n show=False, n_jobs=4, line_alpha=None,\n spatial_colors=None, xscale='linear', verbose=None);\n\nju_bw_filt.plot_psd(tmin=0.0, tmax=160., fmin=0, fmax=70., n_fft=None,\n picks=picks, ax=ax1, color='green', area_mode='std',\n area_alpha=0.33, n_overlap=0, dB=True, average=True,\n show=False, n_jobs=4, line_alpha=None,\n spatial_colors=None, xscale='linear', verbose=None);\n\nax1.set_xlim(0., 75.);\nax1.set_title('jumeg MNE (blue)/jumeg BW (green)');\n\n# plot the MNE FIR and IIR filterered raw psds\nfir_filt.plot_psd(tmin=0.0, tmax=160., fmin=0, fmax=70., n_fft=None,\n picks=picks, ax=ax2, color='red', area_mode='std',\n area_alpha=0.33, n_overlap=0, dB=True, average=True,\n show=False, n_jobs=4, line_alpha=None,\n spatial_colors=None, xscale='linear', verbose='ERROR');\n\niir_filt.plot_psd(tmin=0.0, tmax=160., fmin=0., fmax=70., n_fft=None,\n picks=picks, ax=ax2, color='yellow', area_mode='std',\n area_alpha=0.33, n_overlap=0, dB=True, average=True,\n show=False, n_jobs=4, line_alpha=None,\n spatial_colors=None, xscale='linear', verbose='ERROR');\nax2.set_xlim(0., 75.);\nax2.set_title('MNE FIR (red)/ MNE IIR (yellow)');\n\nfig.tight_layout()\nplt.show()\n\n# Recommendation: Presently, it is best to use the MNE FIR filter for our\n# filtering requirements. The jumeg filter module (which wraps around mne\n# filter) may be used when the MNE band_pass_filter needs to be combined with\n# the notch_filter. In cases where the notch frequencies are removed using the\n# noise reducer, the mne FIR filter can be directly used." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.16" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file diff --git a/docs/build/html/_images/sphx_glr_do_MLICA_thumb.png b/docs/build/html/_images/sphx_glr_do_MLICA_thumb.png new file mode 100644 index 00000000..8a5fed58 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_do_MLICA_thumb.png differ diff --git a/docs/build/html/_images/sphx_glr_do_compare_ica_methods_thumb.png b/docs/build/html/_images/sphx_glr_do_compare_ica_methods_thumb.png new file mode 100644 index 00000000..8a5fed58 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_do_compare_ica_methods_thumb.png differ diff --git a/docs/build/html/_images/sphx_glr_do_granger_causality_thumb.png b/docs/build/html/_images/sphx_glr_do_granger_causality_thumb.png new file mode 100644 index 00000000..8a5fed58 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_do_granger_causality_thumb.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_annot_standard_rsns_001.png b/docs/build/html/_images/sphx_glr_plot_annot_standard_rsns_001.png new file mode 100644 index 00000000..a59bc8a9 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_annot_standard_rsns_001.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_annot_standard_rsns_thumb.png b/docs/build/html/_images/sphx_glr_plot_annot_standard_rsns_thumb.png new file mode 100644 index 00000000..ed507039 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_annot_standard_rsns_thumb.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_brain_connectome_001.png b/docs/build/html/_images/sphx_glr_plot_brain_connectome_001.png new file mode 100644 index 00000000..3eaa9612 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_brain_connectome_001.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_brain_connectome_thumb.png b/docs/build/html/_images/sphx_glr_plot_brain_connectome_thumb.png new file mode 100644 index 00000000..83224ca0 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_brain_connectome_thumb.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_causality_circle_001.png b/docs/build/html/_images/sphx_glr_plot_causality_circle_001.png new file mode 100644 index 00000000..3ae8e9cc Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_causality_circle_001.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_causality_circle_thumb.png b/docs/build/html/_images/sphx_glr_plot_causality_circle_thumb.png new file mode 100644 index 00000000..567f478d Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_causality_circle_thumb.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_circle_lines_and_blobs_001.png b/docs/build/html/_images/sphx_glr_plot_circle_lines_and_blobs_001.png new file mode 100644 index 00000000..cd899025 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_circle_lines_and_blobs_001.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_circle_lines_and_blobs_thumb.png b/docs/build/html/_images/sphx_glr_plot_circle_lines_and_blobs_thumb.png new file mode 100644 index 00000000..6c96e92c Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_circle_lines_and_blobs_thumb.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_communities_001.png b/docs/build/html/_images/sphx_glr_plot_communities_001.png new file mode 100644 index 00000000..2a53bf78 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_communities_001.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_communities_thumb.png b/docs/build/html/_images/sphx_glr_plot_communities_thumb.png new file mode 100644 index 00000000..54140b82 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_communities_thumb.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_compare_jumeg_filters_001.png b/docs/build/html/_images/sphx_glr_plot_compare_jumeg_filters_001.png new file mode 100644 index 00000000..121f080d Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_compare_jumeg_filters_001.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_compare_jumeg_filters_002.png b/docs/build/html/_images/sphx_glr_plot_compare_jumeg_filters_002.png new file mode 100644 index 00000000..41a4ed9d Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_compare_jumeg_filters_002.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_compare_jumeg_filters_thumb.png b/docs/build/html/_images/sphx_glr_plot_compare_jumeg_filters_thumb.png new file mode 100644 index 00000000..e706757b Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_compare_jumeg_filters_thumb.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_compute_epochs_surrogates_001.png b/docs/build/html/_images/sphx_glr_plot_compute_epochs_surrogates_001.png new file mode 100644 index 00000000..43c9dbf8 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_compute_epochs_surrogates_001.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_compute_epochs_surrogates_thumb.png b/docs/build/html/_images/sphx_glr_plot_compute_epochs_surrogates_thumb.png new file mode 100644 index 00000000..e3ce0e3e Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_compute_epochs_surrogates_thumb.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_compute_label_distances_001.png b/docs/build/html/_images/sphx_glr_plot_compute_label_distances_001.png new file mode 100644 index 00000000..6e2351bd Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_compute_label_distances_001.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_compute_label_distances_thumb.png b/docs/build/html/_images/sphx_glr_plot_compute_label_distances_thumb.png new file mode 100644 index 00000000..babf7b8b Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_compute_label_distances_thumb.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_connectivity_between_standard_rsns_001.png b/docs/build/html/_images/sphx_glr_plot_connectivity_between_standard_rsns_001.png new file mode 100644 index 00000000..e3f72564 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_connectivity_between_standard_rsns_001.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_connectivity_between_standard_rsns_thumb.png b/docs/build/html/_images/sphx_glr_plot_connectivity_between_standard_rsns_thumb.png new file mode 100644 index 00000000..d43716fc Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_connectivity_between_standard_rsns_thumb.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_custom_grouped_connectivity_circle_001.png b/docs/build/html/_images/sphx_glr_plot_custom_grouped_connectivity_circle_001.png new file mode 100644 index 00000000..66f6119e Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_custom_grouped_connectivity_circle_001.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_custom_grouped_connectivity_circle_thumb.png b/docs/build/html/_images/sphx_glr_plot_custom_grouped_connectivity_circle_thumb.png new file mode 100644 index 00000000..944b446d Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_custom_grouped_connectivity_circle_thumb.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_data_distribution_001.png b/docs/build/html/_images/sphx_glr_plot_data_distribution_001.png new file mode 100644 index 00000000..24c7088a Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_data_distribution_001.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_data_distribution_thumb.png b/docs/build/html/_images/sphx_glr_plot_data_distribution_thumb.png new file mode 100644 index 00000000..61a19b08 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_data_distribution_thumb.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_degree_circle_001.png b/docs/build/html/_images/sphx_glr_plot_degree_circle_001.png new file mode 100644 index 00000000..bc59026a Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_degree_circle_001.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_degree_circle_thumb.png b/docs/build/html/_images/sphx_glr_plot_degree_circle_thumb.png new file mode 100644 index 00000000..f5894eab Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_degree_circle_thumb.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_destriux_atlas_based_connectivity_001.png b/docs/build/html/_images/sphx_glr_plot_destriux_atlas_based_connectivity_001.png new file mode 100644 index 00000000..99350861 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_destriux_atlas_based_connectivity_001.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_destriux_atlas_based_connectivity_thumb.png b/docs/build/html/_images/sphx_glr_plot_destriux_atlas_based_connectivity_thumb.png new file mode 100644 index 00000000..1390a15e Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_destriux_atlas_based_connectivity_thumb.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_generate_surrogate_connectivity_thumb.png b/docs/build/html/_images/sphx_glr_plot_generate_surrogate_connectivity_thumb.png new file mode 100644 index 00000000..8a5fed58 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_generate_surrogate_connectivity_thumb.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_generate_surrogate_stcs_001.png b/docs/build/html/_images/sphx_glr_plot_generate_surrogate_stcs_001.png new file mode 100644 index 00000000..d1b0c50f Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_generate_surrogate_stcs_001.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_generate_surrogate_stcs_thumb.png b/docs/build/html/_images/sphx_glr_plot_generate_surrogate_stcs_thumb.png new file mode 100644 index 00000000..478a9fa2 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_generate_surrogate_stcs_thumb.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_generic_grouped_connectivity_circle_001.png b/docs/build/html/_images/sphx_glr_plot_generic_grouped_connectivity_circle_001.png new file mode 100644 index 00000000..a0e1987a Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_generic_grouped_connectivity_circle_001.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_generic_grouped_connectivity_circle_002.png b/docs/build/html/_images/sphx_glr_plot_generic_grouped_connectivity_circle_002.png new file mode 100644 index 00000000..bbb03c7e Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_generic_grouped_connectivity_circle_002.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_generic_grouped_connectivity_circle_thumb.png b/docs/build/html/_images/sphx_glr_plot_generic_grouped_connectivity_circle_thumb.png new file mode 100644 index 00000000..d16df231 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_generic_grouped_connectivity_circle_thumb.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_grouped_connectivity_circle_001.png b/docs/build/html/_images/sphx_glr_plot_grouped_connectivity_circle_001.png new file mode 100644 index 00000000..44fad28f Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_grouped_connectivity_circle_001.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_grouped_connectivity_circle_002.png b/docs/build/html/_images/sphx_glr_plot_grouped_connectivity_circle_002.png new file mode 100644 index 00000000..4c2d38a0 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_grouped_connectivity_circle_002.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_grouped_connectivity_circle_thumb.png b/docs/build/html/_images/sphx_glr_plot_grouped_connectivity_circle_thumb.png new file mode 100644 index 00000000..232c74ca Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_grouped_connectivity_circle_thumb.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_inter_and_intra_lobe_causality_thumb.png b/docs/build/html/_images/sphx_glr_plot_inter_and_intra_lobe_causality_thumb.png new file mode 100644 index 00000000..8a5fed58 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_inter_and_intra_lobe_causality_thumb.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_interpolate_bads_thumb.png b/docs/build/html/_images/sphx_glr_plot_interpolate_bads_thumb.png new file mode 100644 index 00000000..8a5fed58 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_interpolate_bads_thumb.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_label_distances_001.png b/docs/build/html/_images/sphx_glr_plot_label_distances_001.png new file mode 100644 index 00000000..2ea342aa Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_label_distances_001.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_label_distances_002.png b/docs/build/html/_images/sphx_glr_plot_label_distances_002.png new file mode 100644 index 00000000..2e713241 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_label_distances_002.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_label_distances_thumb.png b/docs/build/html/_images/sphx_glr_plot_label_distances_thumb.png new file mode 100644 index 00000000..29f5a01e Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_label_distances_thumb.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_labelled_connectivity_circle_001.png b/docs/build/html/_images/sphx_glr_plot_labelled_connectivity_circle_001.png new file mode 100644 index 00000000..d5bbdf65 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_labelled_connectivity_circle_001.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_labelled_connectivity_circle_thumb.png b/docs/build/html/_images/sphx_glr_plot_labelled_connectivity_circle_thumb.png new file mode 100644 index 00000000..025d867c Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_labelled_connectivity_circle_thumb.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_noise_reducer_001.png b/docs/build/html/_images/sphx_glr_plot_noise_reducer_001.png new file mode 100644 index 00000000..92c36a0b Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_noise_reducer_001.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_noise_reducer_thumb.png b/docs/build/html/_images/sphx_glr_plot_noise_reducer_thumb.png new file mode 100644 index 00000000..2f29be37 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_noise_reducer_thumb.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_perform_mft_surface_list_thumb.png b/docs/build/html/_images/sphx_glr_plot_perform_mft_surface_list_thumb.png new file mode 100644 index 00000000..8a5fed58 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_perform_mft_surface_list_thumb.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_perform_mft_surface_thumb.png b/docs/build/html/_images/sphx_glr_plot_perform_mft_surface_thumb.png new file mode 100644 index 00000000..8a5fed58 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_perform_mft_surface_thumb.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_perform_mft_volume_thumb.png b/docs/build/html/_images/sphx_glr_plot_perform_mft_volume_thumb.png new file mode 100644 index 00000000..8a5fed58 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_perform_mft_volume_thumb.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_rank_estimation_001.png b/docs/build/html/_images/sphx_glr_plot_rank_estimation_001.png new file mode 100644 index 00000000..849af377 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_rank_estimation_001.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_rank_estimation_thumb.png b/docs/build/html/_images/sphx_glr_plot_rank_estimation_thumb.png new file mode 100644 index 00000000..7ae455c3 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_rank_estimation_thumb.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_shuffle_time_slices_001.png b/docs/build/html/_images/sphx_glr_plot_shuffle_time_slices_001.png new file mode 100644 index 00000000..930c510a Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_shuffle_time_slices_001.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_shuffle_time_slices_002.png b/docs/build/html/_images/sphx_glr_plot_shuffle_time_slices_002.png new file mode 100644 index 00000000..27e189e2 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_shuffle_time_slices_002.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_shuffle_time_slices_003.png b/docs/build/html/_images/sphx_glr_plot_shuffle_time_slices_003.png new file mode 100644 index 00000000..b9eace78 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_shuffle_time_slices_003.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_shuffle_time_slices_004.png b/docs/build/html/_images/sphx_glr_plot_shuffle_time_slices_004.png new file mode 100644 index 00000000..8d15fcd4 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_shuffle_time_slices_004.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_shuffle_time_slices_005.png b/docs/build/html/_images/sphx_glr_plot_shuffle_time_slices_005.png new file mode 100644 index 00000000..26897c64 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_shuffle_time_slices_005.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_shuffle_time_slices_006.png b/docs/build/html/_images/sphx_glr_plot_shuffle_time_slices_006.png new file mode 100644 index 00000000..26897c64 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_shuffle_time_slices_006.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_shuffle_time_slices_thumb.png b/docs/build/html/_images/sphx_glr_plot_shuffle_time_slices_thumb.png new file mode 100644 index 00000000..00ef2658 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_shuffle_time_slices_thumb.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_simulated_connectivity_001.png b/docs/build/html/_images/sphx_glr_plot_simulated_connectivity_001.png new file mode 100644 index 00000000..8e3463bc Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_simulated_connectivity_001.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_simulated_connectivity_thumb.png b/docs/build/html/_images/sphx_glr_plot_simulated_connectivity_thumb.png new file mode 100644 index 00000000..b0f01002 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_simulated_connectivity_thumb.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_standard_resting_network_on_aparc_annot_map_001.png b/docs/build/html/_images/sphx_glr_plot_standard_resting_network_on_aparc_annot_map_001.png new file mode 100644 index 00000000..9432c6cb Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_standard_resting_network_on_aparc_annot_map_001.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_standard_resting_network_on_aparc_annot_map_thumb.png b/docs/build/html/_images/sphx_glr_plot_standard_resting_network_on_aparc_annot_map_thumb.png new file mode 100644 index 00000000..b3a901b9 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_standard_resting_network_on_aparc_annot_map_thumb.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_suggest_bads_thumb.png b/docs/build/html/_images/sphx_glr_plot_suggest_bads_thumb.png new file mode 100644 index 00000000..8a5fed58 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_suggest_bads_thumb.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_surrogate_methods_001.png b/docs/build/html/_images/sphx_glr_plot_surrogate_methods_001.png new file mode 100644 index 00000000..acfcb56c Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_surrogate_methods_001.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_surrogate_methods_002.png b/docs/build/html/_images/sphx_glr_plot_surrogate_methods_002.png new file mode 100644 index 00000000..41c3a389 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_surrogate_methods_002.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_surrogate_methods_003.png b/docs/build/html/_images/sphx_glr_plot_surrogate_methods_003.png new file mode 100644 index 00000000..18e70de1 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_surrogate_methods_003.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_surrogate_methods_004.png b/docs/build/html/_images/sphx_glr_plot_surrogate_methods_004.png new file mode 100644 index 00000000..875c13fc Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_surrogate_methods_004.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_surrogate_methods_thumb.png b/docs/build/html/_images/sphx_glr_plot_surrogate_methods_thumb.png new file mode 100644 index 00000000..5827a9f9 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_surrogate_methods_thumb.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_test_transform_mni_to_ras_thumb.png b/docs/build/html/_images/sphx_glr_plot_test_transform_mni_to_ras_thumb.png new file mode 100644 index 00000000..8a5fed58 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_test_transform_mni_to_ras_thumb.png differ diff --git a/docs/build/html/_images/sphx_glr_plot_vertices_around_seed_thumb.png b/docs/build/html/_images/sphx_glr_plot_vertices_around_seed_thumb.png new file mode 100644 index 00000000..8a5fed58 Binary files /dev/null and b/docs/build/html/_images/sphx_glr_plot_vertices_around_seed_thumb.png differ diff --git a/docs/build/html/_sources/api.rst.txt b/docs/build/html/_sources/api.rst.txt new file mode 100644 index 00000000..f30fcc83 --- /dev/null +++ b/docs/build/html/_sources/api.rst.txt @@ -0,0 +1,49 @@ +.. _api_documentation: + +================= +API Documentation +================= + +.. currentmodule:: jumeg + +Connectivity +============ + +Functions + +.. currentmodule:: jumeg.connectivity + +.. autosummary:: + :toctree: generated/ + :nosignatures: + + find_distances_matrix + weighted_con_matrix + get_label_distances + make_annot_from_csv + + sensor_connectivity_3d + plot_grouped_connectivity_circle + plot_generic_grouped_circle + plot_grouped_causality_circle + plot_degree_circle + plot_lines_and_blobs + plot_labelled_group_connectivity_circle + plot_fica_grouped_circle + +.. currentmodule:: jumeg.connectivity.causality + +.. autosummary:: + :toctree: generated/ + :nosignatures: + + dw_whiteness + consistency + do_mvar_evaluation + check_whiteness_and_consistency + check_model_order + prepare_causality_matrix + make_frequency_bands + compute_order_extended + compute_order + compute_causal_outflow_inflow diff --git a/docs/build/html/_sources/auto_examples/causality/do_granger_causality.rst.txt b/docs/build/html/_sources/auto_examples/causality/do_granger_causality.rst.txt new file mode 100644 index 00000000..9f841426 --- /dev/null +++ b/docs/build/html/_sources/auto_examples/causality/do_granger_causality.rst.txt @@ -0,0 +1,206 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "auto_examples/causality/do_granger_causality.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_auto_examples_causality_do_granger_causality.py: + + +============= +Granger Causality Analysis +============= + +Perform Granger based causality analysis using Generalized Parital Directed +Coherence on example dataset. + +Uses the data and example from mne-python combined with the Scot package +to perform the Granger Causality analysis. + +Author: Praveen Sripad + +.. GENERATED FROM PYTHON SOURCE LINES 16-156 + +.. code-block:: default + + + import numpy as np + from scipy import stats + + import mne + from mne.datasets import sample + from mne.minimum_norm import apply_inverse_epochs, read_inverse_operator + from jumeg.jumeg_utils import get_jumeg_path + from jumeg.connectivity.causality import (compute_order, do_mvar_evaluation, + prepare_causality_matrix) + from jumeg.connectivity import (plot_grouped_connectivity_circle, + plot_grouped_causality_circle) + + import scot + import scot.connectivity_statistics as scs + from scot.connectivity import connectivity + import yaml + + import time + t_start = time.time() + + print(('Scot version -', scot.__version__)) + + yaml_fname = get_jumeg_path() + '/data/desikan_aparc_cortex_based_grouping.yaml' + labels_fname = get_jumeg_path() + '/data/desikan_label_names.yaml' + + data_path = sample.data_path() + subjects_dir = data_path + '/subjects' + fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif' + fname_raw = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif' + fname_event = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif' + + # Load data + inverse_operator = read_inverse_operator(fname_inv) + raw = mne.io.read_raw_fif(fname_raw) + events = mne.read_events(fname_event) + + # Add a bad channel + raw.info['bads'] += ['MEG 2443'] + + # Pick MEG channels + picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=False, eog=True, + exclude='bads') + + # Define epochs for left-auditory condition + event_id, tmin, tmax = 1, -0.2, 0.5 + epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks, + baseline=(None, 0), reject=dict(mag=4e-12, grad=4000e-13, + eog=150e-6)) + if not epochs.preload: + epochs.load_data() + + # parameters, lots of parameters + snr = 1.0 + lambda2 = 1.0 / snr ** 2 + method = "MNE" # use MNE method (could also be MNE or sLORETA) + stcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, method, + pick_ori="normal", return_generator=True) + + # Get labels for FreeSurfer 'aparc' cortical parcellation with 34 labels/hemi + labels = mne.read_labels_from_annot('sample', parc='aparc', + subjects_dir=subjects_dir) + label_colors = [label.color for label in labels] + + # Average the source estimates within each label using sign-flips to reduce + # signal cancellations, also here we return a generator + src = inverse_operator['src'] + label_ts = mne.extract_label_time_course(stcs, labels, src, mode='mean_flip', + return_generator=False) + label_ts_ = np.array(label_ts) + + bands = ['alpha'] + freqs = [(8, 13)] + gcmethod = 'GPDC' + n_surr = 1 # number of surrogates + surr_thresh = 95 # percentile of surr threshold used + n_jobs = 1 + nfft = 512 + + # normalize the representative ts + print('\nperform normalization using zscoring...') + label_ts = stats.zscore(label_ts_, axis=2) + + morder = 15 # set fixed model order + + # set this to find the optimal model order using the BIC criterion + # be advised, this takes a long time !! + # morder, bic = compute_order(label_ts, m_max=100) # code provided by Qunxi + # print('the model order based on BIC is..', morder) + + # evaluate the chosen model order + print(('\nShape of label_ts -', label_ts.shape)) + # mvar needs (trials, channels, samples) + print(('\nRunning for model order - ', morder)) + + thr_cons, whit_min, whit_max = 0.8, 1., 3. + is_white, consistency, is_stable = do_mvar_evaluation(label_ts, morder, + whit_max, whit_min, + thr_cons) + print(('model_order, whiteness, consistency, stability: %d, %s, %f, %s\n' + % (morder, str(is_white), consistency, str(is_stable)))) + + # compute the Granger Partial Directed Coherence values + print('computing GPDC connectivity...') + + mvar = scot.var.VAR(morder) + # result : array, shape (`repeats`, n_channels, n_channels, nfft) + surr = scs.surrogate_connectivity(gcmethod, label_ts, mvar, nfft=nfft, + n_jobs=n_jobs, repeats=n_surr) + + mvar.fit(label_ts) + # mvar coefficients (n_channels, n_channels * model_order) + # mvar covariance matrix (n_channels, n_channels) + # result : array, shape (n_channels, n_channels, `nfft`) + cau = connectivity(gcmethod, mvar.coef, mvar.rescov, nfft=nfft) + + # get the band averaged, thresholded connectivity matrix + caus, max_cons, max_surrs = prepare_causality_matrix( + cau, surr, freqs, nfft=nfft, + sfreq=epochs.info['sfreq'], surr_thresh=surr_thresh) + + print(('Shape of causality matrix: ', caus.shape)) + + # read the label names used for plotting + # with open(labels_fname, 'r') as f: + # label_names = pickle.load(f) + + with open(labels_fname, 'r') as f: + label_names = yaml.safe_load(f)['label_names'] + + plot_grouped_causality_circle(caus[0], yaml_fname, label_names, n_lines=10, + labels_mode=None, replacer_dict=None, + out_fname='causality_sample.png', + colormap='Blues', colorbar=True, + arrowstyle='->,head_length=1,head_width=1', + figsize=(10, 6), show=False) + + t_end = time.time() + total_time_taken = t_end - t_start + print(('Total time taken in minutes: %f' % (total_time_taken / 60.))) + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** ( 0 minutes 0.000 seconds) + + +.. _sphx_glr_download_auto_examples_causality_do_granger_causality.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + + + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: do_granger_causality.py ` + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: do_granger_causality.ipynb ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/build/html/_sources/auto_examples/causality/index.rst.txt b/docs/build/html/_sources/auto_examples/causality/index.rst.txt new file mode 100644 index 00000000..7db3e4b8 --- /dev/null +++ b/docs/build/html/_sources/auto_examples/causality/index.rst.txt @@ -0,0 +1,76 @@ + + +.. _sphx_glr_auto_examples_causality: + +Causality analysis. + + + +.. raw:: html + +
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /auto_examples/causality/images/thumb/sphx_glr_plot_causality_circle_thumb.png + :alt: + + :ref:`sphx_glr_auto_examples_causality_plot_causality_circle.py` + +.. raw:: html + +
Plot Causality Matrix
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /auto_examples/causality/images/thumb/sphx_glr_plot_inter_and_intra_lobe_causality_thumb.png + :alt: + + :ref:`sphx_glr_auto_examples_causality_plot_inter_and_intra_lobe_causality.py` + +.. raw:: html + +
Group Causality Matrix
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /auto_examples/causality/images/thumb/sphx_glr_do_granger_causality_thumb.png + :alt: + + :ref:`sphx_glr_auto_examples_causality_do_granger_causality.py` + +.. raw:: html + +
Granger Causality Analysis
+
+ + +.. raw:: html + +
+ + +.. toctree:: + :hidden: + + /auto_examples/causality/plot_causality_circle + /auto_examples/causality/plot_inter_and_intra_lobe_causality + /auto_examples/causality/do_granger_causality + diff --git a/docs/build/html/_sources/auto_examples/causality/plot_causality_circle.rst.txt b/docs/build/html/_sources/auto_examples/causality/plot_causality_circle.rst.txt new file mode 100644 index 00000000..80d48c20 --- /dev/null +++ b/docs/build/html/_sources/auto_examples/causality/plot_causality_circle.rst.txt @@ -0,0 +1,111 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "auto_examples/causality/plot_causality_circle.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_auto_examples_causality_plot_causality_circle.py: + + +============= +Plot Causality Matrix +============= + +Example showing how to plot a causality matrix on a circle plot. + +.. GENERATED FROM PYTHON SOURCE LINES 10-40 + + + +.. image-sg:: /auto_examples/causality/images/sphx_glr_plot_causality_circle_001.png + :alt: Causal Metric + :srcset: /auto_examples/causality/images/sphx_glr_plot_causality_circle_001.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + +
+ + + + + +| + +.. code-block:: default + + + import numpy as np + + from jumeg import get_jumeg_path + from jumeg.connectivity import plot_grouped_causality_circle + import yaml + + # load the yaml grouping of Freesurfer labels + yaml_fname = get_jumeg_path() + '/data/desikan_aparc_cortex_based_grouping.yaml' + labels_fname = get_jumeg_path() + '/data/desikan_label_names.yaml' + replacer_dict_fname = get_jumeg_path() + '/data/replacer_dictionaries.yaml' + + with open(labels_fname, 'r') as f: + label_names = yaml.safe_load(f)['label_names'] + + with open(replacer_dict_fname, 'r') as f: + replacer_dict = yaml.safe_load(f)['replacer_dict_aparc'] + + # make a random causality matrix + n_nodes = 68 # currently needs to be always this number + caus = np.random.random((n_nodes, n_nodes)) + caus[np.diag_indices_from(caus)] = 0. + caus[caus < 0.7] = 0. + + plot_grouped_causality_circle(caus, yaml_fname, label_names, n_lines=10, + labels_mode='replace', replacer_dict=replacer_dict, + out_fname='fig_causality_circle.png', + colormap='Blues', colorbar=True, + figsize=(6, 6), show=False, + arrowstyle='->,head_length=1,head_width=1') + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** ( 0 minutes 0.645 seconds) + + +.. _sphx_glr_download_auto_examples_causality_plot_causality_circle.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + + + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_causality_circle.py ` + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_causality_circle.ipynb ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/build/html/_sources/auto_examples/causality/plot_inter_and_intra_lobe_causality.rst.txt b/docs/build/html/_sources/auto_examples/causality/plot_inter_and_intra_lobe_causality.rst.txt new file mode 100644 index 00000000..1637e36b --- /dev/null +++ b/docs/build/html/_sources/auto_examples/causality/plot_inter_and_intra_lobe_causality.rst.txt @@ -0,0 +1,205 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "auto_examples/causality/plot_inter_and_intra_lobe_causality.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_auto_examples_causality_plot_inter_and_intra_lobe_causality.py: + + +============= +Group Causality Matrix +============= + +Group a causality matrix by lobes and plot the resulting +inter- and intra-lobe causality. + +Author: Christian Kiefer + +.. GENERATED FROM PYTHON SOURCE LINES 11-29 + +.. code-block:: default + + + import os + import os.path as op + + import numpy as np + import matplotlib.pyplot as plt + import mne + + from mne.datasets import sample + + print(__doc__) + + data_path = sample.data_path() + + from jumeg.connectivity.con_utils import group_con_matrix_by_lobe + from jumeg.connectivity.con_viz import plot_grouped_causality_circle + from jumeg.jumeg_utils import get_jumeg_path + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 30-32 + +Load the grouping files +############################################################################## + +.. GENERATED FROM PYTHON SOURCE LINES 32-38 + +.. code-block:: default + + + grouping_yaml_fname = op.join(get_jumeg_path(), 'data', + 'desikan_aparc_cortex_based_grouping_ck.yaml') + lobe_grouping_yaml_fname = op.join(get_jumeg_path(), 'data', + 'lobes_grouping.yaml') + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 39-41 + +Load anatomical labels +############################################################################## + +.. GENERATED FROM PYTHON SOURCE LINES 41-50 + +.. code-block:: default + + + subjects_dir = op.join(data_path, 'subjects') + os.environ['SUBJECTS_DIR'] = subjects_dir + + full_labels = mne.read_labels_from_annot(subject='fsaverage', parc='aparc', + hemi='both', subjects_dir=subjects_dir) + + full_label_names = [full_label.name for full_label in full_labels if full_label.name.find('unknown') == -1] + + + + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + Reading labels from parcellation... + read 35 labels from /Users/praveen.sripad/nanna_data/mne_data/MNE-sample-data/subjects/fsaverage/label/lh.aparc.annot + read 34 labels from /Users/praveen.sripad/nanna_data/mne_data/MNE-sample-data/subjects/fsaverage/label/rh.aparc.annot + + + + +.. GENERATED FROM PYTHON SOURCE LINES 51-53 + +create random causality matrix +############################################################################## + +.. GENERATED FROM PYTHON SOURCE LINES 53-64 + +.. code-block:: default + + + # create causality matrix + np.random.seed(42) + cau = np.random.uniform(-0.99, 0.01, (len(full_label_names), len(full_label_names))) + + cau[cau < 0] = 0 + cau = cau / 0.01 # values between 0 and 1 + + cau_grp, grp_label_names = group_con_matrix_by_lobe(con=cau, label_names=full_label_names, + grouping_yaml_fname=grouping_yaml_fname) + + + + + + + + +.. GENERATED FROM PYTHON SOURCE LINES 65-67 + +Compare original matrix with grouped matrix plot +############################################################################## + +.. GENERATED FROM PYTHON SOURCE LINES 67-87 + +.. code-block:: default + + + fig = plot_grouped_causality_circle(cau, grouping_yaml_fname, full_label_names, + title='original causality matrix', n_lines=None, + labels_mode=None, replacer_dict=None, out_fname=None, + colormap='magma_r', colorbar=True, colorbar_pos=(-0.25, 0.05), + arrowstyle='->,head_length=0.7,head_width=0.4', + figsize=(9.1, 6), vmin=0., vmax=1.0, ignore_diagonal=True, + show=True) + + plt.close(fig) + + fig = plot_grouped_causality_circle(cau_grp, lobe_grouping_yaml_fname, grp_label_names, + title='test', n_lines=None, labels_mode=None, + replacer_dict=None, out_fname=None, colormap='magma_r', + colorbar=True, colorbar_pos=(-0.25, 0.05), + arrowstyle='->,head_length=0.7,head_width=0.4', + figsize=(9.1, 6), vmin=0., ignore_diagonal=False, + show=True) + + plt.close(fig) + + + + + + + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** ( 0 minutes 0.211 seconds) + + +.. _sphx_glr_download_auto_examples_causality_plot_inter_and_intra_lobe_causality.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + + + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_inter_and_intra_lobe_causality.py ` + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_inter_and_intra_lobe_causality.ipynb ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/build/html/_sources/auto_examples/causality/sg_execution_times.rst.txt b/docs/build/html/_sources/auto_examples/causality/sg_execution_times.rst.txt new file mode 100644 index 00000000..f68b30fd --- /dev/null +++ b/docs/build/html/_sources/auto_examples/causality/sg_execution_times.rst.txt @@ -0,0 +1,17 @@ + +:orphan: + +.. _sphx_glr_auto_examples_causality_sg_execution_times: + + +Computation times +================= +**00:00.856** total execution time for **auto_examples_causality** files: + ++-----------------------------------------------------------------------------------------------------------------------------+-----------+--------+ +| :ref:`sphx_glr_auto_examples_causality_plot_causality_circle.py` (``plot_causality_circle.py``) | 00:00.645 | 0.0 MB | ++-----------------------------------------------------------------------------------------------------------------------------+-----------+--------+ +| :ref:`sphx_glr_auto_examples_causality_plot_inter_and_intra_lobe_causality.py` (``plot_inter_and_intra_lobe_causality.py``) | 00:00.211 | 0.0 MB | ++-----------------------------------------------------------------------------------------------------------------------------+-----------+--------+ +| :ref:`sphx_glr_auto_examples_causality_do_granger_causality.py` (``do_granger_causality.py``) | 00:00.000 | 0.0 MB | ++-----------------------------------------------------------------------------------------------------------------------------+-----------+--------+ diff --git a/docs/build/html/_sources/auto_examples/connectivity/index.rst.txt b/docs/build/html/_sources/auto_examples/connectivity/index.rst.txt new file mode 100644 index 00000000..1638fd99 --- /dev/null +++ b/docs/build/html/_sources/auto_examples/connectivity/index.rst.txt @@ -0,0 +1,418 @@ + + +.. _sphx_glr_auto_examples_connectivity: + +Connectivity analysis. + + + +.. raw:: html + +
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /auto_examples/connectivity/images/thumb/sphx_glr_plot_degree_circle_thumb.png + :alt: + + :ref:`sphx_glr_auto_examples_connectivity_plot_degree_circle.py` + +.. raw:: html + +
Plot degree circle
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /auto_examples/connectivity/images/thumb/sphx_glr_plot_vertices_around_seed_thumb.png + :alt: + + :ref:`sphx_glr_auto_examples_connectivity_plot_vertices_around_seed.py` + +.. raw:: html + +
Plot vertices around seed.
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /auto_examples/connectivity/images/thumb/sphx_glr_plot_destriux_atlas_based_connectivity_thumb.png + :alt: + + :ref:`sphx_glr_auto_examples_connectivity_plot_destriux_atlas_based_connectivity.py` + +.. raw:: html + +
Plot Destriux Atlas
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /auto_examples/connectivity/images/thumb/sphx_glr_plot_labelled_connectivity_circle_thumb.png + :alt: + + :ref:`sphx_glr_auto_examples_connectivity_plot_labelled_connectivity_circle.py` + +.. raw:: html + +
Plot labelled connectivity circle
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /auto_examples/connectivity/images/thumb/sphx_glr_plot_surrogate_methods_thumb.png + :alt: + + :ref:`sphx_glr_auto_examples_connectivity_plot_surrogate_methods.py` + +.. raw:: html + +
Plot surrogate methods
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /auto_examples/connectivity/images/thumb/sphx_glr_plot_brain_connectome_thumb.png + :alt: + + :ref:`sphx_glr_auto_examples_connectivity_plot_brain_connectome.py` + +.. raw:: html + +
Plot brain connectome
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /auto_examples/connectivity/images/thumb/sphx_glr_plot_circle_lines_and_blobs_thumb.png + :alt: + + :ref:`sphx_glr_auto_examples_connectivity_plot_circle_lines_and_blobs.py` + +.. raw:: html + +
Plot centrality indices on connectivity circle plot
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /auto_examples/connectivity/images/thumb/sphx_glr_plot_annot_standard_rsns_thumb.png + :alt: + + :ref:`sphx_glr_auto_examples_connectivity_plot_annot_standard_rsns.py` + +.. raw:: html + +
Visualise Standard RSNs
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /auto_examples/connectivity/images/thumb/sphx_glr_plot_generic_grouped_connectivity_circle_thumb.png + :alt: + + :ref:`sphx_glr_auto_examples_connectivity_plot_generic_grouped_connectivity_circle.py` + +.. raw:: html + +
Generic Grouped Connectivity Circle
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /auto_examples/connectivity/images/thumb/sphx_glr_plot_compute_label_distances_thumb.png + :alt: + + :ref:`sphx_glr_auto_examples_connectivity_plot_compute_label_distances.py` + +.. raw:: html + +
Compute Label Distances
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /auto_examples/connectivity/images/thumb/sphx_glr_plot_compute_epochs_surrogates_thumb.png + :alt: + + :ref:`sphx_glr_auto_examples_connectivity_plot_compute_epochs_surrogates.py` + +.. raw:: html + +
Surrogate Connectivity Generation
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /auto_examples/connectivity/images/thumb/sphx_glr_plot_grouped_connectivity_circle_thumb.png + :alt: + + :ref:`sphx_glr_auto_examples_connectivity_plot_grouped_connectivity_circle.py` + +.. raw:: html + +
Plot grouped connectivity circle.
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /auto_examples/connectivity/images/thumb/sphx_glr_plot_test_transform_mni_to_ras_thumb.png + :alt: + + :ref:`sphx_glr_auto_examples_connectivity_plot_test_transform_mni_to_ras.py` + +.. raw:: html + +
To plot a vertex point, convert it to MNI coordinates and then reconvert it back to RAS to obtain the vertex number.
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /auto_examples/connectivity/images/thumb/sphx_glr_plot_generate_surrogate_stcs_thumb.png + :alt: + + :ref:`sphx_glr_auto_examples_connectivity_plot_generate_surrogate_stcs.py` + +.. raw:: html + +
Generate surrogate STCs
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /auto_examples/connectivity/images/thumb/sphx_glr_plot_shuffle_time_slices_thumb.png + :alt: + + :ref:`sphx_glr_auto_examples_connectivity_plot_shuffle_time_slices.py` + +.. raw:: html + +
Shuffle channels' data in the time domain and plot.
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /auto_examples/connectivity/images/thumb/sphx_glr_plot_label_distances_thumb.png + :alt: + + :ref:`sphx_glr_auto_examples_connectivity_plot_label_distances.py` + +.. raw:: html + +
Plot label distances
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /auto_examples/connectivity/images/thumb/sphx_glr_plot_communities_thumb.png + :alt: + + :ref:`sphx_glr_auto_examples_connectivity_plot_communities.py` + +.. raw:: html + +
Plot network communities
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /auto_examples/connectivity/images/thumb/sphx_glr_plot_custom_grouped_connectivity_circle_thumb.png + :alt: + + :ref:`sphx_glr_auto_examples_connectivity_plot_custom_grouped_connectivity_circle.py` + +.. raw:: html + +
Plot Custom Grouped Circle
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /auto_examples/connectivity/images/thumb/sphx_glr_plot_standard_resting_network_on_aparc_annot_map_thumb.png + :alt: + + :ref:`sphx_glr_auto_examples_connectivity_plot_standard_resting_network_on_aparc_annot_map.py` + +.. raw:: html + +
Standard RSNs on the connectivity circle
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /auto_examples/connectivity/images/thumb/sphx_glr_plot_connectivity_between_standard_rsns_thumb.png + :alt: + + :ref:`sphx_glr_auto_examples_connectivity_plot_connectivity_between_standard_rsns.py` + +.. raw:: html + +
Modified MNE-Python example script to show connectivity between standard
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /auto_examples/connectivity/images/thumb/sphx_glr_plot_generate_surrogate_connectivity_thumb.png + :alt: + + :ref:`sphx_glr_auto_examples_connectivity_plot_generate_surrogate_connectivity.py` + +.. raw:: html + +
Surrogate computation
+
+ + +.. raw:: html + +
+ +.. only:: html + + .. image:: /auto_examples/connectivity/images/thumb/sphx_glr_plot_simulated_connectivity_thumb.png + :alt: + + :ref:`sphx_glr_auto_examples_connectivity_plot_simulated_connectivity.py` + +.. raw:: html + +
Simulating Connectivity
+
+ + +.. raw:: html + +
+ + +.. toctree:: + :hidden: + + /auto_examples/connectivity/plot_degree_circle + /auto_examples/connectivity/plot_vertices_around_seed + /auto_examples/connectivity/plot_destriux_atlas_based_connectivity + /auto_examples/connectivity/plot_labelled_connectivity_circle + /auto_examples/connectivity/plot_surrogate_methods + /auto_examples/connectivity/plot_brain_connectome + /auto_examples/connectivity/plot_circle_lines_and_blobs + /auto_examples/connectivity/plot_annot_standard_rsns + /auto_examples/connectivity/plot_generic_grouped_connectivity_circle + /auto_examples/connectivity/plot_compute_label_distances + /auto_examples/connectivity/plot_compute_epochs_surrogates + /auto_examples/connectivity/plot_grouped_connectivity_circle + /auto_examples/connectivity/plot_test_transform_mni_to_ras + /auto_examples/connectivity/plot_generate_surrogate_stcs + /auto_examples/connectivity/plot_shuffle_time_slices + /auto_examples/connectivity/plot_label_distances + /auto_examples/connectivity/plot_communities + /auto_examples/connectivity/plot_custom_grouped_connectivity_circle + /auto_examples/connectivity/plot_standard_resting_network_on_aparc_annot_map + /auto_examples/connectivity/plot_connectivity_between_standard_rsns + /auto_examples/connectivity/plot_generate_surrogate_connectivity + /auto_examples/connectivity/plot_simulated_connectivity + diff --git a/docs/build/html/_sources/auto_examples/connectivity/plot_annot_standard_rsns.rst.txt b/docs/build/html/_sources/auto_examples/connectivity/plot_annot_standard_rsns.rst.txt new file mode 100644 index 00000000..aa923eee --- /dev/null +++ b/docs/build/html/_sources/auto_examples/connectivity/plot_annot_standard_rsns.rst.txt @@ -0,0 +1,218 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "auto_examples/connectivity/plot_annot_standard_rsns.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_auto_examples_connectivity_plot_annot_standard_rsns.py: + + +============= +Visualise Standard RSNs +============= + +Grow and visualize standard resting state ROIs from literature. + +1. Read ROIs of standard regions involved in resting state networks from literature. + (the data is provided as a csv file with list of regions with seed MNI coordinates) +2. Grow labels of 1cm radius (approx) in the surface source space. +3. Make annotation and visualize the labels. + +Uses RSNs provided by [1] +[1] P. Garcés, M. C. Martín-Buro, and F. Maestú, +“Quantifying the Test-Retest Reliability of Magnetoencephalography +Resting-State Functional Connectivity,” Brain Connect., vol. 6, no. 6, pp. 448–460, 2016. + +Author: Praveen Sripad + +.. GENERATED FROM PYTHON SOURCE LINES 22-61 + + + +.. image-sg:: /auto_examples/connectivity/images/sphx_glr_plot_annot_standard_rsns_001.png + :alt: plot annot standard rsns + :srcset: /auto_examples/connectivity/images/sphx_glr_plot_annot_standard_rsns_001.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + Visual Left visual cortex : [-41 -77 3] lh Closest vertex on surface chosen: [6708] + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.8s remaining: 0.8s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.8s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.8s finished + Right visual cortex : [ 41 -72 1] rh Closest vertex on surface chosen: [10095] + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s finished + Sensorimotor Left primary somatosensory cortex : [-38 -27 52] lh Closest vertex on surface chosen: [62711] + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s finished + Right primary somatosensory cortex : [ 40 -25 50] rh Closest vertex on surface chosen: [71297] + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s finished + Auditory Left primary auditory cortex : [-55 -21 7] lh Closest vertex on surface chosen: [72410] + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s finished + Right primary auditory cortex : [ 57 -20 7] rh Closest vertex on surface chosen: [76848] + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s finished + DMN Precuneus : [ 1 -57 28] lh Closest vertex on surface chosen: [29030] + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s finished + Left inferior parietal : [-45 -65 30] lh Closest vertex on surface chosen: [15645] + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s finished + Right inferior parietal : [ 52 -60 26] rh Closest vertex on surface chosen: [26366] + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s finished + Anterior cingulate : [ 2 42 7] lh Closest vertex on surface chosen: [155310] + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s finished + Left FP Left angular gyrus : [-40 -58 56] lh Closest vertex on surface chosen: [24630] + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s finished + Left middle frontal gyrus : [-42 28 23] lh Closest vertex on surface chosen: [126993] + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s finished + Right FP Right angular gyrus : [ 53 -50 43] rh Closest vertex on surface chosen: [38519] + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s finished + Right middle frontal gyrus : [45 28 26] rh Closest vertex on surface chosen: [130082] + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s finished + Frontoinsular Left insula : [-38 16 2] lh Closest vertex on surface chosen: [115415] + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s finished + Right insula : [38 16 2] rh Closest vertex on surface chosen: [119046] + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s finished + Median cingulate : [-2 12 40] lh Closest vertex on surface chosen: [110618] + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.1s remaining: 0.1s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s finished + Using pyvistaqt 3d backend. + + + + + + + +| + +.. code-block:: default + + + import os.path as op + import numpy as np + import mne + + from mne.datasets import sample + from jumeg.jumeg_utils import get_jumeg_path + from jumeg.connectivity import make_annot_from_csv + + from nilearn import plotting + from mne.viz import Brain + + data_path = sample.data_path() + subject = 'sample' + subjects_dir = op.join(data_path, 'subjects') + parc_fname = 'standard_garces_2016' + csv_fname = op.join(get_jumeg_path(), 'data', 'standard_rsns.csv') + + # set make_annot to True to save the annotation to disk + labels, coords, _ = make_annot_from_csv(subject, subjects_dir, csv_fname, + parc_fname=parc_fname, make_annot=False, + return_label_coords=True) + + # to plot mni coords on glass brain + n_nodes = np.array(coords).shape[0] + # make a random zero valued connectivity matrix + con = np.zeros((n_nodes, n_nodes)) + # plot the connectome on a glass brain background + plotting.plot_connectome(con, coords) + plotting.show() + + # plot the brain surface, foci and labels + Brain = mne.viz.get_brain_class() + brain = Brain(subject, hemi='both', surf='white', subjects_dir=subjects_dir) + + for mni_coord, mylabel in zip(coords, labels): + brain.add_foci(mni_coord, coords_as_verts=False, hemi=mylabel.hemi, + color='red', scale_factor=0.6) + brain.add_label(mylabel, hemi=mylabel.hemi) + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** ( 0 minutes 5.618 seconds) + + +.. _sphx_glr_download_auto_examples_connectivity_plot_annot_standard_rsns.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + + + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_annot_standard_rsns.py ` + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_annot_standard_rsns.ipynb ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/build/html/_sources/auto_examples/connectivity/plot_brain_connectome.rst.txt b/docs/build/html/_sources/auto_examples/connectivity/plot_brain_connectome.rst.txt new file mode 100644 index 00000000..17fa55a9 --- /dev/null +++ b/docs/build/html/_sources/auto_examples/connectivity/plot_brain_connectome.rst.txt @@ -0,0 +1,130 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "auto_examples/connectivity/plot_brain_connectome.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_auto_examples_connectivity_plot_brain_connectome.py: + + +============= +Plot brain connectome +============= + +Plot connectivity on a glass brain using 'plot_connectome' function from +Nilearn (https://nilearn.github.io/). + +Author: Praveen Sripad + +.. GENERATED FROM PYTHON SOURCE LINES 13-57 + + + +.. image-sg:: /auto_examples/connectivity/images/sphx_glr_plot_brain_connectome_001.png + :alt: plot brain connectome + :srcset: /auto_examples/connectivity/images/sphx_glr_plot_brain_connectome_001.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + Reading labels from parcellation... + read 35 labels from /Users/praveen.sripad/nanna_data/mne_data/MNE-sample-data/subjects/fsaverage/label/lh.aparc.annot + read 34 labels from /Users/praveen.sripad/nanna_data/mne_data/MNE-sample-data/subjects/fsaverage/label/rh.aparc.annot + + + + + + +| + +.. code-block:: default + + + import os.path as op + import numpy as np + import matplotlib.pyplot as plt + + import mne + from mne.datasets import sample + + from nilearn import plotting + + from jumeg.connectivity import generate_random_connectivity_matrix + + data_path = sample.data_path() + subjects_dir = op.join(data_path, 'subjects') + subject = 'fsaverage' + + aparc = mne.read_labels_from_annot(subject, subjects_dir=subjects_dir, + parc='aparc') + + # nodes in one hemisphere can be plotted as well + aparc_lh = [lab for lab in aparc if lab.hemi == 'lh'] + + coords = [] + + # plot 10 nodes from left hemisphere only for better viz + for lab in aparc_lh[:10]: + if lab.name == 'unknown-lh': + continue + # get the center of mass + com = lab.center_of_mass('fsaverage') + # obtain mni coordinated to the vertex from left hemi + coords_ = mne.vertex_to_mni(com, hemis=0, subject=subject, + subjects_dir=subjects_dir) + coords.append(coords_) + + n_nodes = np.array(coords).shape[0] + + # make a random connectivity matrix + con = generate_random_connectivity_matrix(size=(n_nodes, n_nodes), + symmetric=True) + + # plot the connectome on a glass brain background + plotting.plot_connectome(con, coords) + plt.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** ( 0 minutes 0.581 seconds) + + +.. _sphx_glr_download_auto_examples_connectivity_plot_brain_connectome.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + + + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_brain_connectome.py ` + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_brain_connectome.ipynb ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/build/html/_sources/auto_examples/connectivity/plot_circle_lines_and_blobs.rst.txt b/docs/build/html/_sources/auto_examples/connectivity/plot_circle_lines_and_blobs.rst.txt new file mode 100644 index 00000000..5b0bb94e --- /dev/null +++ b/docs/build/html/_sources/auto_examples/connectivity/plot_circle_lines_and_blobs.rst.txt @@ -0,0 +1,120 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "auto_examples/connectivity/plot_circle_lines_and_blobs.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_auto_examples_connectivity_plot_circle_lines_and_blobs.py: + + +============= +Plot centrality indices on connectivity circle plot +============= + +Script to show functionality to plot centrality indices along with +connectivity circle plot. + +.. GENERATED FROM PYTHON SOURCE LINES 9-44 + + + +.. image-sg:: /auto_examples/connectivity/images/sphx_glr_plot_circle_lines_and_blobs_001.png + :alt: Eigen vector centrality: Coh,alpha + :srcset: /auto_examples/connectivity/images/sphx_glr_plot_circle_lines_and_blobs_001.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + /Users/praveen.sripad/seafile/repolib/mne/jumeg/jumeg/connectivity/con_viz.py:1261: UserWarning: No data for colormapping provided via 'c'. Parameters 'cmap' will be ignored + c = ax.scatter(theta, radii, c=reordered_colors, s=degrees * degsize, + /Users/praveen.sripad/seafile/repolib/mne/jumeg/examples/connectivity/plot_circle_lines_and_blobs.py:43: UserWarning: This figure includes Axes that are not compatible with tight_layout, so results might be incorrect. + fig.tight_layout() + + + + + + +| + +.. code-block:: default + + + import os.path as op + import numpy as np + import matplotlib.pyplot as plt + import mne + from mne_connectivity import degree + from jumeg import get_jumeg_path + from jumeg.connectivity import plot_degree_circle, plot_lines_and_blobs + + import bct + import yaml + + orig_labels_fname = op.join(get_jumeg_path(), 'data/desikan_label_names.yaml') + yaml_fname = op.join(get_jumeg_path(), 'data/desikan_aparc_cortex_based_grouping.yaml') + con_fname = op.join(get_jumeg_path(), 'data/sample,aparc-con.npy') + + replacer_dict_fname = op.join(get_jumeg_path(), 'data/replacer_dictionaries.yaml') + + with open(replacer_dict_fname, 'r') as f: + replacer_dict = yaml.safe_load(f)['replacer_dict_aparc'] + + # real connectivity + con = np.load(con_fname) + con = con[0, :, :, 2] + con[0, :, :, 2].T + degrees = degree(con, threshold_prop=0.2) + + eigenvec_centrality = bct.eigenvector_centrality_und(con) + + fig, ax = plot_lines_and_blobs(con, degrees, yaml_fname, + orig_labels_fname, replacer_dict=replacer_dict, + figsize=(8, 8), show_node_labels=False, + show_group_labels=True, n_lines=100, + out_fname=None, degsize=10) + ax.set_title('Eigen vector centrality: Coh,alpha') + fig.tight_layout() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** ( 0 minutes 0.099 seconds) + + +.. _sphx_glr_download_auto_examples_connectivity_plot_circle_lines_and_blobs.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + + + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_circle_lines_and_blobs.py ` + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_circle_lines_and_blobs.ipynb ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/build/html/_sources/auto_examples/connectivity/plot_communities.rst.txt b/docs/build/html/_sources/auto_examples/connectivity/plot_communities.rst.txt new file mode 100644 index 00000000..00772f79 --- /dev/null +++ b/docs/build/html/_sources/auto_examples/connectivity/plot_communities.rst.txt @@ -0,0 +1,187 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "auto_examples/connectivity/plot_communities.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_auto_examples_connectivity_plot_communities.py: + + +============= +Plot network communities +============= + +Plot Networkx Communities on a connectome plot. + +Author: Praveen Sripad + +.. GENERATED FROM PYTHON SOURCE LINES 12-80 + + + +.. image-sg:: /auto_examples/connectivity/images/sphx_glr_plot_communities_001.png + :alt: plot communities + :srcset: /auto_examples/connectivity/images/sphx_glr_plot_communities_001.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + Reading labels from parcellation... + read 35 labels from /Users/praveen.sripad/nanna_data/mne_data/MNE-sample-data/subjects/fsaverage/label/lh.aparc.annot + read 34 labels from /Users/praveen.sripad/nanna_data/mne_data/MNE-sample-data/subjects/fsaverage/label/rh.aparc.annot + bankssts-rh + caudalanteriorcingulate-rh + caudalmiddlefrontal-rh + entorhinal-lh + entorhinal-rh + fusiform-lh + inferiorparietal-lh + inferiortemporal-lh + insula-rh + isthmuscingulate-lh + lateraloccipital-lh + lateraloccipital-rh + lateralorbitofrontal-rh + middletemporal-lh + middletemporal-rh + paracentral-lh + caudalanteriorcingulate-lh + caudalmiddlefrontal-lh + cuneus-lh + frontalpole-lh + frontalpole-rh + inferiortemporal-rh + insula-lh + isthmuscingulate-rh + lateralorbitofrontal-lh + lingual-rh + paracentral-rh + bankssts-lh + cuneus-rh + fusiform-rh + inferiorparietal-rh + lingual-lh + medialorbitofrontal-lh + medialorbitofrontal-rh + + + + + + +| + +.. code-block:: default + + + import os.path as op + import numpy as np + import matplotlib.pyplot as plt + + import mne + from mne.datasets import sample + from jumeg.connectivity.con_utils import make_communities + from jumeg.connectivity import generate_random_connectivity_matrix + + from nilearn import plotting + + data_path = sample.data_path() + subjects_dir = op.join(data_path, 'subjects') + subject = 'fsaverage' + aparc = mne.read_labels_from_annot(subject, subjects_dir=subjects_dir, + parc='aparc') + + # make a random connectivity matrix + con = generate_random_connectivity_matrix(size=(34, 34), symmetric=True) + + top_nodes_list, n_communities = make_communities(con) + + # FIXME better colouring + # cmaps_list = ['Pastel1', 'Pastel2', 'Paired', 'Accent', + # 'Dark2', 'Set1', 'Set2', 'Set3', + # 'tab10', 'tab20', 'tab20b', 'tab20c'] + # color_list = plt.cm.Pastel1(np.linspace(0, 1, len(top_nodes_list))) + + color_list = ['red', 'orange', 'green', 'purple', 'navy', 'blue'] + cmaps_list = ['Reds', 'Oranges', 'Greens', 'Purples', 'PuBu', 'Blues'] + + fig = plt.figure(facecolor='w', edgecolor='w') + + for top_nodes, col, cmap in zip(top_nodes_list, color_list, cmaps_list): + + coords = [] + community_ = [aparc[tp] for tp in top_nodes] + + for lab in community_: + if lab.name == 'unknown-lh': + continue + print(lab.name) + # get the center of mass + com = lab.center_of_mass('fsaverage') + if lab.name.endswith('lh'): + # obtain mni coordinated to the vertex from left hemi + coords_ = mne.vertex_to_mni(com, hemis=0, subject=subject, + subjects_dir=subjects_dir) + else: + coords_ = mne.vertex_to_mni(com, hemis=1, subject=subject, + subjects_dir=subjects_dir) + coords.append(coords_) + + n_nodes = np.array(coords).shape[0] + # make a dummy connectivity matrix + # FIXME use the existing con matrix with indices chosen instead + con_ = np.ones((n_nodes, n_nodes)) / 2. + con_[np.diag_indices(n_nodes)] = 0. + con_[np.triu_indices(n_nodes, k=1)] = 0. + con_ += con_.T + + # plot the connectome on a glass brain background + plotting.plot_connectome(con_, coords, node_color=col, edge_cmap=cmap, + figure=fig, edge_vmin=0., edge_vmax=1.) + + plt.show() + # plt.savefig('fig_communities.png') + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** ( 0 minutes 1.331 seconds) + + +.. _sphx_glr_download_auto_examples_connectivity_plot_communities.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + + + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_communities.py ` + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_communities.ipynb ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/build/html/_sources/auto_examples/connectivity/plot_compute_epochs_surrogates.rst.txt b/docs/build/html/_sources/auto_examples/connectivity/plot_compute_epochs_surrogates.rst.txt new file mode 100644 index 00000000..2057cbcd --- /dev/null +++ b/docs/build/html/_sources/auto_examples/connectivity/plot_compute_epochs_surrogates.rst.txt @@ -0,0 +1,153 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "auto_examples/connectivity/plot_compute_epochs_surrogates.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_auto_examples_connectivity_plot_compute_epochs_surrogates.py: + + +============= +Surrogate Connectivity Generation +============= + +Example to show surrogate generation on Epochs using the jumeg Surrogates +module. + +.. GENERATED FROM PYTHON SOURCE LINES 11-60 + + + +.. image-sg:: /auto_examples/connectivity/images/sphx_glr_plot_compute_epochs_surrogates_001.png + :alt: Evoked (102 channels), Surrogate Evoked (102 channels) + :srcset: /auto_examples/connectivity/images/sphx_glr_plot_compute_epochs_surrogates_001.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + Opening raw data file /Users/praveen.sripad/nanna_data/mne_data/MNE-sample-data/MEG/sample/sample_audvis_filt-0-40_raw.fif... + Read a total of 4 projection items: + PCA-v1 (1 x 102) idle + PCA-v2 (1 x 102) idle + PCA-v3 (1 x 102) idle + Average EEG reference (1 x 60) idle + Range : 6450 ... 48149 = 42.956 ... 320.665 secs + Ready. + Not setting metadata + 72 matching events found + Setting baseline interval to [-0.19979521315838786, 0.0] s + Applying baseline correction (mode: mean) + Created an SSP operator (subspace dimension = 3) + 4 projection items activated + Loading data for 72 events and 106 original time points ... + Rejecting epoch based on MAG : ['MEG 1711'] + 1 bad epochs dropped + WARNING: Currently surrogates on Epochs only returns a generator. + computing surrogate 0 + NOTE: pick_channels() is a legacy function. New code should use inst.pick(...). + Removing projector + NOTE: pick_channels() is a legacy function. New code should use inst.pick(...). + Removing projector + + + + + + +| + +.. code-block:: default + + + import os.path as op + import numpy as np + import matplotlib.pyplot as pl + from mne.datasets import sample + import mne + + from jumeg.jumeg_surrogates import Surrogates, check_power_spectrum + + data_path = sample.data_path() + subjects_dir = op.join(data_path, 'subjects') + + fname_raw = op.join(data_path, 'MEG/sample/sample_audvis_filt-0-40_raw.fif') + fname_event = op.join(data_path, 'MEG/sample/sample_audvis_filt-0-40_raw-eve.fif') + + epochs_testing = False + + raw = mne.io.read_raw_fif(fname_raw) + events = mne.read_events(fname_event) + + # add a bad channel + raw.info['bads'] += ['MEG 2443'] + + # pick MEG channels + picks = mne.pick_types(raw.info, meg='mag', eeg=False, stim=False, eog=False, + exclude='bads') + + # Define epochs for left-auditory condition + event_id, tmin, tmax = 1, -0.2, 0.5 + epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks, + baseline=(None, 0), reject=dict(mag=4e-12)) + + # initialize the Surrogates object + surr_epochs = Surrogates(epochs) + + n_surr = 10 # number of surrogates + mode = 'randomize_phase' + mysurr = surr_epochs.compute_surrogates(n_surr=n_surr, + mode=mode, return_generator=False) + + # get one epochs for plotting + # for epochs, a generator is always returned + first_surr_epoch = next(mysurr) + + # visualize surrogates + fig, (ax1, ax2) = pl.subplots(2, 1) + epochs.average().plot(axes=ax1, show=False, titles='Evoked') + first_surr_epoch.average().plot(axes=ax2, show=False, titles='Surrogate Evoked') + pl.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** ( 0 minutes 0.463 seconds) + + +.. _sphx_glr_download_auto_examples_connectivity_plot_compute_epochs_surrogates.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + + + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_compute_epochs_surrogates.py ` + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_compute_epochs_surrogates.ipynb ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/build/html/_sources/auto_examples/connectivity/plot_compute_label_distances.rst.txt b/docs/build/html/_sources/auto_examples/connectivity/plot_compute_label_distances.rst.txt new file mode 100644 index 00000000..6f634144 --- /dev/null +++ b/docs/build/html/_sources/auto_examples/connectivity/plot_compute_label_distances.rst.txt @@ -0,0 +1,123 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "auto_examples/connectivity/plot_compute_label_distances.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_auto_examples_connectivity_plot_compute_label_distances.py: + + +============= +Compute Label Distances +============= + +Script show how to compute and visualize distance between label center of +masses for a given subject. + +Author: Praveen Sripad + +.. GENERATED FROM PYTHON SOURCE LINES 13-49 + + + +.. image-sg:: /auto_examples/connectivity/images/sphx_glr_plot_compute_label_distances_001.png + :alt: plot compute label distances + :srcset: /auto_examples/connectivity/images/sphx_glr_plot_compute_label_distances_001.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + Reading labels from parcellation... + read 226 labels from /Users/praveen.sripad/nanna_data/mne_data/MNE-sample-data/subjects/sample/label/lh.aparc_sub.annot + read 224 labels from /Users/praveen.sripad/nanna_data/mne_data/MNE-sample-data/subjects/sample/label/rh.aparc_sub.annot + Max distance between ROIs 169.0 + + + + + + +| + +.. code-block:: default + + + import os.path as op + from jumeg.connectivity import get_label_distances + from surfer import Brain + from nilearn import plotting + from mne.datasets import sample + + data_path = sample.data_path() + subjects_dir = op.join(data_path, 'subjects') + subject = 'sample' + parc = 'aparc_sub' + + # compute the distances between COM's of the labels + rounded_coms, coords, coms_lh, coms_rh = get_label_distances(subject, + subjects_dir, + parc=parc) + # np.save('%s_distances.npy' % subject, rounded_com) + + # get maximum distance between ROIs + print('Max distance between ROIs', rounded_coms.ravel().max()) + + # do plotting using PySurfer + brain = Brain(subject, hemi='both', surf='inflated', subjects_dir=subjects_dir) + brain.add_foci(coms_lh, coords_as_verts=True, hemi='lh') + brain.add_foci(coms_rh, coords_as_verts=True, hemi='rh') + brain.save_montage('%s_%s_coms.png' % (subject, parc), + order=['lat', 'ven', 'med'], + orientation='h', border_size=15, colorbar='auto', + row=-1, col=-1) + brain.close() + + # show the label ROIs using Nilearn plotting + fig = plotting.plot_connectome(rounded_coms, coords, + edge_threshold='99%', node_color='cornflowerblue', + title='%s - label distances' % parc) + fig.savefig('fig_%s_label_distances.png' % parc) + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** ( 0 minutes 6.340 seconds) + + +.. _sphx_glr_download_auto_examples_connectivity_plot_compute_label_distances.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + + + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_compute_label_distances.py ` + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_compute_label_distances.ipynb ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/build/html/_sources/auto_examples/connectivity/plot_connectivity_between_standard_rsns.rst.txt b/docs/build/html/_sources/auto_examples/connectivity/plot_connectivity_between_standard_rsns.rst.txt new file mode 100644 index 00000000..8d019961 --- /dev/null +++ b/docs/build/html/_sources/auto_examples/connectivity/plot_connectivity_between_standard_rsns.rst.txt @@ -0,0 +1,467 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "auto_examples/connectivity/plot_connectivity_between_standard_rsns.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_auto_examples_connectivity_plot_connectivity_between_standard_rsns.py: + + +Modified MNE-Python example script to show connectivity between standard +resting state network labels obtained from [1]. + +[1] P. Garcés, M. C. Martín-Buro, and F. Maestú, +“Quantifying the Test-Retest Reliability of Magnetoencephalography +Resting-State Functional Connectivity,” Brain Connect., vol. 6, no. 6, pp. +448–460, 2016. + +Author: Praveen sripad + +.. GENERATED FROM PYTHON SOURCE LINES 12-124 + + + +.. image-sg:: /auto_examples/connectivity/images/sphx_glr_plot_connectivity_between_standard_rsns_001.png + :alt: Connectivity between standard RSNs + :srcset: /auto_examples/connectivity/images/sphx_glr_plot_connectivity_between_standard_rsns_001.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + Reading inverse operator decomposition from /Users/praveen.sripad/nanna_data/mne_data/MNE-sample-data/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif... + Reading inverse operator info... + [done] + Reading inverse operator decomposition... + [done] + 305 x 305 full covariance (kind = 1) found. + Read a total of 4 projection items: + PCA-v1 (1 x 102) active + PCA-v2 (1 x 102) active + PCA-v3 (1 x 102) active + Average EEG reference (1 x 60) active + Noise covariance matrix read. + 22494 x 22494 diagonal covariance (kind = 2) found. + Source covariance matrix read. + 22494 x 22494 diagonal covariance (kind = 6) found. + Orientation priors read. + 22494 x 22494 diagonal covariance (kind = 5) found. + Depth priors read. + Did not find the desired covariance matrix (kind = 3) + Reading a source space... + Computing patch statistics... + Patch information added... + Distance information added... + [done] + Reading a source space... + Computing patch statistics... + Patch information added... + Distance information added... + [done] + 2 source spaces read + Read a total of 4 projection items: + PCA-v1 (1 x 102) active + PCA-v2 (1 x 102) active + PCA-v3 (1 x 102) active + Average EEG reference (1 x 60) active + Source spaces transformed to the inverse solution coordinate frame + Opening raw data file /Users/praveen.sripad/nanna_data/mne_data/MNE-sample-data/MEG/sample/sample_audvis_filt-0-40_raw.fif... + Read a total of 4 projection items: + PCA-v1 (1 x 102) idle + PCA-v2 (1 x 102) idle + PCA-v3 (1 x 102) idle + Average EEG reference (1 x 60) idle + Range : 6450 ... 48149 = 42.956 ... 320.665 secs + Ready. + Not setting metadata + 72 matching events found + Setting baseline interval to [-0.19979521315838786, 0.0] s + Applying baseline correction (mode: mean) + Created an SSP operator (subspace dimension = 3) + 4 projection items activated + Loading data for 72 events and 106 original time points ... + Rejecting epoch based on EOG : ['EOG 061'] + Rejecting epoch based on EOG : ['EOG 061'] + Rejecting epoch based on EOG : ['EOG 061'] + Rejecting epoch based on EOG : ['EOG 061'] + Rejecting epoch based on EOG : ['EOG 061'] + Rejecting epoch based on MAG : ['MEG 1711'] + Rejecting epoch based on EOG : ['EOG 061'] + Rejecting epoch based on EOG : ['EOG 061'] + Rejecting epoch based on EOG : ['EOG 061'] + Rejecting epoch based on EOG : ['EOG 061'] + Rejecting epoch based on EOG : ['EOG 061'] + Rejecting epoch based on EOG : ['EOG 061'] + Rejecting epoch based on EOG : ['EOG 061'] + Rejecting epoch based on EOG : ['EOG 061'] + Rejecting epoch based on EOG : ['EOG 061'] + Rejecting epoch based on EOG : ['EOG 061'] + Rejecting epoch based on EOG : ['EOG 061'] + 17 bad epochs dropped + Reading labels from parcellation... + read 11 labels from /Users/praveen.sripad/nanna_data/mne_data/MNE-sample-data/subjects/sample/label/lh.standard_garces_2016.annot + read 8 labels from /Users/praveen.sripad/nanna_data/mne_data/MNE-sample-data/subjects/sample/label/rh.standard_garces_2016.annot + Connectivity computation... + Preparing the inverse operator for use... + Scaled noise and source covariance from nave = 1 to nave = 1 + Created the regularized inverter + Created an SSP operator (subspace dimension = 3) + Created the whitener using a noise covariance matrix with rank 302 (3 small eigenvalues omitted) + Picked 305 channels from the data + Computing inverse... + Eigenleads need to be weighted ... + Processing epoch : 1 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 2 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 3 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 4 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + only using indices for lower-triangular matrix + computing connectivity for 136 connections + using t=0.000s..0.699s for estimation (106 points) + frequencies: 8.5Hz..12.7Hz (4 points) + connectivity scores will be averaged for each band + Using multitaper spectrum estimation with 7 DPSS windows + the following metrics will be computed: Coherence, WPLI + computing connectivity for epochs 1..4 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.7s remaining: 0.7s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.7s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.7s finished + Processing epoch : 5 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 6 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 7 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 8 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + computing connectivity for epochs 5..8 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + Processing epoch : 9 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 10 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 11 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 12 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + computing connectivity for epochs 9..12 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + Processing epoch : 13 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 14 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 15 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 16 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + computing connectivity for epochs 13..16 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + Processing epoch : 17 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 18 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 19 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 20 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + computing connectivity for epochs 17..20 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + Processing epoch : 21 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 22 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 23 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 24 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + computing connectivity for epochs 21..24 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + Processing epoch : 25 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 26 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 27 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 28 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + computing connectivity for epochs 25..28 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + Processing epoch : 29 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 30 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 31 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 32 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + computing connectivity for epochs 29..32 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + Processing epoch : 33 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 34 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 35 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 36 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + computing connectivity for epochs 33..36 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + Processing epoch : 37 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 38 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 39 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 40 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + computing connectivity for epochs 37..40 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + Processing epoch : 41 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 42 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 43 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 44 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + computing connectivity for epochs 41..44 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + Processing epoch : 45 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 46 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 47 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 48 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + computing connectivity for epochs 45..48 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + Processing epoch : 49 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 50 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 51 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 52 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + computing connectivity for epochs 49..52 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + Processing epoch : 53 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 54 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + Processing epoch : 55 / 55 + Extracting time courses for 17 labels (mode: mean_flip) + [done] + computing connectivity for epochs 53..55 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 3 out of 3 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 3 out of 3 | elapsed: 0.0s finished + assembling connectivity matrix + [Connectivity computation done] + + (
, ) + + + + + +| + +.. code-block:: default + + + import os.path as op + + import numpy as np + import matplotlib.pyplot as plt + + import mne + from mne.datasets import sample + from mne.minimum_norm import apply_inverse_epochs, read_inverse_operator + from mne.viz import circular_layout + + from mne_connectivity import spectral_connectivity_epochs + from mne_connectivity.viz import plot_connectivity_circle + + data_path = sample.data_path() + subjects_dir = op.join(data_path, 'subjects') + fname_inv = op.join(data_path, 'MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif') + fname_raw = op.join(data_path, 'MEG/sample/sample_audvis_filt-0-40_raw.fif') + fname_event = op.join(data_path, 'MEG/sample/sample_audvis_filt-0-40_raw-eve.fif') + + # Load data + inverse_operator = read_inverse_operator(fname_inv) + raw = mne.io.read_raw_fif(fname_raw) + events = mne.read_events(fname_event) + + # Add a bad channel + raw.info['bads'] += ['MEG 2443'] + + # Pick MEG channels + picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=False, eog=True, + exclude='bads') + + # Define epochs for left-auditory condition + event_id, tmin, tmax = 1, -0.2, 0.5 + epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks, + baseline=(None, 0), reject=dict(mag=4e-12, grad=4000e-13, + eog=150e-6)) + if not epochs.preload: + epochs.load_data() + + # Compute inverse solution and for each epoch. By using "return_generator=True" + # stcs will be a generator object instead of a list. + snr = 1.0 # use lower SNR for single epochs + lambda2 = 1.0 / snr ** 2 + method = "MNE" # use dSPM method (could also be MNE or sLORETA) + stcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, method, + pick_ori="normal", return_generator=True) + + # Get labels for FreeSurfer 'aparc' cortical parcellation with 34 labels/hemi + labels = mne.read_labels_from_annot('sample', parc='standard_garces_2016', + subjects_dir=subjects_dir) + labels = [lab for lab in labels if not lab.name.startswith('unknown')] + label_colors = [label.color for label in labels] + + # Average the source estimates within each label using sign-flips to reduce + # signal cancellations, also here we return a generator + src = inverse_operator['src'] + label_ts = mne.extract_label_time_course(stcs, labels, src, mode='mean_flip', + return_generator=True) + + fmin = 8. + fmax = 13. + sfreq = raw.info['sfreq'] # the sampling frequency + con_methods = ['coh', 'wpli'] + con = spectral_connectivity_epochs( + label_ts, method=con_methods, mode='multitaper', sfreq=sfreq, fmin=fmin, + fmax=fmax, faverage=True, mt_adaptive=True, n_jobs=4) + + # con is a 3D array, get the connectivity for the first (and only) freq. band + # for each method + con_res = dict() + for method, c in zip(con_methods, con): + con_res[method] = c.get_data(output='dense')[:, :, 0] + + # Now, we visualize the connectivity using a circular graph layout + # First, we reorder the labels based on their location in the left hemi + label_names = [label.name for label in labels] + + from jumeg import get_jumeg_path + yaml_fname = get_jumeg_path() + '/data/standard_garces_rsns_grouping.yaml' + + import yaml + with open(yaml_fname, 'r') as f: + xlabels = yaml.safe_load(f) + + # the yaml file has been hand curated to follow the same order as label_names + # if not the node order has to be changed appropriately + node_order = list() + node_order.extend(label_names) + + group_bound = [len(list(key.values())[0]) for key in xlabels] + group_bound = [0] + group_bound + group_boundaries = [sum(group_bound[:i+1]) for i in range(len(group_bound))] + group_boundaries.pop() + + rsn_colors = ['m', 'b', 'y', 'c', 'r', 'g', 'w'] + + group_bound.pop(0) + label_colors = [] + for ind, rep in enumerate(group_bound): + label_colors += [rsn_colors[ind]] * rep + assert len(label_colors) == len(node_order), 'Number of colours do not match' + + from mne.viz.circle import circular_layout + node_angles = circular_layout(label_names, label_names, start_pos=90, + group_boundaries=group_boundaries) + + # Plot the graph using node colors from the FreeSurfer parcellation. + plot_connectivity_circle(con_res['wpli'], label_names, n_lines=300, + node_angles=node_angles, node_colors=label_colors, + title='Connectivity between standard RSNs') + # plt.savefig('circle.png', facecolor='black') + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** ( 0 minutes 2.858 seconds) + + +.. _sphx_glr_download_auto_examples_connectivity_plot_connectivity_between_standard_rsns.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + + + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_connectivity_between_standard_rsns.py ` + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_connectivity_between_standard_rsns.ipynb ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/build/html/_sources/auto_examples/connectivity/plot_custom_grouped_connectivity_circle.rst.txt b/docs/build/html/_sources/auto_examples/connectivity/plot_custom_grouped_connectivity_circle.rst.txt new file mode 100644 index 00000000..16908f50 --- /dev/null +++ b/docs/build/html/_sources/auto_examples/connectivity/plot_custom_grouped_connectivity_circle.rst.txt @@ -0,0 +1,139 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "auto_examples/connectivity/plot_custom_grouped_connectivity_circle.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_auto_examples_connectivity_plot_custom_grouped_connectivity_circle.py: + + +============= +Plot Custom Grouped Circle +============= + +Example how to create a custom label groups and plot grouped connectivity +circle with these labels. + +Author: Praveen Sripad + Christian Kiefer + +.. GENERATED FROM PYTHON SOURCE LINES 14-68 + + + +.. image-sg:: /auto_examples/connectivity/images/sphx_glr_plot_custom_grouped_connectivity_circle_001.png + :alt: plot custom grouped connectivity circle + :srcset: /auto_examples/connectivity/images/sphx_glr_plot_custom_grouped_connectivity_circle_001.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + +
+ + + + + +| + +.. code-block:: default + + + import os.path as op + import matplotlib.pyplot as plt + from jumeg import get_jumeg_path + from jumeg.connectivity import (plot_grouped_connectivity_circle, + generate_random_connectivity_matrix) + + import yaml + + labels_fname = op.join(get_jumeg_path(), 'data/desikan_label_names.yaml') + replacer_dict_fname = op.join(get_jumeg_path(), 'data/replacer_dictionaries.yaml') + + with open(labels_fname, 'r') as f: + label_names = yaml.safe_load(f)['label_names'] + + with open(replacer_dict_fname, 'r') as f: + replacer_dict = yaml.safe_load(f)['replacer_dict_aparc'] + + # make a random matrix with 68 nodes + con = generate_random_connectivity_matrix(size=(68, 68), symmetric=True) + + # make groups based on lobes + occipital = ['lateraloccipital', 'lingual', 'cuneus', 'pericalcarine'] + parietal = ['superiorparietal', 'inferiorparietal', 'precuneus', + 'postcentral', 'supramarginal'] + temporal = ['bankssts', 'temporalpole', 'superiortemporal', 'middletemporal', + 'transversetemporal', 'inferiortemporal', 'fusiform', + 'entorhinal', 'parahippocampal'] + insula = ['insula'] + cingulate = ['rostralanteriorcingulate', 'caudalanteriorcingulate', + 'posteriorcingulate', 'isthmuscingulate'] + frontal = ['superiorfrontal', 'rostralmiddlefrontal', 'caudalmiddlefrontal', + 'parsopercularis', 'parsorbitalis', 'parstriangularis', + 'lateralorbitofrontal', 'medialorbitofrontal', 'precentral', + 'paracentral', 'frontalpole'] + + # we need a list of dictionaries, one dict for each group to denote grouping + label_groups = [{'occipital': occipital}, {'parietal': parietal}, + {'temporal': temporal}, {'insula': insula}, + {'cingulate': cingulate}, + {'frontal': frontal}] + + n_colors = len(label_groups) + cmap = plt.get_cmap('Pastel1') + cortex_colors = cmap.colors[:n_colors] + cmap.colors[:n_colors][::-1] + + # plot simple connectivity circle with cortex based grouping and colors + plot_grouped_connectivity_circle(label_groups, con, label_names, + labels_mode='replace', + replacer_dict=replacer_dict, + cortex_colors=cortex_colors, vmin=0., vmax=1., + out_fname='fig_grouped_con_circle_cortex.png', + colorbar_pos=(0.1, 0.1), n_lines=50, colorbar=True, + colormap='viridis') + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** ( 0 minutes 1.007 seconds) + + +.. _sphx_glr_download_auto_examples_connectivity_plot_custom_grouped_connectivity_circle.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + + + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_custom_grouped_connectivity_circle.py ` + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_custom_grouped_connectivity_circle.ipynb ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/build/html/_sources/auto_examples/connectivity/plot_degree_circle.rst.txt b/docs/build/html/_sources/auto_examples/connectivity/plot_degree_circle.rst.txt new file mode 100644 index 00000000..9dce456b --- /dev/null +++ b/docs/build/html/_sources/auto_examples/connectivity/plot_degree_circle.rst.txt @@ -0,0 +1,94 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "auto_examples/connectivity/plot_degree_circle.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_auto_examples_connectivity_plot_degree_circle.py: + + +============= +Plot degree circle +============= + +Plot degree values for a given set of nodes in a simple circle plot. + +.. GENERATED FROM PYTHON SOURCE LINES 10-33 + + + +.. image-sg:: /auto_examples/connectivity/images/sphx_glr_plot_degree_circle_001.png + :alt: plot degree circle + :srcset: /auto_examples/connectivity/images/sphx_glr_plot_degree_circle_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: default + + + import os.path as op + import numpy as np + import matplotlib.pyplot as plt + + import mne + from mne_connectivity import degree + from jumeg import get_jumeg_path + from jumeg.connectivity import plot_degree_circle + + import bct + + orig_labels_fname = op.join(get_jumeg_path(), 'data/desikan_label_names.yaml') + yaml_fname = op.join(get_jumeg_path(), 'data/desikan_aparc_cortex_based_grouping.yaml') + con_fname = op.join(get_jumeg_path(), 'data/sample,aparc-con.npy') + + con = np.load(con_fname) + con_ = con[0, :, :, 2] + con[0, :, :, 2].T + + # compute the degree + degrees = degree(con_, threshold_prop=0.2) + + fig, ax = plot_degree_circle(degrees, yaml_fname, orig_labels_fname) + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** ( 0 minutes 1.439 seconds) + + +.. _sphx_glr_download_auto_examples_connectivity_plot_degree_circle.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + + + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_degree_circle.py ` + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_degree_circle.ipynb ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/build/html/_sources/auto_examples/connectivity/plot_destriux_atlas_based_connectivity.rst.txt b/docs/build/html/_sources/auto_examples/connectivity/plot_destriux_atlas_based_connectivity.rst.txt new file mode 100644 index 00000000..1f8e195a --- /dev/null +++ b/docs/build/html/_sources/auto_examples/connectivity/plot_destriux_atlas_based_connectivity.rst.txt @@ -0,0 +1,107 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "auto_examples/connectivity/plot_destriux_atlas_based_connectivity.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_auto_examples_connectivity_plot_destriux_atlas_based_connectivity.py: + + +============= +Plot Destriux Atlas +============= + +Read grouped aparc labels from yaml file. + +Plot grouped connectivity circle with these grouped labels +for the Destriux atlas. + +.. GENERATED FROM PYTHON SOURCE LINES 13-36 + + + +.. image-sg:: /auto_examples/connectivity/images/sphx_glr_plot_destriux_atlas_based_connectivity_001.png + :alt: plot destriux atlas based connectivity + :srcset: /auto_examples/connectivity/images/sphx_glr_plot_destriux_atlas_based_connectivity_001.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + +
+ + + + + +| + +.. code-block:: default + + + import os.path as op + from jumeg import get_jumeg_path + from jumeg.connectivity import (plot_grouped_connectivity_circle, + generate_random_connectivity_matrix) + import yaml + + grouping_yaml_fname = op.join(get_jumeg_path(), 'data/destriux_aparc_cortex_based_grouping.yaml') + label_names_yaml_fname = op.join(get_jumeg_path(), 'data/destriux_label_names.yaml') + + with open(label_names_yaml_fname, 'r') as f: + label_names = yaml.safe_load(f)['label_names'] + + # make a random matrix with 148 nodes + con = generate_random_connectivity_matrix(size=(148, 148), symmetric=True) + con[con < 0.5] = 0. + + # plot grouped connnectivity + plot_grouped_connectivity_circle(grouping_yaml_fname, con, label_names, + labels_mode=None, colorbar_pos=(0.1, 0.1), + replacer_dict=None, + out_fname='fig_destriux_circle.png', + n_lines=50, colorbar=True) + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** ( 0 minutes 1.830 seconds) + + +.. _sphx_glr_download_auto_examples_connectivity_plot_destriux_atlas_based_connectivity.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + + + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_destriux_atlas_based_connectivity.py ` + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_destriux_atlas_based_connectivity.ipynb ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/build/html/_sources/auto_examples/connectivity/plot_generate_surrogate_connectivity.rst.txt b/docs/build/html/_sources/auto_examples/connectivity/plot_generate_surrogate_connectivity.rst.txt new file mode 100644 index 00000000..02fe6720 --- /dev/null +++ b/docs/build/html/_sources/auto_examples/connectivity/plot_generate_surrogate_connectivity.rst.txt @@ -0,0 +1,992 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "auto_examples/connectivity/plot_generate_surrogate_connectivity.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_auto_examples_connectivity_plot_generate_surrogate_connectivity.py: + + +Surrogate computation + +.. GENERATED FROM PYTHON SOURCE LINES 5-120 + + + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + Opening raw data file /Users/praveen.sripad/nanna_data/mne_data/MNE-sample-data/MEG/sample/sample_audvis_filt-0-40_raw.fif... + Read a total of 4 projection items: + PCA-v1 (1 x 102) idle + PCA-v2 (1 x 102) idle + PCA-v3 (1 x 102) idle + Average EEG reference (1 x 60) idle + Range : 6450 ... 48149 = 42.956 ... 320.665 secs + Ready. + Reading inverse operator decomposition from /Users/praveen.sripad/nanna_data/mne_data/MNE-sample-data/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif... + Reading inverse operator info... + [done] + Reading inverse operator decomposition... + [done] + 305 x 305 full covariance (kind = 1) found. + Read a total of 4 projection items: + PCA-v1 (1 x 102) active + PCA-v2 (1 x 102) active + PCA-v3 (1 x 102) active + Average EEG reference (1 x 60) active + Noise covariance matrix read. + 22494 x 22494 diagonal covariance (kind = 2) found. + Source covariance matrix read. + 22494 x 22494 diagonal covariance (kind = 6) found. + Orientation priors read. + 22494 x 22494 diagonal covariance (kind = 5) found. + Depth priors read. + Did not find the desired covariance matrix (kind = 3) + Reading a source space... + Computing patch statistics... + Patch information added... + Distance information added... + [done] + Reading a source space... + Computing patch statistics... + Patch information added... + Distance information added... + [done] + 2 source spaces read + Read a total of 4 projection items: + PCA-v1 (1 x 102) active + PCA-v2 (1 x 102) active + PCA-v3 (1 x 102) active + Average EEG reference (1 x 60) active + Source spaces transformed to the inverse solution coordinate frame + Not setting metadata + 72 matching events found + Setting baseline interval to [-0.19979521315838786, 0.0] s + Applying baseline correction (mode: mean) + Created an SSP operator (subspace dimension = 3) + 4 projection items activated + Preparing the inverse operator for use... + Scaled noise and source covariance from nave = 1 to nave = 1 + Created the regularized inverter + Created an SSP operator (subspace dimension = 3) + Created the whitener using a noise covariance matrix with rank 302 (3 small eigenvalues omitted) + Computing noise-normalization factors (dSPM)... + [done] + Picked 305 channels from the data + Computing inverse... + Eigenleads need to be weighted ... + Processing epoch : 1 / 72 (at most) + Processing epoch : 2 / 72 (at most) + Processing epoch : 3 / 72 (at most) + Processing epoch : 4 / 72 (at most) + Processing epoch : 5 / 72 (at most) + Processing epoch : 6 / 72 (at most) + Processing epoch : 7 / 72 (at most) + Processing epoch : 8 / 72 (at most) + Processing epoch : 9 / 72 (at most) + Processing epoch : 10 / 72 (at most) + Processing epoch : 11 / 72 (at most) + Processing epoch : 12 / 72 (at most) + Processing epoch : 13 / 72 (at most) + Processing epoch : 14 / 72 (at most) + Processing epoch : 15 / 72 (at most) + Processing epoch : 16 / 72 (at most) + Processing epoch : 17 / 72 (at most) + Processing epoch : 18 / 72 (at most) + Processing epoch : 19 / 72 (at most) + Processing epoch : 20 / 72 (at most) + Processing epoch : 21 / 72 (at most) + Processing epoch : 22 / 72 (at most) + Processing epoch : 23 / 72 (at most) + Processing epoch : 24 / 72 (at most) + Processing epoch : 25 / 72 (at most) + Processing epoch : 26 / 72 (at most) + Processing epoch : 27 / 72 (at most) + Processing epoch : 28 / 72 (at most) + Rejecting epoch based on MAG : ['MEG 1711'] + Processing epoch : 29 / 72 (at most) + Processing epoch : 30 / 72 (at most) + Processing epoch : 31 / 72 (at most) + Processing epoch : 32 / 72 (at most) + Processing epoch : 33 / 72 (at most) + Processing epoch : 34 / 72 (at most) + Processing epoch : 35 / 72 (at most) + Processing epoch : 36 / 72 (at most) + Processing epoch : 37 / 72 (at most) + Processing epoch : 38 / 72 (at most) + Processing epoch : 39 / 72 (at most) + Processing epoch : 40 / 72 (at most) + Processing epoch : 41 / 72 (at most) + Processing epoch : 42 / 72 (at most) + Processing epoch : 43 / 72 (at most) + Processing epoch : 44 / 72 (at most) + Processing epoch : 45 / 72 (at most) + Processing epoch : 46 / 72 (at most) + Processing epoch : 47 / 72 (at most) + Processing epoch : 48 / 72 (at most) + Processing epoch : 49 / 72 (at most) + Processing epoch : 50 / 72 (at most) + Processing epoch : 51 / 72 (at most) + Processing epoch : 52 / 72 (at most) + Processing epoch : 53 / 72 (at most) + Processing epoch : 54 / 72 (at most) + Processing epoch : 55 / 72 (at most) + Processing epoch : 56 / 72 (at most) + Processing epoch : 57 / 72 (at most) + Processing epoch : 58 / 72 (at most) + Processing epoch : 59 / 72 (at most) + Processing epoch : 60 / 72 (at most) + Processing epoch : 61 / 72 (at most) + Processing epoch : 62 / 72 (at most) + Processing epoch : 63 / 72 (at most) + Processing epoch : 64 / 72 (at most) + Processing epoch : 65 / 72 (at most) + Processing epoch : 66 / 72 (at most) + Processing epoch : 67 / 72 (at most) + Processing epoch : 68 / 72 (at most) + Processing epoch : 69 / 72 (at most) + Processing epoch : 70 / 72 (at most) + Processing epoch : 71 / 72 (at most) + [done] + Reading labels from parcellation... + read 34 labels from /Users/praveen.sripad/nanna_data/mne_data/MNE-sample-data/subjects/sample/label/lh.aparc.annot + read 34 labels from /Users/praveen.sripad/nanna_data/mne_data/MNE-sample-data/subjects/sample/label/rh.aparc.annot + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Extracting time courses for 68 labels (mode: mean_flip) + Connectivity computation... + only using indices for lower-triangular matrix + computing connectivity for 2278 connections + using t=0.000s..0.699s for estimation (106 points) + frequencies: 8.5Hz..12.7Hz (4 points) + connectivity scores will be averaged for each band + using FFT with a Hanning window to estimate spectra + the following metrics will be computed: Coherence, PLV, WPLI + computing connectivity for epochs 1..4 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 5..8 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 9..12 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 13..16 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 17..20 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 21..24 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 25..28 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 29..32 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 33..36 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 37..40 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 41..44 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 45..48 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 49..52 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 53..56 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 57..60 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 61..64 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 65..68 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 69..71 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 3 out of 3 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 3 out of 3 | elapsed: 0.0s finished + assembling connectivity matrix + [Connectivity computation done] + computing surrogate 0 + Connectivity computation... + only using indices for lower-triangular matrix + computing connectivity for 2278 connections + using t=0.000s..0.699s for estimation (106 points) + frequencies: 8.5Hz..12.7Hz (4 points) + connectivity scores will be averaged for each band + using FFT with a Hanning window to estimate spectra + the following metrics will be computed: Coherence, PLV, WPLI + computing connectivity for epochs 1..4 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 5..8 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 9..12 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 13..16 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 17..20 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 21..24 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 25..28 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 29..32 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 33..36 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 37..40 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 41..44 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 45..48 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 49..52 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 53..56 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 57..60 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 61..64 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 65..68 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 69..71 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 3 out of 3 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 3 out of 3 | elapsed: 0.0s finished + assembling connectivity matrix + [Connectivity computation done] + computing surrogate 1 + Connectivity computation... + only using indices for lower-triangular matrix + computing connectivity for 2278 connections + using t=0.000s..0.699s for estimation (106 points) + frequencies: 8.5Hz..12.7Hz (4 points) + connectivity scores will be averaged for each band + using FFT with a Hanning window to estimate spectra + the following metrics will be computed: Coherence, PLV, WPLI + computing connectivity for epochs 1..4 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 5..8 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 9..12 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 13..16 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 17..20 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 21..24 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 25..28 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 29..32 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 33..36 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 37..40 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 41..44 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 45..48 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 49..52 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 53..56 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 57..60 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 61..64 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 65..68 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 69..71 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 3 out of 3 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 3 out of 3 | elapsed: 0.0s finished + assembling connectivity matrix + [Connectivity computation done] + computing surrogate 2 + Connectivity computation... + only using indices for lower-triangular matrix + computing connectivity for 2278 connections + using t=0.000s..0.699s for estimation (106 points) + frequencies: 8.5Hz..12.7Hz (4 points) + connectivity scores will be averaged for each band + using FFT with a Hanning window to estimate spectra + the following metrics will be computed: Coherence, PLV, WPLI + computing connectivity for epochs 1..4 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 5..8 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 9..12 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 13..16 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 17..20 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 21..24 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 25..28 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 29..32 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 33..36 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 37..40 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 41..44 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 45..48 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 49..52 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 53..56 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 57..60 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 61..64 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 65..68 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 69..71 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 3 out of 3 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 3 out of 3 | elapsed: 0.0s finished + assembling connectivity matrix + [Connectivity computation done] + computing surrogate 3 + Connectivity computation... + only using indices for lower-triangular matrix + computing connectivity for 2278 connections + using t=0.000s..0.699s for estimation (106 points) + frequencies: 8.5Hz..12.7Hz (4 points) + connectivity scores will be averaged for each band + using FFT with a Hanning window to estimate spectra + the following metrics will be computed: Coherence, PLV, WPLI + computing connectivity for epochs 1..4 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 5..8 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 9..12 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 13..16 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 17..20 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 21..24 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 25..28 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 29..32 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 33..36 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 37..40 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 41..44 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 45..48 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 49..52 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 53..56 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 57..60 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 61..64 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 65..68 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 69..71 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 3 out of 3 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 3 out of 3 | elapsed: 0.0s finished + assembling connectivity matrix + [Connectivity computation done] + computing surrogate 4 + Connectivity computation... + only using indices for lower-triangular matrix + computing connectivity for 2278 connections + using t=0.000s..0.699s for estimation (106 points) + frequencies: 8.5Hz..12.7Hz (4 points) + connectivity scores will be averaged for each band + using FFT with a Hanning window to estimate spectra + the following metrics will be computed: Coherence, PLV, WPLI + computing connectivity for epochs 1..4 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 5..8 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 9..12 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 13..16 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 17..20 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 21..24 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 25..28 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 29..32 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 33..36 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 37..40 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 41..44 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 45..48 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 49..52 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 53..56 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 57..60 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 61..64 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 65..68 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.0s finished + computing connectivity for epochs 69..71 + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 3 out of 3 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 3 out of 3 | elapsed: 0.0s finished + assembling connectivity matrix + [Connectivity computation done] + + + + + + +| + +.. code-block:: default + + + import os.path as op + import numpy as np + import matplotlib.pyplot as pl + + import mne + from mne_connectivity import spectral_connectivity_epochs + from mne.datasets import sample + from mne.minimum_norm import read_inverse_operator, apply_inverse_epochs + + from jumeg.jumeg_surrogates import Surrogates + + data_path = sample.data_path() + subjects_dir = op.join(data_path, 'subjects') + + fname_inv = op.join(data_path, 'MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif') + fname_raw = op.join(data_path, 'MEG/sample/sample_audvis_filt-0-40_raw.fif') + fname_event = op.join(data_path, 'MEG/sample/sample_audvis_filt-0-40_raw-eve.fif') + + raw = mne.io.read_raw_fif(fname_raw) + events = mne.read_events(fname_event) + inverse_operator = read_inverse_operator(fname_inv) + + # add a bad channel + raw.info['bads'] += ['MEG 2443'] + + # pick MEG channels + picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=False, eog=False, + exclude='bads') + + # Define epochs for left-auditory condition + event_id, tmin, tmax = 1, -0.2, 0.5 + epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks, + baseline=(None, 0), reject=dict(mag=4e-12, grad=4000e-13)) + + snr = 1.0 # use lower SNR for single epochs + lambda2 = 1.0 / snr ** 2 + method = "dSPM" # use dSPM method (could also be MNE or sLORETA) + stcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, method, + pick_ori="normal", return_generator=False) + + # get labels for FreeSurfer 'aparc' cortical parcellation with 34 labels/hemi + labels = mne.read_labels_from_annot('sample', parc='aparc', + subjects_dir=subjects_dir) + label_colors = [label.color for label in labels] + + # average the source estimates within each label using sign-flips to reduce + # signal cancellations, also here we can return a generator + src = inverse_operator['src'] + label_ts = mne.extract_label_time_course(stcs, labels, src, mode='mean_flip', + return_generator=False) + + # compute surrogates on the first STC extracted for 68 labels + n_surr = 5 + fmin = 8. + fmax = 13. + sfreq = raw.info['sfreq'] # the sampling frequency + con_methods = ['coh', 'plv', 'wpli'] + n_rois = len(labels) + full_surr_con = np.zeros((3, n_rois, n_rois, 1, n_surr)) + + real_con = spectral_connectivity_epochs( + label_ts, method=con_methods, mode='fourier', sfreq=sfreq, + fmin=fmin, fmax=fmax, faverage=True, n_jobs=4) + + # get the data from SpectralConnectivity object and expand it + real_con = np.array([c.get_data(output='dense') for c in real_con]) + + # loop through each of the label_ts from each epoch (i.e. 71) + # for my_label_ts in label_ts: + surr_ts = Surrogates(np.array(label_ts)) + surr_ts.original_data.shape + surr_label_ts = surr_ts.compute_surrogates(n_surr=n_surr, + return_generator=True) + + for ind_surr, surr in enumerate(surr_label_ts): + con = spectral_connectivity_epochs( + surr, method=con_methods, mode='fourier', sfreq=sfreq, + fmin=fmin, fmax=fmax, faverage=True, n_jobs=4) + + con = np.array([c.get_data(output='dense') for c in con]) + + # con now a list of arrays + # con shape (method, n_signals, n_signals, n_freqs) + full_surr_con[:, :, :, :, ind_surr] = con + assert full_surr_con.flatten().max() <= 1., 'Maximum connectivity is above 1.' + assert full_surr_con.flatten().min() >= 0., 'Minimum connectivity is 0.' + + surr_ts.clear_cache() + + # visualize the surrogates + # pl.plot(label_ts[0][0, :], 'b') + # for lts in surr_label_ts: + # pl.plot(lts[0, :], 'r') + # pl.title('Extracted label time courses - real vs surrogates') + # pl.show() + + + def sanity_check_con_matrix(con): + ''' + Check if the connectivity matrix provided satisfies necessary conditions. + This is done to ensure that the data remains clean and spurious values are + easily detected. + Expected a connectivity matrix of shape + (n_methods x n_rois x n_rois x n_freqs x n_surr) + ''' + n_methods, n_rois, n_rois, n_freqs, n_surr = con.shape + assert np.any(con), 'Matrix is not all zeros.' + assert not (con == con[0]).all(), 'All rows are equal - methods not different.' + for surr in range(1, n_surr): + assert not (con[:, :, :, :, surr] == con[:, :, :, :, 0]).all(), 'All surrogates are equal.' + assert not np.triu(con[0, :, :, 0, surr]).any(), 'Matrices not symmetric.' + + + sanity_check_con_matrix(full_surr_con) + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** ( 0 minutes 3.075 seconds) + + +.. _sphx_glr_download_auto_examples_connectivity_plot_generate_surrogate_connectivity.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + + + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_generate_surrogate_connectivity.py ` + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_generate_surrogate_connectivity.ipynb ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/build/html/_sources/auto_examples/connectivity/plot_generate_surrogate_stcs.rst.txt b/docs/build/html/_sources/auto_examples/connectivity/plot_generate_surrogate_stcs.rst.txt new file mode 100644 index 00000000..2bbc1a9b --- /dev/null +++ b/docs/build/html/_sources/auto_examples/connectivity/plot_generate_surrogate_stcs.rst.txt @@ -0,0 +1,285 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "auto_examples/connectivity/plot_generate_surrogate_stcs.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_auto_examples_connectivity_plot_generate_surrogate_stcs.py: + + +============= +Generate surrogate STCs +============= + + +Example to show surrogate generation on STCs using the jumeg Surrogates +module. + +.. GENERATED FROM PYTHON SOURCE LINES 12-72 + + + +.. image-sg:: /auto_examples/connectivity/images/sphx_glr_plot_generate_surrogate_stcs_001.png + :alt: Averaged real vs surrogate source time courses + :srcset: /auto_examples/connectivity/images/sphx_glr_plot_generate_surrogate_stcs_001.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + Opening raw data file /Users/praveen.sripad/nanna_data/mne_data/MNE-sample-data/MEG/sample/sample_audvis_filt-0-40_raw.fif... + Read a total of 4 projection items: + PCA-v1 (1 x 102) idle + PCA-v2 (1 x 102) idle + PCA-v3 (1 x 102) idle + Average EEG reference (1 x 60) idle + Range : 6450 ... 48149 = 42.956 ... 320.665 secs + Ready. + Reading inverse operator decomposition from /Users/praveen.sripad/nanna_data/mne_data/MNE-sample-data/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif... + Reading inverse operator info... + [done] + Reading inverse operator decomposition... + [done] + 305 x 305 full covariance (kind = 1) found. + Read a total of 4 projection items: + PCA-v1 (1 x 102) active + PCA-v2 (1 x 102) active + PCA-v3 (1 x 102) active + Average EEG reference (1 x 60) active + Noise covariance matrix read. + 22494 x 22494 diagonal covariance (kind = 2) found. + Source covariance matrix read. + 22494 x 22494 diagonal covariance (kind = 6) found. + Orientation priors read. + 22494 x 22494 diagonal covariance (kind = 5) found. + Depth priors read. + Did not find the desired covariance matrix (kind = 3) + Reading a source space... + Computing patch statistics... + Patch information added... + Distance information added... + [done] + Reading a source space... + Computing patch statistics... + Patch information added... + Distance information added... + [done] + 2 source spaces read + Read a total of 4 projection items: + PCA-v1 (1 x 102) active + PCA-v2 (1 x 102) active + PCA-v3 (1 x 102) active + Average EEG reference (1 x 60) active + Source spaces transformed to the inverse solution coordinate frame + Not setting metadata + 72 matching events found + Setting baseline interval to [-0.19979521315838786, 0.0] s + Applying baseline correction (mode: mean) + Created an SSP operator (subspace dimension = 3) + 4 projection items activated + Preparing the inverse operator for use... + Scaled noise and source covariance from nave = 1 to nave = 1 + Created the regularized inverter + Created an SSP operator (subspace dimension = 3) + Created the whitener using a noise covariance matrix with rank 302 (3 small eigenvalues omitted) + Computing noise-normalization factors (dSPM)... + [done] + Picked 305 channels from the data + Computing inverse... + Eigenleads need to be weighted ... + Processing epoch : 1 / 72 (at most) + Processing epoch : 2 / 72 (at most) + Processing epoch : 3 / 72 (at most) + Processing epoch : 4 / 72 (at most) + Processing epoch : 5 / 72 (at most) + Processing epoch : 6 / 72 (at most) + Processing epoch : 7 / 72 (at most) + Processing epoch : 8 / 72 (at most) + Processing epoch : 9 / 72 (at most) + Processing epoch : 10 / 72 (at most) + Processing epoch : 11 / 72 (at most) + Processing epoch : 12 / 72 (at most) + Processing epoch : 13 / 72 (at most) + Processing epoch : 14 / 72 (at most) + Processing epoch : 15 / 72 (at most) + Processing epoch : 16 / 72 (at most) + Processing epoch : 17 / 72 (at most) + Processing epoch : 18 / 72 (at most) + Processing epoch : 19 / 72 (at most) + Processing epoch : 20 / 72 (at most) + Processing epoch : 21 / 72 (at most) + Processing epoch : 22 / 72 (at most) + Processing epoch : 23 / 72 (at most) + Processing epoch : 24 / 72 (at most) + Processing epoch : 25 / 72 (at most) + Processing epoch : 26 / 72 (at most) + Processing epoch : 27 / 72 (at most) + Processing epoch : 28 / 72 (at most) + Rejecting epoch based on MAG : ['MEG 1711'] + Processing epoch : 29 / 72 (at most) + Processing epoch : 30 / 72 (at most) + Processing epoch : 31 / 72 (at most) + Processing epoch : 32 / 72 (at most) + Processing epoch : 33 / 72 (at most) + Processing epoch : 34 / 72 (at most) + Processing epoch : 35 / 72 (at most) + Processing epoch : 36 / 72 (at most) + Processing epoch : 37 / 72 (at most) + Processing epoch : 38 / 72 (at most) + Processing epoch : 39 / 72 (at most) + Processing epoch : 40 / 72 (at most) + Processing epoch : 41 / 72 (at most) + Processing epoch : 42 / 72 (at most) + Processing epoch : 43 / 72 (at most) + Processing epoch : 44 / 72 (at most) + Processing epoch : 45 / 72 (at most) + Processing epoch : 46 / 72 (at most) + Processing epoch : 47 / 72 (at most) + Processing epoch : 48 / 72 (at most) + Processing epoch : 49 / 72 (at most) + Processing epoch : 50 / 72 (at most) + Processing epoch : 51 / 72 (at most) + Processing epoch : 52 / 72 (at most) + Processing epoch : 53 / 72 (at most) + Processing epoch : 54 / 72 (at most) + Processing epoch : 55 / 72 (at most) + Processing epoch : 56 / 72 (at most) + Processing epoch : 57 / 72 (at most) + Processing epoch : 58 / 72 (at most) + Processing epoch : 59 / 72 (at most) + Processing epoch : 60 / 72 (at most) + Processing epoch : 61 / 72 (at most) + Processing epoch : 62 / 72 (at most) + Processing epoch : 63 / 72 (at most) + Processing epoch : 64 / 72 (at most) + Processing epoch : 65 / 72 (at most) + Processing epoch : 66 / 72 (at most) + Processing epoch : 67 / 72 (at most) + Processing epoch : 68 / 72 (at most) + Processing epoch : 69 / 72 (at most) + Processing epoch : 70 / 72 (at most) + Processing epoch : 71 / 72 (at most) + [done] + computing surrogate 0 + computing surrogate 1 + computing surrogate 2 + computing surrogate 3 + computing surrogate 4 + computing surrogate 5 + computing surrogate 6 + computing surrogate 7 + computing surrogate 8 + computing surrogate 9 + + + + + + +| + +.. code-block:: default + + + import os.path as op + import numpy as np + import matplotlib.pyplot as pl + + from mne.datasets import sample + from mne.minimum_norm import read_inverse_operator, apply_inverse_epochs + import mne + + from jumeg.jumeg_surrogates import Surrogates, check_power_spectrum + + data_path = sample.data_path() + subjects_dir = op.join(data_path, 'subjects') + + fname_inv = op.join(data_path, 'MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif') + fname_raw = op.join(data_path, 'MEG/sample/sample_audvis_filt-0-40_raw.fif') + fname_event = op.join(data_path, 'MEG/sample/sample_audvis_filt-0-40_raw-eve.fif') + + stcs_testing = True + + raw = mne.io.read_raw_fif(fname_raw) + events = mne.read_events(fname_event) + inverse_operator = read_inverse_operator(fname_inv) + + # add a bad channel + raw.info['bads'] += ['MEG 2443'] + + # pick MEG channels + picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=False, eog=False, + exclude='bads') + + # define epochs for left-auditory condition + event_id, tmin, tmax = 1, -0.2, 0.5 + epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks, + baseline=(None, 0), reject=dict(mag=4e-12, grad=4000e-13)) + + + snr = 1.0 # use lower SNR for single epochs + lambda2 = 1.0 / snr ** 2 + method = "dSPM" # use dSPM method (could also be MNE or sLORETA) + stcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, method, + pick_ori="normal", return_generator=False) + + # compute surrogates for one STC + surr_stcs = Surrogates(stcs[0]) + mysurr = surr_stcs.compute_surrogates(n_surr=10, return_generator=False) + + # check if surrogates are correctly computed + assert not np.array_equal(mysurr[0].data, + mysurr[1].data), 'Surrogates mostly equal' + assert not np.array_equal(stcs[0].data, + mysurr[2].data), 'Surrogates equal to original' + + # visualize results by plotting 1 the average across voxels + # of original and surrogate STC + pl.plot(stcs[0].data.mean(axis=0)) + for i in mysurr: + pl.plot(i.data.mean(axis=0), color='r') + pl.title('Averaged real vs surrogate source time courses') + pl.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** ( 0 minutes 2.492 seconds) + + +.. _sphx_glr_download_auto_examples_connectivity_plot_generate_surrogate_stcs.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + + + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_generate_surrogate_stcs.py ` + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_generate_surrogate_stcs.ipynb ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/build/html/_sources/auto_examples/connectivity/plot_generic_grouped_connectivity_circle.rst.txt b/docs/build/html/_sources/auto_examples/connectivity/plot_generic_grouped_connectivity_circle.rst.txt new file mode 100644 index 00000000..7d872c48 --- /dev/null +++ b/docs/build/html/_sources/auto_examples/connectivity/plot_generic_grouped_connectivity_circle.rst.txt @@ -0,0 +1,116 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "auto_examples/connectivity/plot_generic_grouped_connectivity_circle.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_auto_examples_connectivity_plot_generic_grouped_connectivity_circle.py: + + +============= +Generic Grouped Connectivity Circle +============= + +Script exposing circle plots with outer ring. + +Author: Praveen Sripad + +.. GENERATED FROM PYTHON SOURCE LINES 13-44 + + + +.. rst-class:: sphx-glr-horizontal + + + * + + .. image-sg:: /auto_examples/connectivity/images/sphx_glr_plot_generic_grouped_connectivity_circle_001.png + :alt: Groups + :srcset: /auto_examples/connectivity/images/sphx_glr_plot_generic_grouped_connectivity_circle_001.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /auto_examples/connectivity/images/sphx_glr_plot_generic_grouped_connectivity_circle_002.png + :alt: Groups + Labels + :srcset: /auto_examples/connectivity/images/sphx_glr_plot_generic_grouped_connectivity_circle_002.png + :class: sphx-glr-multi-img + + + + + +.. code-block:: default + + import os.path as op + from jumeg.connectivity import (plot_generic_grouped_circle, + plot_fica_grouped_circle, + generate_random_connectivity_matrix) + from jumeg import get_jumeg_path + + # load the yaml grouping of Freesurfer labels + yaml_fname = op.join(get_jumeg_path(), 'data/rsn_desikan_aparc_cortex_grouping.yaml') + + # make a random matrix + con = generate_random_connectivity_matrix(size=(34, 34), symmetric=True) + + # load the label names in the original order + # this should be same order as the connectivity matrix + labels_fname = op.join(get_jumeg_path(), 'data/fica_names.txt') + with open(labels_fname, 'r') as f: + orig_labels = [line.rstrip('\n') for line in f] + + # plot the connectivity circle grouped + plot_generic_grouped_circle(yaml_fname, con, orig_labels, + node_order_size=34, + out_fname='fig_fica_circle.png', + show=False, n_lines=20, + title='Groups') + + # plot the connectivity circle with outer group labels ring + plot_fica_grouped_circle(yaml_fname, con, orig_labels, + node_order_size=34, + out_fname='fig_fica_circle_with_names.png', + show=False, n_lines=20, + title='Groups + Labels') + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** ( 0 minutes 1.585 seconds) + + +.. _sphx_glr_download_auto_examples_connectivity_plot_generic_grouped_connectivity_circle.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + + + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_generic_grouped_connectivity_circle.py ` + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_generic_grouped_connectivity_circle.ipynb ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/build/html/_sources/auto_examples/connectivity/plot_grouped_connectivity_circle.rst.txt b/docs/build/html/_sources/auto_examples/connectivity/plot_grouped_connectivity_circle.rst.txt new file mode 100644 index 00000000..7b6be8c6 --- /dev/null +++ b/docs/build/html/_sources/auto_examples/connectivity/plot_grouped_connectivity_circle.rst.txt @@ -0,0 +1,131 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "auto_examples/connectivity/plot_grouped_connectivity_circle.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_auto_examples_connectivity_plot_grouped_connectivity_circle.py: + + +============= +Plot grouped connectivity circle. +============= + +Example showing how to read grouped aparc labels from yaml file and plot +grouped connectivity circle with these labels. + +Author: Praveen Sripad + Christian Kiefer + +.. GENERATED FROM PYTHON SOURCE LINES 15-49 + + + +.. rst-class:: sphx-glr-horizontal + + + * + + .. image-sg:: /auto_examples/connectivity/images/sphx_glr_plot_grouped_connectivity_circle_001.png + :alt: plot grouped connectivity circle + :srcset: /auto_examples/connectivity/images/sphx_glr_plot_grouped_connectivity_circle_001.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /auto_examples/connectivity/images/sphx_glr_plot_grouped_connectivity_circle_002.png + :alt: plot grouped connectivity circle + :srcset: /auto_examples/connectivity/images/sphx_glr_plot_grouped_connectivity_circle_002.png + :class: sphx-glr-multi-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + +
+ + + + + +| + +.. code-block:: default + + import os.path as op + from jumeg import get_jumeg_path + from jumeg.connectivity import (plot_grouped_connectivity_circle, + generate_random_connectivity_matrix) + import yaml + + labels_fname = get_jumeg_path() + '/data/desikan_label_names.yaml' + yaml_cortex_fname = get_jumeg_path() + '/data/desikan_aparc_cortex_based_grouping.yaml' + yaml_cluster_fname = get_jumeg_path() + '/data/desikan_aparc_cluster_based_grouping_example.yaml' + replacer_dict_fname = get_jumeg_path() + '/data/replacer_dictionaries.yaml' + + with open(labels_fname, 'r') as f: + label_names = yaml.safe_load(f)['label_names'] + + with open(replacer_dict_fname, 'r') as f: + replacer_dict = yaml.safe_load(f)['replacer_dict_aparc'] + + # make a random matrix with 68 nodes + con = generate_random_connectivity_matrix(size=(68, 68), symmetric=True) + + # plot simple connectivity circle with cortex based grouping and colors + plot_grouped_connectivity_circle(yaml_cortex_fname, con, label_names, + labels_mode='replace', replacer_dict=replacer_dict, + out_fname='fig_grouped_con_circle_cortex.png', + colorbar_pos=(0.1, 0.1), n_lines=10, colorbar=True, + colormap='viridis') + + # plot connectivity circle with cluster-based grouping but same node colors as above + plot_grouped_connectivity_circle(yaml_cluster_fname, con, label_names, + labels_mode=None, replacer_dict=None, + yaml_color_fname=yaml_cortex_fname, + out_fname='fig_grouped_con_circle_cluster.png', + colorbar_pos=(0.1, 0.1), n_lines=10, colorbar=True, + colormap='viridis') + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** ( 0 minutes 2.186 seconds) + + +.. _sphx_glr_download_auto_examples_connectivity_plot_grouped_connectivity_circle.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + + + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_grouped_connectivity_circle.py ` + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_grouped_connectivity_circle.ipynb ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/build/html/_sources/auto_examples/connectivity/plot_label_distances.rst.txt b/docs/build/html/_sources/auto_examples/connectivity/plot_label_distances.rst.txt new file mode 100644 index 00000000..58772361 --- /dev/null +++ b/docs/build/html/_sources/auto_examples/connectivity/plot_label_distances.rst.txt @@ -0,0 +1,156 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "auto_examples/connectivity/plot_label_distances.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_auto_examples_connectivity_plot_label_distances.py: + + +========== +Plot label distances +========== + +Script to plot label distances on circle and connectome plots. + +.. GENERATED FROM PYTHON SOURCE LINES 10-71 + + + +.. rst-class:: sphx-glr-horizontal + + + * + + .. image-sg:: /auto_examples/connectivity/images/sphx_glr_plot_label_distances_001.png + :alt: plot label distances + :srcset: /auto_examples/connectivity/images/sphx_glr_plot_label_distances_001.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /auto_examples/connectivity/images/sphx_glr_plot_label_distances_002.png + :alt: plot label distances + :srcset: /auto_examples/connectivity/images/sphx_glr_plot_label_distances_002.png + :class: sphx-glr-multi-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + Reading labels from parcellation... + read 34 labels from /Users/praveen.sripad/nanna_data/mne_data/MNE-sample-data/subjects/sample/label/lh.aparc.annot + read 34 labels from /Users/praveen.sripad/nanna_data/mne_data/MNE-sample-data/subjects/sample/label/rh.aparc.annot + + + + + + +| + +.. code-block:: default + + + import os.path as op + + import mne + from mne.datasets import sample + from mne_connectivity import degree + + from jumeg import get_jumeg_path + from jumeg.connectivity import (get_label_distances, + plot_grouped_connectivity_circle) + import yaml + + from nilearn import plotting + + data_path = sample.data_path() + subjects_dir = op.join(data_path, 'subjects') + subject = 'sample' + + parc = 'aparc' + + yaml_cortex_fname = op.join(get_jumeg_path(), 'data/desikan_%s_cortex_based_grouping.yaml' % parc) + + labels_fname = op.join(get_jumeg_path(), 'data/desikan_label_names.yaml') + with open(labels_fname, 'r') as f: + label_names = yaml.safe_load(f)['label_names'] + + replacer_dict_fname = op.join(get_jumeg_path(), 'data/replacer_dictionaries.yaml') + with open(replacer_dict_fname, 'r') as f: + replacer_dict = yaml.safe_load(f)['replacer_dict_%s' % parc] + + # compute distances between center of masses (COMs) of the labels + # we also get the MNI coordinates of the COMs in millimetres + con, coords, _, _ = get_label_distances(subject, subjects_dir, parc=parc) + + # forget long range connections, plot short neighbouring connections + neighbor_range = 30. # millimetres + con[con > neighbor_range] = 0. + + cortex_colors = ['m', 'b', 'y', 'c', 'r', 'g', + 'g', 'r', 'c', 'y', 'b', 'm'] + + out_fname = 'fig_label_com_distances_circle_%0.1f_%s.png' % (neighbor_range, parc) + plot_grouped_connectivity_circle(yaml_cortex_fname, con, label_names, + replacer_dict=replacer_dict, + yaml_color_fname=None, labels_mode='replace', + cortex_colors=cortex_colors, + out_fname=out_fname, colorbar_pos=(0.1, 0.1), + n_lines=None, colorbar=True, + colormap='Reds') + + # compute the degree + degs = degree(con, threshold_prop=1) + + # show the label ROIs and short range connections using nilearn glass brain + fig = plotting.plot_connectome(con, coords, node_size=degs, + edge_threshold='99%', + node_color='cornflowerblue', + display_mode='ortho', + title='%s' % parc) + + fig.savefig('fig_%s_labels_distance_degrees.png' % parc) + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** ( 0 minutes 1.941 seconds) + + +.. _sphx_glr_download_auto_examples_connectivity_plot_label_distances.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + + + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_label_distances.py ` + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_label_distances.ipynb ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/build/html/_sources/auto_examples/connectivity/plot_labelled_connectivity_circle.rst.txt b/docs/build/html/_sources/auto_examples/connectivity/plot_labelled_connectivity_circle.rst.txt new file mode 100644 index 00000000..a7eae4f0 --- /dev/null +++ b/docs/build/html/_sources/auto_examples/connectivity/plot_labelled_connectivity_circle.rst.txt @@ -0,0 +1,95 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "auto_examples/connectivity/plot_labelled_connectivity_circle.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_auto_examples_connectivity_plot_labelled_connectivity_circle.py: + + +========== +Plot labelled connectivity circle +========== + +Example exposing the plot_labelled_group_connectivity_circle function. + +Author: Praveen Sripad + +.. GENERATED FROM PYTHON SOURCE LINES 13-35 + + + +.. image-sg:: /auto_examples/connectivity/images/sphx_glr_plot_labelled_connectivity_circle_001.png + :alt: test RSN circ labels + :srcset: /auto_examples/connectivity/images/sphx_glr_plot_labelled_connectivity_circle_001.png + :class: sphx-glr-single-img + + + + + +.. code-block:: default + + import os.path as op + from jumeg.connectivity import (plot_labelled_group_connectivity_circle, + generate_random_connectivity_matrix) + from jumeg import get_jumeg_path + import yaml + + # load the yaml grouping of Freesurfer labels + yaml_fname = op.join(get_jumeg_path(), 'data/rsn_desikan_aparc_cortex_grouping.yaml') + label_names_yaml_fname = op.join(get_jumeg_path(), 'data/desikan_label_names.yaml') + + with open(label_names_yaml_fname, 'r') as f: + label_names = yaml.safe_load(f)['label_names'] + + # make a random matrix with 68 nodes + con = generate_random_connectivity_matrix(size=(68, 68), symmetric=True) + + # plotting within a subplot + plot_labelled_group_connectivity_circle(yaml_fname, con, label_names, + out_fname='fig_rsn_circle.png', + show=False, n_lines=20, + fontsize_names=6, + title='test RSN circ labels') + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** ( 0 minutes 0.575 seconds) + + +.. _sphx_glr_download_auto_examples_connectivity_plot_labelled_connectivity_circle.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + + + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_labelled_connectivity_circle.py ` + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_labelled_connectivity_circle.ipynb ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/build/html/_sources/auto_examples/connectivity/plot_shuffle_time_slices.rst.txt b/docs/build/html/_sources/auto_examples/connectivity/plot_shuffle_time_slices.rst.txt new file mode 100644 index 00000000..c763f5cd --- /dev/null +++ b/docs/build/html/_sources/auto_examples/connectivity/plot_shuffle_time_slices.rst.txt @@ -0,0 +1,209 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "auto_examples/connectivity/plot_shuffle_time_slices.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_auto_examples_connectivity_plot_shuffle_time_slices.py: + + +==================================================== +Shuffle channels' data in the time domain and plot. +==================================================== + +.. GENERATED FROM PYTHON SOURCE LINES 6-69 + + + +.. rst-class:: sphx-glr-horizontal + + + * + + .. image-sg:: /auto_examples/connectivity/images/sphx_glr_plot_shuffle_time_slices_001.png + :alt: Gradiometers, Magnetometers + :srcset: /auto_examples/connectivity/images/sphx_glr_plot_shuffle_time_slices_001.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /auto_examples/connectivity/images/sphx_glr_plot_shuffle_time_slices_002.png + :alt: Gradiometers, Magnetometers + :srcset: /auto_examples/connectivity/images/sphx_glr_plot_shuffle_time_slices_002.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /auto_examples/connectivity/images/sphx_glr_plot_shuffle_time_slices_003.png + :alt: Gradiometers, Magnetometers + :srcset: /auto_examples/connectivity/images/sphx_glr_plot_shuffle_time_slices_003.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /auto_examples/connectivity/images/sphx_glr_plot_shuffle_time_slices_004.png + :alt: Gradiometers, Magnetometers + :srcset: /auto_examples/connectivity/images/sphx_glr_plot_shuffle_time_slices_004.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /auto_examples/connectivity/images/sphx_glr_plot_shuffle_time_slices_005.png + :alt: Gradiometers, Magnetometers + :srcset: /auto_examples/connectivity/images/sphx_glr_plot_shuffle_time_slices_005.png + :class: sphx-glr-multi-img + + * + + .. image-sg:: /auto_examples/connectivity/images/sphx_glr_plot_shuffle_time_slices_006.png + :alt: Gradiometers, Magnetometers + :srcset: /auto_examples/connectivity/images/sphx_glr_plot_shuffle_time_slices_006.png + :class: sphx-glr-multi-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + Opening raw data file /Users/praveen.sripad/nanna_data/mne_data/MNE-sample-data/MEG/sample/sample_audvis_raw.fif... + Read a total of 3 projection items: + PCA-v1 (1 x 102) idle + PCA-v2 (1 x 102) idle + PCA-v3 (1 x 102) idle + Range : 25800 ... 192599 = 42.956 ... 320.670 secs + Ready. + Reading 0 ... 166799 = 0.000 ... 277.714 secs... + Opening raw data file /Users/praveen.sripad/nanna_data/mne_data/MNE-sample-data/MEG/sample/sample_audvis_raw.fif,tperm-raw.fif... + Read a total of 3 projection items: + PCA-v1 (1 x 102) idle + PCA-v2 (1 x 102) idle + PCA-v3 (1 x 102) idle + Range : 25800 ... 192599 = 42.956 ... 320.670 secs + Ready. + Reading 0 ... 166799 = 0.000 ... 277.714 secs... + NOTE: plot_psd() is a legacy function. New code should use .compute_psd().plot(). + Effective window size : 3.410 (s) + NOTE: plot_psd() is a legacy function. New code should use .compute_psd().plot(). + Effective window size : 3.410 (s) + NOTE: plot_psd() is a legacy function. New code should use .compute_psd().plot(). + Effective window size : 3.410 (s) + NOTE: plot_psd() is a legacy function. New code should use .compute_psd().plot(). + Effective window size : 3.410 (s) + NOTE: plot_psd() is a legacy function. New code should use .compute_psd().plot(). + Effective window size : 3.410 (s) + NOTE: plot_psd() is a legacy function. New code should use .compute_psd().plot(). + Effective window size : 3.410 (s) + + + + + + +| + +.. code-block:: default + + # Author: Eberhard Eich + # Praveen Sripad + # + # License: BSD (3-clause) + + import os.path as op + import numpy as np + + import mne + from mne.datasets import sample + + from jumeg.jumeg_utils import (get_files_from_list, time_shuffle_slices, + channel_indices_from_list) + + data_path = sample.data_path() + raw_fname = op.join(data_path, 'MEG/sample/sample_audvis_raw.fif') + + # shuffle all MEG channels that begin with number 11 + shflchanlist = ['MEG 11..'] + + # shuffle the whole length of the data + tmin, tmax = 0., None + + # apply the shuffling + # time_shuffle_slices(raw_fname, shufflechans=shflchanlist, tmin=tmin, tmax=tmax) + + plot_things = True + if plot_things: + permname = op.join(op.dirname(raw_fname), + op.basename(raw_fname).split('-')[0]) + ',tperm-raw.fif' + + rawraw = mne.io.Raw(raw_fname,preload=True) + shflpick = channel_indices_from_list(rawraw.info['ch_names'][:], + shflchanlist) + procdperm = mne.io.Raw(permname, preload=True) + + figraw = rawraw.plot_psd(fmin=0., fmax=300., tmin=0., color=(1,0,0), picks=shflpick) + axisraw = figraw.gca() + axisraw.set_ylim([-300., -250.]) + # procdnr.plot_psd(fmin=0.,fmax=300., color=(0,0,1), picks=shflpick) + figshfl = procdperm.plot_psd(fmin=0., fmax=300., tmin=0., color=(1,0,0), picks=shflpick) + axisshfl = figshfl.gca() + axisshfl.set_ylim([-300., -250.]) + + megpick = mne.pick_types(rawraw.info, meg=True, ref_meg=False, eeg=False, eog=False, stim=False) + + figraw1 = rawraw.plot_psd(fmin=0., fmax=300., tmin=0., color=(0,0,1), picks=megpick) + axisraw1 = figraw1.gca() + axisraw1.set_ylim([-300., -250.]) + + figshfl1 = procdperm.plot_psd(fmin=0., fmax=300., tmin=0., color=(0,0,1), picks=megpick) + axisshfl1 = figshfl1.gca() + axisshfl1.set_ylim([-300., -250.]) + + megnochgpick = np.setdiff1d(megpick, shflpick) + + figraw2 = rawraw.plot_psd(fmin=0., fmax=300., tmin=0., color=(0,1,0), picks=megnochgpick) + axisraw2 = figraw2.gca() + axisraw2.set_ylim([-300., -250.]) + + figshfl2 = procdperm.plot_psd(fmin=0., fmax=300., tmin=0., color=(0,1,0), picks=megnochgpick) + axisshfl2 = figshfl2.gca() + axisshfl2.set_ylim([-300., -250.]) + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** ( 0 minutes 5.027 seconds) + + +.. _sphx_glr_download_auto_examples_connectivity_plot_shuffle_time_slices.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + + + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_shuffle_time_slices.py ` + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_shuffle_time_slices.ipynb ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/build/html/_sources/auto_examples/connectivity/plot_simulated_connectivity.rst.txt b/docs/build/html/_sources/auto_examples/connectivity/plot_simulated_connectivity.rst.txt new file mode 100644 index 00000000..7bc4e33f --- /dev/null +++ b/docs/build/html/_sources/auto_examples/connectivity/plot_simulated_connectivity.rst.txt @@ -0,0 +1,258 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "auto_examples/connectivity/plot_simulated_connectivity.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_auto_examples_connectivity_plot_simulated_connectivity.py: + + +========== +Simulating Connectivity +========== + +Simple implementations of connectivity measures. + +.. GENERATED FROM PYTHON SOURCE LINES 10-186 + + + +.. image-sg:: /auto_examples/connectivity/images/sphx_glr_plot_simulated_connectivity_001.png + :alt: plot simulated connectivity + :srcset: /auto_examples/connectivity/images/sphx_glr_plot_simulated_connectivity_001.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + /Users/praveen.sripad/miniconda3/envs/jumeg/lib/python3.9/site-packages/matplotlib/cbook/__init__.py:1335: ComplexWarning: Casting complex values to real discards the imaginary part + return np.asarray(x, float) + + + + + + +| + +.. code-block:: default + + + # Authors : pravsripad@gmail.com + # daniel.vandevelden@yahoo.de + + import os.path as op + import sys + import numpy as np + import matplotlib.pyplot as pl + import matplotlib.mlab as mlab + + n_epochs = 120 + sfreq, duration = 1000., 1000 + times = np.arange(0, duration, 1 / sfreq) + amp , amp2 , nse_amp = 1., 1., 0.5 + nfft = 512 + + nse1 = np.random.rand(times.size) * nse_amp + nse2 = np.random.rand(times.size) * nse_amp + x = amp * np.sin(2 * np.pi * 200 * times) + nse1 + y = amp * np.sin(2 * np.pi * 200 * times + np.pi/5) + nse2 + + shift = 100 # integer + assert shift < sfreq * duration, 'Choose a smaller shift.' + #y = amp2 * np.roll(x, shift) + nse2 + + # coherence using mlab function + cohxy, freqs = mlab.cohere(x, y, Fs=sfreq, NFFT=nfft) + + n_freqs = int(nfft/2 + 1) + + def compute_mean_psd_csd(x, y, n_epochs, nfft, sfreq): + '''Computes mean of PSD and CSD for signals.''' + x2 = np.array_split(x, n_epochs) + y2 = np.array_split(y, n_epochs) + + Rxy = np.zeros((n_epochs, n_freqs), dtype=complex) + Rxx = np.zeros((n_epochs, n_freqs), dtype=complex) + Ryy = np.zeros((n_epochs, n_freqs), dtype=complex) + + for i in range(n_epochs): + Rxy[i], freqs = mlab.csd(x2[i], y2[i], NFFT=nfft, Fs=sfreq) + Rxx[i], _ = mlab.psd(x2[i], NFFT=nfft, Fs=sfreq) + Ryy[i], _ = mlab.psd(y2[i], NFFT=nfft, Fs=sfreq) + + Rxy_mean = np.mean(Rxy, axis=0) + Rxx_mean = np.mean(Rxx, axis=0) + Ryy_mean = np.mean(Ryy, axis=0) + + return freqs, Rxy, Rxy_mean, np.real(Rxx_mean), np.real(Ryy_mean) + + def my_coherence(n_freqs, Rxy_mean, Rxx_mean, Ryy_mean): + ''' Computes coherence. ''' + + coh = np.zeros((n_freqs)) + for i in range(0, n_freqs): + coh[i] = np.abs(Rxy_mean[i]) / np.sqrt(Rxx_mean[i] * Ryy_mean[i]) + + return coh + + def my_imcoh(n_freqs, Rxy_mean, Rxx_mean, Ryy_mean): + ''' Computes imaginary coherence. ''' + + imcoh = np.zeros((n_freqs)) + for i in range(0, n_freqs): + imcoh[i] = np.imag(Rxy_mean[i]) / np.sqrt(Rxx_mean[i] * Ryy_mean[i]) + + return imcoh + + def my_cohy(n_freqs, Rxy_mean, Rxx_mean, Ryy_mean): + ''' Computes coherency. ''' + + cohy = np.zeros((n_freqs)) + for i in range(0, n_freqs): + cohy[i] = np.real(Rxy_mean[i]) / np.sqrt(Rxx_mean[i] * Ryy_mean[i]) + + return cohy + + def my_plv(n_freqs, Rxy, Rxy_mean): + ''' Computes PLV. ''' + + Rxy_plv = np.zeros((n_epochs, n_freqs), dtype=complex) + for i in range(0, n_epochs): + Rxy_plv[i] = Rxy[i] / np.abs(Rxy[i]) + + plv = np.abs(np.mean(Rxy_plv, axis=0)) + return plv + + def my_pli(n_freqs, Rxy, Rxy_mean): + ''' Computes PLI. ''' + Rxy_pli = np.zeros((n_epochs, n_freqs), dtype=complex) + for i in range(0, n_epochs): + Rxy_pli[i] = np.sign(np.imag(Rxy[i])) + + pli = np.abs(np.mean(Rxy_pli, axis=0)) + return pli + + def my_wpli(n_freqs, Rxy, Rxy_mean): + ''' Computes WPLI. ''' + Rxy_wpli_1 = np.zeros((n_epochs, n_freqs), dtype=complex) + Rxy_wpli_2 = np.zeros((n_epochs, n_freqs), dtype=complex) + for i in range(0, n_epochs): + Rxy_wpli_1[i] = np.imag(Rxy[i]) + Rxy_wpli_2[i] = np.abs(np.imag(Rxy[i])) + + # handle divide by zero + denom = np.mean(Rxy_wpli_2, axis=0) + idx_denom = np.where(denom == 0.) + denom[idx_denom] = 1. + wpli = np.abs(np.mean(Rxy_wpli_1, axis=0)) / denom + wpli[idx_denom] = 0. + return wpli + + + def my_con(x, y, n_epochs, nfft, sfreq, con_name='coh'): + '''Computes connectivity measure mentioned on provided signal pair and its surrogates.''' + + freqs, Rxy, Rxy_mean, Rxx_mean, Ryy_mean = compute_mean_psd_csd(x, y, n_epochs, nfft, sfreq) + + # compute surrogates + x_surr = x.copy() + y_surr = y.copy() + np.random.shuffle(x_surr) + np.random.shuffle(y_surr) + freqs_surro, Rxy_s, Rxy_s_mean, Rxx_s_mean, Ryy_s_mean = compute_mean_psd_csd(x_surr, y_surr, n_epochs, nfft, sfreq) + + if con_name == 'coh': + coh = my_coherence(n_freqs, Rxy_mean, Rxx_mean, Ryy_mean) + coh_surro = my_coherence(n_freqs, Rxy_s_mean, Rxx_s_mean, Ryy_s_mean) + return coh, coh_surro, freqs, freqs_surro + + if con_name == 'imcoh': + imcoh = my_imcoh(n_freqs, Rxy_mean, Rxx_mean, Ryy_mean) + imcoh_surro = my_imcoh(n_freqs, Rxy_s_mean, Rxx_s_mean, Ryy_s_mean) + return imcoh, imcoh_surro, freqs, freqs_surro + + if con_name == 'cohy': + cohy = my_cohy(n_freqs, Rxy_mean, Rxx_mean, Ryy_mean) + cohy_surro = my_cohy(n_freqs, Rxy_s_mean, Rxx_s_mean, Ryy_s_mean) + return cohy, cohy_surro, freqs, freqs_surro + + if con_name == 'plv': + plv = my_plv(n_freqs, Rxy, Rxy_mean) + plv_surro = my_plv(n_freqs, Rxy_s, Rxy_s_mean) + return plv, plv_surro, freqs, freqs_surro + + if con_name == 'pli': + pli = my_pli(n_freqs, Rxy, Rxy_mean) + pli_surro = my_pli(n_freqs, Rxy_s, Rxy_s_mean) + return pli, pli_surro, freqs, freqs_surro + + if con_name == 'wpli': + wpli = my_wpli(n_freqs, Rxy, Rxy_mean) + wpli_surro = my_wpli(n_freqs, Rxy_s, Rxy_s_mean) + return wpli, wpli_surro, freqs, freqs_surro + + if con_name == '': + print('Please provide the connectivity method to use.') + sys.exit() + else: + print('Connectivity method unrecognized.') + sys.exit() + + con_name = 'wpli' + con, con_surro, freqs, freqs_surro = my_con(x, y, n_epochs, nfft, sfreq, con_name) + + # coherence using mlab function + #cohxy, freqs = mlab.cohere(x, y, Fs=sfreq, NFFT=nfft) + #pl.plot(freqs, cohxy) + + # plot results + pl.figure('Connectivity') + pl.plot(freqs, con) + pl.plot(freqs_surro, con_surro) + pl.legend(['Con', 'Surrogates']) + pl.tight_layout() + pl.show() + + +.. rst-class:: sphx-glr-timing + + **Total running time of the script:** ( 0 minutes 0.242 seconds) + + +.. _sphx_glr_download_auto_examples_connectivity_plot_simulated_connectivity.py: + +.. only:: html + + .. container:: sphx-glr-footer sphx-glr-footer-example + + + + + .. container:: sphx-glr-download sphx-glr-download-python + + :download:`Download Python source code: plot_simulated_connectivity.py ` + + .. container:: sphx-glr-download sphx-glr-download-jupyter + + :download:`Download Jupyter notebook: plot_simulated_connectivity.ipynb ` + + +.. only:: html + + .. rst-class:: sphx-glr-signature + + `Gallery generated by Sphinx-Gallery `_ diff --git a/docs/build/html/_sources/auto_examples/connectivity/plot_standard_resting_network_on_aparc_annot_map.rst.txt b/docs/build/html/_sources/auto_examples/connectivity/plot_standard_resting_network_on_aparc_annot_map.rst.txt new file mode 100644 index 00000000..7290fa1a --- /dev/null +++ b/docs/build/html/_sources/auto_examples/connectivity/plot_standard_resting_network_on_aparc_annot_map.rst.txt @@ -0,0 +1,283 @@ + +.. DO NOT EDIT. +.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. +.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: +.. "auto_examples/connectivity/plot_standard_resting_network_on_aparc_annot_map.py" +.. LINE NUMBERS ARE GIVEN BELOW. + +.. only:: html + + .. note:: + :class: sphx-glr-download-link-note + + :ref:`Go to the end ` + to download the full example code + +.. rst-class:: sphx-glr-example-title + +.. _sphx_glr_auto_examples_connectivity_plot_standard_resting_network_on_aparc_annot_map.py: + + +========== +Standard RSNs on the connectivity circle +========== + +Plot the visualization of the standard resting state network on the +connectivity circle plot showing the Freesurfer aparc annotation map. + +This provides a quick visualization of the primary connections of the standard +resting state network. + +Uses the standard RSNs provided by [1] +[1] P. Garcés, M. C. Martín-Buro, and F. Maestú, +“Quantifying the Test-Retest Reliability of Magnetoencephalography +Resting-State Functional Connectivity,” Brain Connect., vol. 6, no. 6, +pp. 448–460, 2016. + +Author: Praveen Sripad + +.. GENERATED FROM PYTHON SOURCE LINES 23-109 + + + +.. image-sg:: /auto_examples/connectivity/images/sphx_glr_plot_standard_resting_network_on_aparc_annot_map_001.png + :alt: plot standard resting network on aparc annot map + :srcset: /auto_examples/connectivity/images/sphx_glr_plot_standard_resting_network_on_aparc_annot_map_001.png + :class: sphx-glr-single-img + + +.. rst-class:: sphx-glr-script-out + + .. code-block:: none + + Visual Left visual cortex : [-41 -77 3] lh Closest vertex on surface chosen: [6708] + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s finished + Right visual cortex : [ 41 -72 1] rh Closest vertex on surface chosen: [10095] + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s finished + Sensorimotor Left primary somatosensory cortex : [-38 -27 52] lh Closest vertex on surface chosen: [62711] + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s finished + Right primary somatosensory cortex : [ 40 -25 50] rh Closest vertex on surface chosen: [71297] + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s finished + Auditory Left primary auditory cortex : [-55 -21 7] lh Closest vertex on surface chosen: [72410] + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s finished + Right primary auditory cortex : [ 57 -20 7] rh Closest vertex on surface chosen: [76848] + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s finished + DMN Precuneus : [ 1 -57 28] lh Closest vertex on surface chosen: [29030] + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s finished + Left inferior parietal : [-45 -65 30] lh Closest vertex on surface chosen: [15645] + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s finished + Right inferior parietal : [ 52 -60 26] rh Closest vertex on surface chosen: [26366] + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s finished + Anterior cingulate : [ 2 42 7] lh Closest vertex on surface chosen: [155310] + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s finished + Left FP Left angular gyrus : [-40 -58 56] lh Closest vertex on surface chosen: [24630] + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s finished + Left middle frontal gyrus : [-42 28 23] lh Closest vertex on surface chosen: [126993] + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s finished + Right FP Right angular gyrus : [ 53 -50 43] rh Closest vertex on surface chosen: [38519] + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s finished + Right middle frontal gyrus : [45 28 26] rh Closest vertex on surface chosen: [130082] + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s finished + Frontoinsular Left insula : [-38 16 2] lh Closest vertex on surface chosen: [115415] + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s finished + Right insula : [38 16 2] rh Closest vertex on surface chosen: [119046] + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s finished + Median cingulate : [-2 12 40] lh Closest vertex on surface chosen: [110618] + [Parallel(n_jobs=4)]: Using backend LokyBackend with 4 concurrent workers. + [Parallel(n_jobs=4)]: Done 2 out of 4 | elapsed: 0.0s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s remaining: 0.0s + [Parallel(n_jobs=4)]: Done 4 out of 4 | elapsed: 0.1s finished + Reading labels from parcellation... + read 34 labels from /Users/praveen.sripad/nanna_data/mne_data/MNE-sample-data/subjects/sample/label/lh.aparc.annot + read 34 labels from /Users/praveen.sripad/nanna_data/mne_data/MNE-sample-data/subjects/sample/label/rh.aparc.annot + Left: Visual_Left visual cortex-lh [6708]