Skip to content
Snippets Groups Projects
Commit 000db917 authored by Jan Caron's avatar Jan Caron
Browse files

Setup and many smaller things!

conf.py: uncommented path  finding for sphinx to find docs folder.
index.rst: Added modules.rst as an overview.
make.bat, Makefile, pyramid.rst: Deleted!
utils: put many functions in convenience.py
environment.py: Added stuff for documentation
README.md: deleted badges (directly on GitLab now!)
setup.py: Further streamline!
parent e471a8c9
No related branches found
No related tags found
No related merge requests found
......@@ -7,3 +7,6 @@ desktop.ini
*.DS_Store
*.DS
*.ipynb_checkpoints*
build/*
docs/api/*
dist/*
[![build status](https://iffgit.fz-juelich.de/caron/Pyramid/badges/master/build.svg)] (https://iffgit.fz-juelich.de/caron/Pyramid/commits/master) [![coverage report](https://iffgit.fz-juelich.de/caron/Pyramid/badges/master/coverage.svg)](https://iffgit.fz-juelich.de/caron/Pyramid/commits/master)
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = .build
# 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
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@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 " applehelp to make an Apple Help Book"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " epub3 to make an epub3"
@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 " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
@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 " xml to make Docutils-native XML files"
@echo " pseudoxml to make pseudoxml-XML files for display purposes"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
@echo " coverage to run coverage check of the documentation (if enabled)"
@echo " dummy to check syntax errors of document sources"
.PHONY: clean
clean:
rm -rf $(BUILDDIR)/*
.PHONY: html
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
.PHONY: dirhtml
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
.PHONY: singlehtml
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
.PHONY: pickle
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
.PHONY: json
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
.PHONY: htmlhelp
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."
.PHONY: qthelp
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/Pyramid.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Pyramid.qhc"
.PHONY: applehelp
applehelp:
$(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp
@echo
@echo "Build finished. The help book is in $(BUILDDIR)/applehelp."
@echo "N.B. You won't be able to view it unless you put it in" \
"~/Library/Documentation/Help or install it in your application" \
"bundle."
.PHONY: devhelp
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/Pyramid"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Pyramid"
@echo "# devhelp"
.PHONY: epub
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
.PHONY: epub3
epub3:
$(SPHINXBUILD) -b epub3 $(ALLSPHINXOPTS) $(BUILDDIR)/epub3
@echo
@echo "Build finished. The epub3 file is in $(BUILDDIR)/epub3."
.PHONY: latex
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)."
.PHONY: latexpdf
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."
.PHONY: latexpdfja
latexpdfja:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through platex and dvipdfmx..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
.PHONY: text
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
.PHONY: man
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
.PHONY: texinfo
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)."
.PHONY: info
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."
.PHONY: gettext
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
.PHONY: changes
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
.PHONY: linkcheck
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."
.PHONY: doctest
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
.PHONY: coverage
coverage:
$(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage
@echo "Testing of coverage in the sources finished, look at the " \
"results in $(BUILDDIR)/coverage/python.txt."
.PHONY: xml
xml:
$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
@echo
@echo "Build finished. The XML files are in $(BUILDDIR)/xml."
.PHONY: pseudoxml
pseudoxml:
$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
@echo
@echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
.PHONY: dummy
dummy:
$(SPHINXBUILD) -b dummy $(ALLSPHINXOPTS) $(BUILDDIR)/dummy
@echo
@echo "Build finished. Dummy builder generates no files."
......@@ -17,9 +17,9 @@
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))
import os
import sys
sys.path.insert(0, os.path.abspath('..'))
# -- General configuration ------------------------------------------------
......@@ -34,8 +34,8 @@ extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.coverage',
'sphinx.ext.mathjax',
'sphinx.ext.autosummary',
'numpydoc'
'sphinx.ext.autosummary',
'numpydoc'
]
numpydoc_show_class_members = False
......@@ -120,7 +120,7 @@ pygments_style = 'sphinx'
# keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
todo_include_todos = True
# -- Options for HTML output ----------------------------------------------
......@@ -247,21 +247,21 @@ htmlhelp_basename = 'Pyramiddoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
......@@ -309,10 +309,7 @@ latex_documents = [
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'pyramid', 'Pyramid Documentation',
[author], 1)
]
man_pages = [(master_doc, 'pyramid', 'Pyramid Documentation', [author], 1)]
# If true, show URL addresses after external links.
#
......@@ -447,12 +444,10 @@ epub_exclude_files = ['search.html']
# would mean that specific document would be compressed
# regardless of the global pdf_compressed setting.
pdf_documents = [
('index', u'Pyramid', u'Pyramid', u'Jan Caron'),
]
pdf_documents = [('index', u'Pyramid', u'Pyramid', u'Jan Caron')]
# A comma-separated list of custom stylesheets. Example:
pdf_stylesheets = ['sphinx','kerning','a4']
pdf_stylesheets = ['sphinx', 'kerning', 'a4']
# A list of folders to search for stylesheets. Example:
pdf_style_path = ['.', '_styles']
......@@ -460,65 +455,65 @@ pdf_style_path = ['.', '_styles']
# Create a compressed PDF
# Use True/False or 1/0
# Example: compressed=True
#pdf_compressed = False
# pdf_compressed = False
# A colon-separated list of folders to search for fonts. Example:
# pdf_font_path = ['/usr/share/fonts', '/usr/share/texmf-dist/fonts/']
# Language to be used for hyphenation support
#pdf_language = "en_US"
# pdf_language = "en_US"
# Mode for literal blocks wider than the frame. Can be
# overflow, shrink or truncate
#pdf_fit_mode = "shrink"
# pdf_fit_mode = "shrink"
# Section level that forces a break page.
# For example: 1 means top-level sections start in a new page
# 0 means disabled
#pdf_break_level = 0
# pdf_break_level = 0
# When a section starts in a new page, force it to be 'even', 'odd',
# or just use 'any'
#pdf_breakside = 'any'
# pdf_breakside = 'any'
# Insert footnotes where they are defined instead of
# at the end.
#pdf_inline_footnotes = True
# pdf_inline_footnotes = True
# verbosity level. 0 1 or 2
#pdf_verbosity = 0
# pdf_verbosity = 0
# If false, no index is generated.
#pdf_use_index = True
# pdf_use_index = True
# If false, no modindex is generated.
#pdf_use_modindex = True
# pdf_use_modindex = True
# If false, no coverpage is generated.
#pdf_use_coverpage = True
# pdf_use_coverpage = True
# Name of the cover page template to use
#pdf_cover_template = 'sphinxcover.tmpl'
# pdf_cover_template = 'sphinxcover.tmpl'
# Documents to append as an appendix to all manuals.
#pdf_appendices = []
# pdf_appendices = []
# Enable experimental feature to split table cells. Use it
# if you get "DelayedTable too big" errors
#pdf_splittables = False
# pdf_splittables = False
# Set the default DPI for images
#pdf_default_dpi = 72
# pdf_default_dpi = 72
# Enable rst2pdf extension modules (default is only vectorpdf)
# you need vectorpdf if you want to use sphinx's graphviz support
#pdf_extensions = ['vectorpdf']
# pdf_extensions = ['vectorpdf']
# Page template name for "regular" pages
#pdf_page_template = 'cutePage'
# pdf_page_template = 'cutePage'
# Show Table Of Contents at the beginning?
#pdf_use_toc = True
# pdf_use_toc = True
# How many levels deep should the table of contents be?
pdf_toc_depth = 9999
......
.. Pyramid documentation master file, created by
sphinx-quickstart on Thu Feb 25 19:34:18 2016.
.. Pyramid documentation master file, created by sphinx-quickstart on Thu Feb 25 19:34:18 2016.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
......@@ -8,10 +7,13 @@ Welcome to Pyramid's documentation!
Contents:
Modules
=======
.. toctree::
:maxdepth: 4
pyramid.rst
api/modules
Indices and tables
......
@ECHO OFF
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set BUILDDIR=.build
set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .
set I18NSPHINXOPTS=%SPHINXOPTS% .
if NOT "%PAPER%" == "" (
set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
)
if "%1" == "" goto help
if "%1" == "help" (
:help
echo.Please use `make ^<target^>` where ^<target^> is one of
echo. html to make standalone HTML files
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. epub3 to make an epub3
echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
echo. text to make text files
echo. man to make manual pages
echo. texinfo to make Texinfo files
echo. gettext to make PO message catalogs
echo. changes to make an overview over all changed/added/deprecated items
echo. xml to make Docutils-native XML files
echo. pseudoxml to make pseudoxml-XML files for display purposes
echo. linkcheck to check all external links for integrity
echo. doctest to run all doctests embedded in the documentation if enabled
echo. coverage to run coverage check of the documentation if enabled
echo. dummy to check syntax errors of document sources
goto end
)
if "%1" == "clean" (
for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
del /q /s %BUILDDIR%\*
goto end
)
REM Check if sphinx-build is available and fallback to Python version if any
%SPHINXBUILD% 1>NUL 2>NUL
if errorlevel 9009 goto sphinx_python
goto sphinx_ok
:sphinx_python
set SPHINXBUILD=python -m sphinx.__init__
%SPHINXBUILD% 2> nul
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.http://sphinx-doc.org/
exit /b 1
)
:sphinx_ok
if "%1" == "html" (
%SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/html.
goto end
)
if "%1" == "dirhtml" (
%SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
goto end
)
if "%1" == "singlehtml" (
%SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
goto end
)
if "%1" == "pickle" (
%SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the pickle files.
goto end
)
if "%1" == "json" (
%SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the JSON files.
goto end
)
if "%1" == "htmlhelp" (
%SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run HTML Help Workshop with the ^
.hhp project file in %BUILDDIR%/htmlhelp.
goto end
)
if "%1" == "qthelp" (
%SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run "qcollectiongenerator" with the ^
.qhcp project file in %BUILDDIR%/qthelp, like this:
echo.^> qcollectiongenerator %BUILDDIR%\qthelp\Pyramid.qhcp
echo.To view the help file:
echo.^> assistant -collectionFile %BUILDDIR%\qthelp\Pyramid.ghc
goto end
)
if "%1" == "devhelp" (
%SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished.
goto end
)
if "%1" == "epub" (
%SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The epub file is in %BUILDDIR%/epub.
goto end
)
if "%1" == "epub3" (
%SPHINXBUILD% -b epub3 %ALLSPHINXOPTS% %BUILDDIR%/epub3
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The epub3 file is in %BUILDDIR%/epub3.
goto end
)
if "%1" == "latex" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
if errorlevel 1 exit /b 1
echo.
echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "latexpdf" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
cd %BUILDDIR%/latex
make all-pdf
cd %~dp0
echo.
echo.Build finished; the PDF files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "latexpdfja" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
cd %BUILDDIR%/latex
make all-pdf-ja
cd %~dp0
echo.
echo.Build finished; the PDF files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "text" (
%SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The text files are in %BUILDDIR%/text.
goto end
)
if "%1" == "man" (
%SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The manual pages are in %BUILDDIR%/man.
goto end
)
if "%1" == "texinfo" (
%SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
goto end
)
if "%1" == "gettext" (
%SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
goto end
)
if "%1" == "changes" (
%SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
if errorlevel 1 exit /b 1
echo.
echo.The overview file is in %BUILDDIR%/changes.
goto end
)
if "%1" == "linkcheck" (
%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
if errorlevel 1 exit /b 1
echo.
echo.Link check complete; look for any errors in the above output ^
or in %BUILDDIR%/linkcheck/output.txt.
goto end
)
if "%1" == "doctest" (
%SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
if errorlevel 1 exit /b 1
echo.
echo.Testing of doctests in the sources finished, look at the ^
results in %BUILDDIR%/doctest/output.txt.
goto end
)
if "%1" == "coverage" (
%SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage
if errorlevel 1 exit /b 1
echo.
echo.Testing of coverage in the sources finished, look at the ^
results in %BUILDDIR%/coverage/python.txt.
goto end
)
if "%1" == "xml" (
%SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The XML files are in %BUILDDIR%/xml.
goto end
)
if "%1" == "pseudoxml" (
%SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml.
goto end
)
if "%1" == "dummy" (
%SPHINXBUILD% -b dummy %ALLSPHINXOPTS% %BUILDDIR%/dummy
if errorlevel 1 exit /b 1
echo.
echo.Build finished. Dummy builder generates no files.
goto end
)
:end
pyramid Package
===============
:mod:`analytic` Module
----------------------
.. automodule:: pyramid.analytic
:members:
:show-inheritance:
:special-members:
:mod:`colormap` Module
--------------------------
.. automodule:: pyramid.colormap
:members:
:show-inheritance:
:special-members:
:mod:`costfunction` Module
--------------------------
.. automodule:: pyramid.costfunction
:members:
:show-inheritance:
:special-members:
:mod:`dataset` Module
---------------------
.. automodule:: pyramid.dataset
:members:
:show-inheritance:
:special-members:
:mod:`diagnostics` Module
--------------------------
.. automodule:: pyramid.diagnostics
:members:
:show-inheritance:
:special-members:
:mod:`fft` Module
--------------------------
.. automodule:: pyramid.fft
:members:
:show-inheritance:
:special-members:
:mod:`forwardmodel` Module
--------------------------
.. automodule:: pyramid.forwardmodel
:members:
:show-inheritance:
:special-members:
:mod:`kernel` Module
--------------------
.. automodule:: pyramid.kernel
:members:
:show-inheritance:
:special-members:
:mod:`magcreator` Module
------------------------
.. automodule:: pyramid.magcreator
:members:
:show-inheritance:
:special-members:
:mod:`magdata` Module
---------------------
.. automodule:: pyramid.magdata
:members:
:show-inheritance:
:special-members:
:mod:`phasemap` Module
----------------------
.. automodule:: pyramid.phasemap
:members:
:show-inheritance:
:special-members:
:mod:`phasemapper` Module
-------------------------
.. automodule:: pyramid.phasemapper
:members:
:show-inheritance:
:special-members:
:mod:`projector` Module
-----------------------
.. automodule:: pyramid.projector
:members:
:show-inheritance:
:special-members:
:mod:`quaternion` Module
----------------------------
.. automodule:: pyramid.quaternion
:members:
:show-inheritance:
:special-members:
:mod:`ramp` Module
----------------------------
.. automodule:: pyramid.ramp
:members:
:show-inheritance:
:special-members:
:mod:`reconstruction` Module
----------------------------
.. automodule:: pyramid.reconstruction
:members:
:show-inheritance:
:special-members:
:mod:`regularisator` Module
----------------------------
.. automodule:: pyramid.regularisator
:members:
:show-inheritance:
:special-members:
Subpackages
-----------
.. toctree::
pyramid.numcore
......@@ -14,6 +14,7 @@ channels:
dependencies:
# Basic:
- python=3.7
- setuptools
- numpy=1.16
- scipy=1.3
- tqdm=4.36
......@@ -35,6 +36,9 @@ dependencies:
- pytest-runner=5.1
- pytest-mpl=0.10 # Needed for testing hyperspy! # TODO: Use for pyramid/plotting library, too!
- coverage=4.5
# Documentation:
- sphinx=2.1
- numpydoc=0.9
# IPython and notebooks:
- ipython=7.7
- jupyter=1.0
......@@ -45,7 +49,7 @@ dependencies:
# TODO: ...because one is Unix, ond is Windows).
# Fast computation:
- pyFFTW=0.11
- pathos # pathos.multiprocessing uses dill instead of pickle (needed for class functions)
# TODO: ? - pathos # pathos.multiprocessing uses dill instead of pickle
# PIP installations:
- pip=19.0
# - pip:
......
......@@ -7,8 +7,8 @@
This module reconstructs 3-dimensional magnetic distributions (as
:class:`~pyramid.magdata.VectorData` objects) from a given set of phase maps (represented by
:class:`~pyramid.phasemap.PhaseMap` objects) by using several model based reconstruction algorithms
which use the forward model provided by :mod:`~pyramid.projector` and :mod:`~pyramid.phasemapper`
and a priori knowledge of the distribution.
which use the forward model provided by :mod:`~pyramid.projector` and :mod:`~pyramid.phasemapper`
and a priori knowledge of the distribution.
"""
......
......@@ -4,11 +4,10 @@
#
"""Subpackage containing Pyramid utility functions."""
from .pm import pm
from .reconstruction_2d_from_phasemap import reconstruction_2d_from_phasemap
from .reconstruction_2d_from_phasemap import reconstruction_2d_charge_from_phasemap
from .reconstruction_3d_from_magdata import reconstruction_3d_from_magdata
from .reconstruction_3d_from_magdata import reconstruction_3d_from_elecdata
from . import lorentz
from .convenience import (pm,
reconstruction_2d_from_phasemap, reconstruction_2d_charge_from_phasemap,
reconstruction_3d_from_magdata, reconstruction_3d_from_elecdata)
# from .phasemap_creator import gui_phasemap_creator
# from .mag_slicer import gui_mag_slicer
......
......@@ -2,27 +2,277 @@
# Copyright 2016 by Forschungszentrum Juelich GmbH
# Author: J. Caron
#
"""Reconstruct a magnetization distributions from phase maps created from it."""
"""Convenience function for phase mapping magnetic or charge distributions."""
import logging
import numpy as np
import multiprocessing as mp
from .. import reconstruction
from ..dataset import DataSet, DataSetCharge
from ..projector import XTiltProjector, YTiltProjector
from ..projector import XTiltProjector, YTiltProjector, RotTiltProjector, SimpleProjector
from ..ramp import Ramp
from ..regularisator import FirstOrderRegularisator, NoneRegularisator, ZeroOrderRegularisator
from ..forwardmodel import ForwardModel, DistributedForwardModel, ForwardModelCharge
from ..costfunction import Costfunction
from ..phasemapper import PhaseMapperRDFC, PhaseMapperCharge
from ..phasemapper import PhaseMapperRDFC, PhaseMapperFDFC, PhaseMapperCharge
from ..kernel import Kernel, KernelCharge
__all__ = ['reconstruction_3d_from_magdata', 'reconstruction_3d_from_elecdata']
__all__ = ['pm', 'reconstruction_2d_from_phasemap', 'reconstruction_2d_charge_from_phasemap',
'reconstruction_3d_from_magdata', 'reconstruction_3d_from_elecdata']
_log = logging.getLogger(__name__)
# TODO: rename magdata to vecdata everywhere!
def pm(fielddata, mode='z', b_0=1, electrode_vec=(1E6, 1E6), prw_vec=None, mapper='RDFC', **kwargs):
"""Convenience function for fast electric charge and magnetic phase mapping.
Parameters
----------
fielddata : :class:`~.VectorData`, or `~.ScalarData`
A :class:`~.VectorData` or `~.ScalarData` object, from which the projected phase map should
be calculated.
mode: {'z', 'y', 'x', 'x-tilt', 'y-tilt', 'rot-tilt'}, optional
Projection mode which determines the :class:`~.pyramid.projector.Projector` subclass, which
is used for the projection. Default is a simple projection along the `z`-direction.
b_0 : float, optional
Saturation magnetization in Tesla, which is used for the phase calculation. Default is 1.
electrode_vec : tuple of float (N=2)
The norm vector of the counter electrode, (elec_a,elec_b), and the distance to the origin is
the norm of (elec_a,elec_b). The default value is (1E6, 1E6).
prw_vec: tuple of 2 int, optional
A two-component vector describing the displacement of the reference wave to include
perturbation of this reference by the object itself (via fringing fields), (y, x).
mapper : :class: '~. PhaseMap'
A :class: '~. PhaseMap' object, which maps a fielddata into a phase map. The default
is 'RDFC'.
**kwargs : additional arguments
Additional arguments like `dim_uv`, 'tilt' or 'rotation', which are passed to the
projector-constructor, defined by the `mode`.
Returns
-------
phasemap : :class:`~pyramid.phasemap.PhaseMap`
The calculated phase map as a :class:`~.PhaseMap` object.
"""
_log.debug('Calling pm')
# In case of FDFC:
padding = kwargs.pop('padding', 0)
# Determine projection mode:
if mode == 'rot-tilt':
projector = RotTiltProjector(fielddata.dim, **kwargs)
elif mode == 'x-tilt':
projector = XTiltProjector(fielddata.dim, **kwargs)
elif mode == 'y-tilt':
projector = YTiltProjector(fielddata.dim, **kwargs)
elif mode in ['x', 'y', 'z']:
projector = SimpleProjector(fielddata.dim, axis=mode, **kwargs)
else:
raise ValueError("Invalid mode (use 'x', 'y', 'z', 'x-tilt', 'y-tilt' or 'rot-tilt')")
# Project:
field_proj = projector(fielddata)
# Set up phasemapper and map phase:
if mapper == 'RDFC':
phasemapper = PhaseMapperRDFC(Kernel(fielddata.a, projector.dim_uv, b_0=b_0))
elif mapper == 'FDFC':
phasemapper = PhaseMapperFDFC(fielddata.a, projector.dim_uv, b_0=b_0, padding=padding)
# Set up phasemapper and map phase:
elif mapper == 'Charge':
phasemapper = PhaseMapperCharge(KernelCharge(fielddata.a, projector.dim_uv,
electrode_vec=electrode_vec, prw_vec=prw_vec))
else:
raise ValueError("Invalid mapper (use 'RDFC', 'FDFC' or 'Charge'")
phasemap = phasemapper(field_proj)
# Get mask from fielddata:
phasemap.mask = field_proj.get_mask()[0, ...]
# Return phase:
return phasemap
def reconstruction_2d_from_phasemap(phasemap, b_0=1, lam=1E-3, max_iter=100, ramp_order=None,
plot_results=False, ar_dens=None, verbose=True):
"""Convenience function for reconstructing a projected distribution from a single phasemap.
Parameters
----------
phasemap: :class:`~PhaseMap`
The phasemap which is used for the reconstruction.
b_0 : float, optional
The magnetic induction corresponding to a magnetization :math:`M_{0}` in T.
The default is 1.
lam : float
Regularisation parameter determining the weighting between measurements and regularisation.
max_iter : int, optional
The maximum number of iterations for the opimization.
ramp_order : int or None (default)
Polynomial order of the additional phase ramp which will be added to the phase maps.
All ramp parameters have to be at the end of the input vector and are split automatically.
Default is None (no ramps are added).
plot_results: boolean, optional
If True, the results are plotted after reconstruction.
ar_dens: int, optional
Number defining the arrow density which is plotted. A higher ar_dens number skips more
arrows (a number of 2 plots every second arrow). Will be estimated if not provided.
verbose: bool, optional
If set to True, information like a progressbar is displayed during reconstruction.
The default is False.
Returns
-------
magdata_rec, cost: :class:`~.VectorData`, :class:`~.Costfunction`
The reconstructed magnetisation distribution and the used costfunction.
"""
_log.debug('Calling reconstruction_2d_from_phasemap')
# Construct DataSet, Regularisator, ForwardModel and Costfunction:
dim = (1,) + phasemap.dim_uv
data = DataSet(phasemap.a, dim, b_0)
data.append(phasemap, SimpleProjector(dim))
data.set_3d_mask()
fwd_model = ForwardModel(data, ramp_order)
reg = FirstOrderRegularisator(data.mask, lam, add_params=fwd_model.ramp.n)
cost = Costfunction(fwd_model, reg)
# Reconstruct:
magdata_rec = reconstruction.optimize_linear(cost, max_iter=max_iter, verbose=verbose)
param_cache = cost.fwd_model.ramp.param_cache
if ramp_order is None:
offset, ramp = 0, (0, 0)
elif ramp_order >= 1:
offset, ramp = param_cache[0][0], (param_cache[1][0], param_cache[2][0])
elif ramp_order == 0:
offset, ramp = param_cache[0][0], (0, 0)
else:
raise ValueError('ramp_order has to be a positive integer or None!')
# Plot stuff:
if plot_results:
if ar_dens is None:
ar_dens = np.max([1, np.max(dim) // 64])
magdata_rec.plot_quiver_field(note='Reconstructed Distribution',
ar_dens=ar_dens, figsize=(16, 16))
phasemap_rec = pm(magdata_rec)
gain = 4 * 2 * np.pi / (np.abs(phasemap_rec.phase).max() + 1E-30)
gain = round(gain, -int(np.floor(np.log10(abs(gain)))))
vmin = phasemap_rec.phase.min()
vmax = phasemap_rec.phase.max()
phasemap.plot_combined(note='Input Phase', gain=gain)
phasemap -= fwd_model.ramp(index=0)
phasemap.plot_combined(note='Input Phase (ramp corrected)', gain=gain, vmin=vmin, vmax=vmax)
title = 'Reconstructed Phase'
if ramp_order is not None:
if ramp_order >= 0:
print('offset:', offset)
# title += ', fitted Offset: {:.2g} [rad]'.format(offset)
if ramp_order >= 1:
print('ramp:', ramp)
# title += ', (Fitted Ramp: (u:{:.2g}, v:{:.2g}) [rad/nm]'.format(*ramp)
phasemap_rec.plot_combined(note=title, gain=gain, vmin=vmin, vmax=vmax)
diff = (phasemap_rec - phasemap)
diff_name = 'Difference (RMS: {:.2g} rad)'.format(np.sqrt(np.mean(diff.phase) ** 2))
diff.plot_phase_with_hist(note=diff_name, sigma_clip=3)
if ramp_order is not None:
ramp = fwd_model.ramp(0)
ramp.plot_phase(note='Fitted Ramp')
# Return reconstructed magnetisation distribution and cost function:
return magdata_rec, cost
def reconstruction_2d_charge_from_phasemap(phasemap, max_iter=1000, ramp_order=None, mask=None,
lam=None, electrode_vec=(1E6, 1E6), v_acc=300000, prw=None,
plot_results=False, verbose=True):
"""Convenience function for reconstructing a projected distribution from a single phasemap.
Parameters
----------
phasemap: :class:`~PhaseMap`
The phasemap which is used for the reconstruction.
max_iter : int, optional
The maximum number of iterations for the optimization.
ramp_order : int or None (default)
Polynomial order of the additional phase ramp which will be added to the phase maps.
All ramp parameters have to be at the end of the input vector and are split automatically.
Default is None (no ramps are added).
lam: float,
The zero order regularisator parameter. 'None' means no regularisator.
mask: ndarrary,
Define where situate the reconstructed charges
electrode_vec : tuple of float (N=2)
The norm vector of the counter electrode in pixels, (elec_a,elec_b), and the distance to the origin is
the norm of (elec_a,elec_b).
v_acc: float
The accelerating voltage of electrons.
prw: tuple of 2 int, optional
A two-component vector describing the displacement of the reference wave to include
perturbation of this reference by the object itself (via fringing fields), (y, x).
plot_results: boolean, optional
If True, the results are plotted after reconstruction.
verbose: bool, optional
If set to True, information like a progressbar is displayed during reconstruction.
The default is False.
Returns
-------
elecdata_rec, cost: :class:`~.ScalarData`, :class:`~.Costfunction`
The reconstructed magnetisation distribution and the used costfunction.
"""
_log.debug('Calling reconstruction_2d_charge_from_phasemap')
# Construct DataSet, Regularisator, ForwardModel and Costfunction:
dim = (1,) + phasemap.dim_uv
data = DataSetCharge(phasemap.a, dim, electrode_vec, mask=mask)
kernel = KernelCharge(phasemap.a, phasemap.dim_uv, electrode_vec=electrode_vec,
v_acc=v_acc, prw_vec=prw)
data.append(phasemap, SimpleProjector(dim), PhaseMapperCharge(kernel))
data.set_3d_mask()
# TODO: Rework classes below (ForwardModel, Costfunction)!
fwd_model = ForwardModelCharge(data, ramp_order)
if lam is None:
reg = NoneRegularisator() # FirstOrderRegularisator(data.mask, lam, add_params=fwd_model.ramp.n)
else:
# reg = FirstOrderRegularisator(data.mask, lam=lam, p=2, add_params=fwd_model.ramp.n, factor=1)
reg = ZeroOrderRegularisator(data.mask, lam=lam, add_params=fwd_model.ramp.n)
cost = Costfunction(fwd_model, reg)
# Reconstruct:
elecdata_rec = reconstruction.optimize_linear_charge(cost, max_iter=max_iter, verbose=verbose)
param_cache = cost.fwd_model.ramp.param_cache
if ramp_order is None:
offset, ramp = 0, (0, 0)
elif ramp_order >= 1:
offset, ramp = param_cache[0][0], (param_cache[1][0], param_cache[2][0])
elif ramp_order == 0:
offset, ramp = param_cache[0][0], (0, 0)
else:
raise ValueError('ramp_order has to be a positive integer or None!')
# Plot stuff:
if plot_results:
phasemap_rec = pm(elecdata_rec, mapper='Charge')
gain = 4 * 2 * np.pi / (np.abs(phasemap_rec.phase).max() + 1E-30)
gain = round(gain, -int(np.floor(np.log10(abs(gain)))))
vmin = phasemap_rec.phase.min()
vmax = phasemap_rec.phase.max()
phasemap.plot_combined(note='Input Phase', gain=gain)
phasemap -= fwd_model.ramp(index=0)
phasemap.plot_combined(note='Input Phase (ramp corrected)', gain=gain, vmin=vmin, vmax=vmax)
title = 'Reconstructed Phase'
if ramp_order is not None:
if ramp_order >= 0:
print('offset:', offset)
# title += ', fitted Offset: {:.2g} [rad]'.format(offset)
if ramp_order >= 1:
print('ramp:', ramp)
# title += ', (Fitted Ramp: (u:{:.2g}, v:{:.2g}) [rad/nm]'.format(*ramp)
phasemap_rec.plot_combined(note=title, gain=gain, vmin=vmin, vmax=vmax)
diff = (phasemap_rec - phasemap)
diff_name = 'Difference (RMS: {:.2g} rad)'.format(np.sqrt(np.mean(diff.phase) ** 2))
diff.plot_phase_with_hist(note=diff_name, sigma_clip=3)
if ramp_order is not None:
ramp = fwd_model.ramp(0)
ramp.plot_phase(note='Fitted Ramp')
# Return reconstructed charge distribution and cost function:
return elecdata_rec, cost
def reconstruction_3d_from_magdata(magdata, b_0=1, lam=1E-3, max_iter=100, ramp_order=1,
angles=np.linspace(-90, 90, num=19), dim_uv=None,
......
......@@ -5,6 +5,7 @@ import numpy as np
def electron_wavelength(ht):
"""
Returns electron wavelenght in nm.
Parameters
----------
ht : float
......
# -*- coding: utf-8 -*-
# Copyright 2016 by Forschungszentrum Juelich GmbH
# Author: J. Caron
#
"""Convenience function for phase mapping magnetic or charge distributions."""
import logging
from ..kernel import Kernel, KernelCharge
from ..phasemapper import PhaseMapperRDFC, PhaseMapperFDFC, PhaseMapperCharge
from ..projector import RotTiltProjector, XTiltProjector, YTiltProjector, SimpleProjector
__all__ = ['pm']
_log = logging.getLogger(__name__)
# TODO: rename magdata to vecdata everywhere!
def pm(fielddata, mode='z', b_0=1, electrode_vec=(1E6, 1E6), prw_vec=None, mapper='RDFC', **kwargs):
"""Convenience function for fast electric charge and magnetic phase mapping.
Parameters
----------
fielddata : :class:`~.VectorData`, or `~.ScalarData`
A :class:`~.VectorData` or `~.ScalarData` object, from which the projected phase map should
be calculated.
mode: {'z', 'y', 'x', 'x-tilt', 'y-tilt', 'rot-tilt'}, optional
Projection mode which determines the :class:`~.pyramid.projector.Projector` subclass, which
is used for the projection. Default is a simple projection along the `z`-direction.
b_0 : float, optional
Saturation magnetization in Tesla, which is used for the phase calculation. Default is 1.
electrode_vec : tuple of float (N=2)
The norm vector of the counter electrode, (elec_a,elec_b), and the distance to the origin is
the norm of (elec_a,elec_b). The default value is (1E6, 1E6).
prw_vec: tuple of 2 int, optional
A two-component vector describing the displacement of the reference wave to include
perturbation of this reference by the object itself (via fringing fields), (y, x).
mapper : :class: '~. PhaseMap'
A :class: '~. PhaseMap' object, which maps a fielddata into a phase map. The default
is 'RDFC'.
**kwargs : additional arguments
Additional arguments like `dim_uv`, 'tilt' or 'rotation', which are passed to the
projector-constructor, defined by the `mode`.
Returns
-------
phasemap : :class:`~pyramid.phasemap.PhaseMap`
The calculated phase map as a :class:`~.PhaseMap` object.
"""
_log.debug('Calling pm')
# In case of FDFC:
padding = kwargs.pop('padding', 0)
# Determine projection mode:
if mode == 'rot-tilt':
projector = RotTiltProjector(fielddata.dim, **kwargs)
elif mode == 'x-tilt':
projector = XTiltProjector(fielddata.dim, **kwargs)
elif mode == 'y-tilt':
projector = YTiltProjector(fielddata.dim, **kwargs)
elif mode in ['x', 'y', 'z']:
projector = SimpleProjector(fielddata.dim, axis=mode, **kwargs)
else:
raise ValueError("Invalid mode (use 'x', 'y', 'z', 'x-tilt', 'y-tilt' or 'rot-tilt')")
# Project:
field_proj = projector(fielddata)
# Set up phasemapper and map phase:
if mapper == 'RDFC':
phasemapper = PhaseMapperRDFC(Kernel(fielddata.a, projector.dim_uv, b_0=b_0))
elif mapper == 'FDFC':
phasemapper = PhaseMapperFDFC(fielddata.a, projector.dim_uv, b_0=b_0, padding=padding)
# Set up phasemapper and map phase:
elif mapper == 'Charge':
phasemapper = PhaseMapperCharge(KernelCharge(fielddata.a, projector.dim_uv,
electrode_vec=electrode_vec, prw_vec=prw_vec))
else:
raise ValueError("Invalid mapper (use 'RDFC', 'FDFC' or 'Charge'")
phasemap = phasemapper(field_proj)
# Get mask from fielddata:
phasemap.mask = field_proj.get_mask()[0, ...]
# Return phase:
return phasemap
# -*- coding: utf-8 -*-
# Copyright 2016 by Forschungszentrum Juelich GmbH
# Author: J. Caron
#
"""Reconstruct a magnetization distributions from a single phase map."""
import logging
import numpy as np
from .. import reconstruction
from ..dataset import DataSet, DataSetCharge
from ..projector import SimpleProjector
from ..regularisator import FirstOrderRegularisator, NoneRegularisator, ZeroOrderRegularisator
from ..kernel import KernelCharge
from ..phasemapper import PhaseMapperCharge
from ..forwardmodel import ForwardModel, ForwardModelCharge
from ..costfunction import Costfunction
from .pm import pm
__all__ = ['reconstruction_2d_from_phasemap']
_log = logging.getLogger(__name__)
# TODO: lam should NOT have a default!!!
def reconstruction_2d_from_phasemap(phasemap, b_0=1, lam=1E-3, max_iter=100, ramp_order=None,
plot_results=False, ar_dens=None, verbose=True):
"""Convenience function for reconstructing a projected distribution from a single phasemap.
Parameters
----------
phasemap: :class:`~PhaseMap`
The phasemap which is used for the reconstruction.
b_0 : float, optional
The magnetic induction corresponding to a magnetization :math:`M_{0}` in T.
The default is 1.
lam : float
Regularisation parameter determining the weighting between measurements and regularisation.
max_iter : int, optional
The maximum number of iterations for the opimization.
ramp_order : int or None (default)
Polynomial order of the additional phase ramp which will be added to the phase maps.
All ramp parameters have to be at the end of the input vector and are split automatically.
Default is None (no ramps are added).
plot_results: boolean, optional
If True, the results are plotted after reconstruction.
ar_dens: int, optional
Number defining the arrow density which is plotted. A higher ar_dens number skips more
arrows (a number of 2 plots every second arrow). Will be estimated if not provided.
verbose: bool, optional
If set to True, information like a progressbar is displayed during reconstruction.
The default is False.
Returns
-------
magdata_rec, cost: :class:`~.VectorData`, :class:`~.Costfunction`
The reconstructed magnetisation distribution and the used costfunction.
"""
_log.debug('Calling reconstruction_2d_from_phasemap')
# Construct DataSet, Regularisator, ForwardModel and Costfunction:
dim = (1,) + phasemap.dim_uv
data = DataSet(phasemap.a, dim, b_0)
data.append(phasemap, SimpleProjector(dim))
data.set_3d_mask()
fwd_model = ForwardModel(data, ramp_order)
reg = FirstOrderRegularisator(data.mask, lam, add_params=fwd_model.ramp.n)
cost = Costfunction(fwd_model, reg)
# Reconstruct:
magdata_rec = reconstruction.optimize_linear(cost, max_iter=max_iter, verbose=verbose)
param_cache = cost.fwd_model.ramp.param_cache
if ramp_order is None:
offset, ramp = 0, (0, 0)
elif ramp_order >= 1:
offset, ramp = param_cache[0][0], (param_cache[1][0], param_cache[2][0])
elif ramp_order == 0:
offset, ramp = param_cache[0][0], (0, 0)
else:
raise ValueError('ramp_order has to be a positive integer or None!')
# Plot stuff:
if plot_results:
if ar_dens is None:
ar_dens = np.max([1, np.max(dim) // 64])
magdata_rec.plot_quiver_field(note='Reconstructed Distribution',
ar_dens=ar_dens, figsize=(16, 16))
phasemap_rec = pm(magdata_rec)
gain = 4 * 2 * np.pi / (np.abs(phasemap_rec.phase).max() + 1E-30)
gain = round(gain, -int(np.floor(np.log10(abs(gain)))))
vmin = phasemap_rec.phase.min()
vmax = phasemap_rec.phase.max()
phasemap.plot_combined(note='Input Phase', gain=gain)
phasemap -= fwd_model.ramp(index=0)
phasemap.plot_combined(note='Input Phase (ramp corrected)', gain=gain, vmin=vmin, vmax=vmax)
title = 'Reconstructed Phase'
if ramp_order is not None:
if ramp_order >= 0:
print('offset:', offset)
# title += ', fitted Offset: {:.2g} [rad]'.format(offset)
if ramp_order >= 1:
print('ramp:', ramp)
# title += ', (Fitted Ramp: (u:{:.2g}, v:{:.2g}) [rad/nm]'.format(*ramp)
phasemap_rec.plot_combined(note=title, gain=gain, vmin=vmin, vmax=vmax)
diff = (phasemap_rec - phasemap)
diff_name = 'Difference (RMS: {:.2g} rad)'.format(np.sqrt(np.mean(diff.phase) ** 2))
diff.plot_phase_with_hist(note=diff_name, sigma_clip=3)
if ramp_order is not None:
ramp = fwd_model.ramp(0)
ramp.plot_phase(note='Fitted Ramp')
# Return reconstructed magnetisation distribution and cost function:
return magdata_rec, cost
def reconstruction_2d_charge_from_phasemap(phasemap, max_iter=1000, ramp_order=None, mask=None,
lam=None, electrode_vec=(1E6, 1E6), v_acc=300000, prw=None,
plot_results=False, verbose=True):
"""Convenience function for reconstructing a projected distribution from a single phasemap.
Parameters
----------
phasemap: :class:`~PhaseMap`
The phasemap which is used for the reconstruction.
max_iter : int, optional
The maximum number of iterations for the optimization.
ramp_order : int or None (default)
Polynomial order of the additional phase ramp which will be added to the phase maps.
All ramp parameters have to be at the end of the input vector and are split automatically.
Default is None (no ramps are added).
lam: float,
The zero order regularisator parameter. 'None' means no regularisator.
mask: ndarrary,
Define where situate the reconstructed charges
electrode_vec : tuple of float (N=2)
The norm vector of the counter electrode in pixels, (elec_a,elec_b), and the distance to the origin is
the norm of (elec_a,elec_b).
v_acc: float
The accelerating voltage of electrons.
prw: tuple of 2 int, optional
A two-component vector describing the displacement of the reference wave to include
perturbation of this reference by the object itself (via fringing fields), (y, x).
plot_results: boolean, optional
If True, the results are plotted after reconstruction.
verbose: bool, optional
If set to True, information like a progressbar is displayed during reconstruction.
The default is False.
Returns
-------
elecdata_rec, cost: :class:`~.ScalarData`, :class:`~.Costfunction`
The reconstructed magnetisation distribution and the used costfunction.
"""
_log.debug('Calling reconstruction_2d_charge_from_phasemap')
# Construct DataSet, Regularisator, ForwardModel and Costfunction:
dim = (1,) + phasemap.dim_uv
data = DataSetCharge(phasemap.a, dim, electrode_vec, mask=mask)
kernel = KernelCharge(phasemap.a, phasemap.dim_uv, electrode_vec=electrode_vec,
v_acc=v_acc, prw_vec=prw)
data.append(phasemap, SimpleProjector(dim), PhaseMapperCharge(kernel))
data.set_3d_mask()
# TODO: Rework classes below (ForwardModel, Costfunction)!
fwd_model = ForwardModelCharge(data, ramp_order)
if lam is None:
reg = NoneRegularisator() # FirstOrderRegularisator(data.mask, lam, add_params=fwd_model.ramp.n)
else:
# reg = FirstOrderRegularisator(data.mask, lam=lam, p=2, add_params=fwd_model.ramp.n, factor=1)
reg = ZeroOrderRegularisator(data.mask, lam=lam, add_params=fwd_model.ramp.n)
cost = Costfunction(fwd_model, reg)
# Reconstruct:
elecdata_rec = reconstruction.optimize_linear_charge(cost, max_iter=max_iter, verbose=verbose)
param_cache = cost.fwd_model.ramp.param_cache
if ramp_order is None:
offset, ramp = 0, (0, 0)
elif ramp_order >= 1:
offset, ramp = param_cache[0][0], (param_cache[1][0], param_cache[2][0])
elif ramp_order == 0:
offset, ramp = param_cache[0][0], (0, 0)
else:
raise ValueError('ramp_order has to be a positive integer or None!')
# Plot stuff:
if plot_results:
phasemap_rec = pm(elecdata_rec, mapper='Charge')
gain = 4 * 2 * np.pi / (np.abs(phasemap_rec.phase).max() + 1E-30)
gain = round(gain, -int(np.floor(np.log10(abs(gain)))))
vmin = phasemap_rec.phase.min()
vmax = phasemap_rec.phase.max()
phasemap.plot_combined(note='Input Phase', gain=gain)
phasemap -= fwd_model.ramp(index=0)
phasemap.plot_combined(note='Input Phase (ramp corrected)', gain=gain, vmin=vmin, vmax=vmax)
title = 'Reconstructed Phase'
if ramp_order is not None:
if ramp_order >= 0:
print('offset:', offset)
# title += ', fitted Offset: {:.2g} [rad]'.format(offset)
if ramp_order >= 1:
print('ramp:', ramp)
# title += ', (Fitted Ramp: (u:{:.2g}, v:{:.2g}) [rad/nm]'.format(*ramp)
phasemap_rec.plot_combined(note=title, gain=gain, vmin=vmin, vmax=vmax)
diff = (phasemap_rec - phasemap)
diff_name = 'Difference (RMS: {:.2g} rad)'.format(np.sqrt(np.mean(diff.phase) ** 2))
diff.plot_phase_with_hist(note=diff_name, sigma_clip=3)
if ramp_order is not None:
ramp = fwd_model.ramp(0)
ramp.plot_phase(note='Fitted Ramp')
# Return reconstructed charge distribution and cost function:
return elecdata_rec, cost
# -*- coding: utf-8 -*-
""""This file is generated automatically by the Pyramid `setup.py`"""
""""This file was automatically generated by `setup.py`"""
version = "0.1.0.dev0"
hg_revision = "???"
git_revision = "a9c22581a4bfd12bfadd9001ccf893f77fc1a6de"
......@@ -69,9 +69,6 @@ install_requires =
scipy
matplotlib
Pillow
h5py
hyperspy
cmocean
# jutil # TODO: How to handle this??? Ask Jörn!
[options.extras_require]
......@@ -111,8 +108,8 @@ omit =
tests/*
[tool:pytest] # TODO: Check if everything is taylored to pyramid!
#addopts = --cov --flake8
flake8-max-line-length = 100
#addopts = --cov --flake8 # TODO: delete?
flake8-max-line-length = 120
flake8-ignore =
#ALL # TODO: PEP8 deactivated by this line (remove at a later point)!
E402 # module import not at top of file
......@@ -120,6 +117,7 @@ flake8-ignore =
E125 # continuation line with same indent as next logical line
E226 # missing whitespace around arithmetic operator
W503 # line break before binary operator
W504 # line break after binary operator
E741 # do not use variables named ‘l’, ‘O’, or ‘I’
pyramid/__init__.py F401 # module imported but unused
#doc/conf.py ALL
#doc/conf.py ALL # TODO: delete?
......@@ -4,49 +4,26 @@
import os
import subprocess
import itertools
from setuptools import setup
from setuptools.config import read_configuration
from setuptools import setup, config
# Read version from setup.py:
version = config.read_configuration('setup.cfg')['metadata']['version']
# Get current git revision:
try:
git_rev = subprocess.check_output(['git', 'rev-parse', 'HEAD']).strip().decode()
except Exception:
git_rev = "???"
# Write both to version.py:
version_string =
with open(os.path.join(os.path.dirname(__file__), 'pyramid', 'version.py'), 'w') as vfile:
vfile.write('# -*- coding: utf-8 -*-\n' +
'""""This file was automatically generated by `setup.py`"""\n' +
f'version = "{version}"\n' +
f'git_revision = "{git_rev}"\n')
# Run setup (reads metadata & options from setup.cfg):
setup()
def git_version():
'''Get current git revision.'''
try:
git_rev = subprocess.check_output(['git', 'rev-parse', 'HEAD']).strip().decode()
except Exception:
git_rev = "???"
return git_rev
def write_version_py(version, git_version, filename='pyramid/version.py'):
'''Write version.py file.'''
version_string = '# -*- coding: utf-8 -*-\n' + \
'""""This file was automatically generated by `setup.py`"""\n' + \
f'version = "{version}"\n' + \
f'git_revision = "{git_version}"\n'
with open(os.path.join(os.path.dirname(__file__), filename), 'w') as vfile:
vfile.write(version_string)
# Read setup.cfg (setup() would auto-read it, but we want to read the version and modify it here):
conf_dict = read_configuration('setup.cfg')
metadata_dict = conf_dict['metadata']
options_dict = conf_dict['options']
# Read version and write to version.py:
version = metadata_dict['version']
write_version_py(version, git_version())
# Add 'full' convenience option to extras_require for full install: python setup.py install .[full]
full_list = list(itertools.chain(*list(options_dict['extras_require'].values())))
options_dict['extras_require']['full'] = full_list
# Run setup:
setup(**metadata_dict, **options_dict) # TODO: Is this overwritten by setup.cfg again?
# TODO: Currently does not work, find out why!
# TODO: HOW TO GET JUTIL???
# TODO: Also create conda recipe!
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment