Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • kwant/kwant
  • jbweston/kwant
  • anton-akhmerov/kwant
  • cwg/kwant
  • Mathieu/kwant
  • slavoutich/kwant
  • pacome/kwant
  • behrmann/kwant
  • michaelwimmer/kwant
  • albeercik/kwant
  • eunjongkim/kwant
  • basnijholt/kwant
  • r-j-skolasinski/kwant
  • sahmed95/kwant
  • pablopiskunow/kwant
  • mare/kwant
  • dvarjas/kwant
  • Paul/kwant
  • bbuijtendorp/kwant
  • tkloss/kwant
  • torosdahl/kwant
  • kel85uk/kwant
  • kpoyhonen/kwant
  • Fromeworld/kwant
  • quaeritis/kwant
  • marwahaha/kwant
  • fernandodfufrpe/kwant
  • oly/kwant
  • jiamingh/kwant
  • mehdi2369/kwant
  • ValFadeev/kwant
  • Kostas/kwant
  • chelseabaptiste03/kwant
33 results
Show changes
Commits on Source (133)
Showing
with 151 additions and 2588 deletions
......@@ -8,13 +8,7 @@
/dist
/doc/build
/doc/source/reference/generated/
/doc/source/code/include/*.py
/doc/source/code/figure/*.png
/doc/source/code/figure/*.pdf
/doc/source/code/figure/.*_flag
/doc/source/code/figure/[a-zA-Z]*.py
/doc/source/code/figure/*.txt
/doc/source/code/download/
/doc/source/figure/*.pdf
/build.conf
/kwant.egg-info/
/MANIFEST.in
......
......@@ -25,14 +25,11 @@ variables:
untracked: true
expire_in: 1 hour
before_script:
- mkdir -p /root/.docker
- echo "{\"auths\":{\"$CI_REGISTRY\":{\"username\":\"$CI_REGISTRY_USER\",\"password\":\"$CI_REGISTRY_PASSWORD\"}}}" > /root/.docker/config.json
- mkdir -p /kaniko/.docker
- echo "{\"auths\":{\"$CI_REGISTRY\":{\"username\":\"$CI_REGISTRY_USER\",\"password\":\"$CI_REGISTRY_PASSWORD\"}}}" > /kaniko/.docker/config.json
build-env:ubuntu:
<<: *build-env
only:
changes:
- docker/Dockerfile.ubuntu
script:
- /kaniko/executor
--context $CI_PROJECT_DIR/docker
......@@ -41,9 +38,6 @@ build-env:ubuntu:
build-env:debian:
<<: *build-env
only:
changes:
- docker/Dockerfile.debian
script:
- /kaniko/executor
--context $CI_PROJECT_DIR/docker
......@@ -52,10 +46,6 @@ build-env:debian:
build-env:conda:
<<: *build-env
only:
changes:
- docker/Dockerfile.conda
- docker/*.yml
script:
- /kaniko/executor
--context $CI_PROJECT_DIR/docker
......@@ -64,10 +54,6 @@ build-env:conda:
build-env:default:
<<: *build-env
only:
changes:
- docker/Dockerfile.conda
- docker/*.yml
script:
- /kaniko/executor
--context $CI_PROJECT_DIR/docker
......@@ -160,6 +146,14 @@ check for dependencies installed:
.test: &test
stage: test
script:
- py.test -r w --flakes kwant --junitxml=tests.xml --durations=10
artifacts:
reports:
junit: tests.xml
.coverage: &coverage
stage: test
script:
- py.test -r w --cov=kwant --cov-report term --cov-report html --flakes kwant --junitxml=tests.xml --durations=10
......@@ -209,6 +203,14 @@ test:bleeding-edge:
- schedules
allow_failure: true
coverage:latest:
<<: *coverage
<<: *latest_env
dependencies:
- build:latest
only:
- schedules
## Documentation building
build documentation:
......@@ -217,7 +219,7 @@ build documentation:
- build:latest
stage: test
script:
- make -C doc realclean; make -C doc html SPHINXOPTS='-A website_deploy=True -n -W' SOURCE_LINK_TEMPLATE="$CI_PROJECT_URL"/blob/\$\$r/\$\$f
- make -C doc clean; make -C doc html SPHINXOPTS='-A website_deploy=True -n -W -D jupyter_execute_default_kernel=kwant-latest' SOURCE_LINK_TEMPLATE="$CI_PROJECT_URL"/blob/\$\$r/\$\$f
artifacts:
paths:
- doc/build/html/
......@@ -229,7 +231,7 @@ build PDF documentation:
- build:latest
stage: test
script:
- make -C doc latex SPHINXOPTS='-n -W'
- make -C doc latex SPHINXOPTS='-n -W -D jupyter_execute_default_kernel=kwant-latest'
- cd doc/build/latex
- make all-pdf
artifacts:
......@@ -252,7 +254,9 @@ check for broken links in doc:
upload coverage:
stage: deploy
only:
- branches@kwant/kwant
- schedules
dependencies:
- coverage:latest
environment:
name: coverage/$CI_BUILD_REF_NAME
url: https://kwant-project.org/coverage/$CI_BUILD_REF_SLUG
......
# Release %vX.Y.Z **UPDATE THIS**
This is a checklist based on the [release document](RELEASE.rst); consult it for more details.
## Preflight checks
- [ ] All the issues from this milestone are resolved
- [ ] Ensure that tests pass (either on [stable](https://gitlab.kwant-project.org/kwant/kwant/tree/stable) or on [master](https://gitlab.kwant-project.org/kwant/kwant/tree/master) branch)
- [ ] Documentation looks correct https://test.kwant-project.org/doc/<branch name>
- [ ] [Whatnew](doc/source/pre/whatsnew) is up to date
- [ ] `AUTHORS.rst` and `.mailmap` are up to date (run `git shortlog -s | sed -e "s/^ *[0-9\t ]*//"| xargs -i sh -c 'grep -q "{}" AUTHORS.rst || echo "{}"'`)
## Make a release, but do not publish it yet
- [ ] Tag the release
- [ ] Build the source tarball and inspect it
- [ ] Build the documentation
## Test packaging
These steps may be done in parallel
### Debian
- [ ] Follow the steps for building the Debian packages from [RELEASE.rst](RELEASE.rst)
### Conda
- [ ] Publish the release candidate source tarball "somewhere on the internet" (SOTI)
- [ ] open a PR to the [conda-forge/kwant-feedstock](https://github.com/conda-forge/kwant-feedstock/) repo on Github. Make sure to mark the PR as WIP so that it doesn't get merged in accidentally
- [ ] set the upstream tarball URL (in meta.yaml) to SOTI
- [ ] update the tarball hash in meta.yaml
- [ ] See if the package builds
## Publish the release
- [ ] push the tag
- [ ] upload the source tarball to PyPI
- [ ] upload the source tarball to the Kwant website
- [ ] publish the debian packages
- [ ] publish the ubuntu packages
- [ ] create a new version of the Kwant conda-forge feedstock, and open a pull request to upstream
- [ ] upload the documentation to the Kwant website
- [ ] update the Kwant website to say that Conda is the preferred way to install Kwant on Windows
## Announce the release
- [ ] Write a short post summarizing the highlights on the Kwant website
- [ ] post to the Kwant mailing list
## Working towards next release
- [ ] add a whatsnew file for the next release
- [ ] tag this release with an `a0` suffix
- [ ] push this tag to the official Kwant repository
- [ ] create a milestone for the next release
......@@ -10,14 +10,17 @@ The principal developers of Kwant are
* `Michael Wimmer <https://michaelwimmer.org>`_ (TU Delft)
* `Anton Akhmerov <http://antonakhmerov.org>`_ (TU Delft)
* `Xavier Waintal <http://inac.cea.fr/Pisp/xavier.waintal>`_ (CEA Grenoble)
* `Joseph Weston <http://josephweston.org>`_ (TU Delft)
* `Joseph Weston <https://joseph.weston.cloud>`_ (TU Delft)
Contributors to Kwant include
* Jörg Behrmann (FU Berlin)
* Pierre Carmier (CEA Grenoble)
* Paul Clisson (CEA Grenoble)
* `Dennis Heffels <mailto:d.heffels@fz-juelich.de>`_ (FZJ PGI-9)
* Mathieu Istas (CEA Grenoble)
* Daniel Jaschke (CEA Grenoble)
* Thomas Kloss (CEA Grenoble)
* Bas Nijholt (TU Delft)
* Michał Nowak (TU Delft)
* Viacheslav Ostroukh (Leiden University)
......@@ -27,8 +30,6 @@ Contributors to Kwant include
* Rafał Skolasiński (TU Delft)
* Adrien Sorgniard (CEA Grenoble)
* Dániel Varjas (TU Delft)
* Thomas Kloss (CEA Grenoble)
* Pierre Carmier (CEA Grenoble)
We thank Christoph Gohlke for the creation of installers for Microsoft Windows.
......
......@@ -29,10 +29,10 @@ Prerequisites
=============
Building Kwant requires
* `Python <https://www.python.org/>`_ 3.5 or above (Kwant 1.1 is the last
* `Python <https://www.python.org/>`_ 3.6 or above (Kwant 1.1 is the last
version to support Python 2),
* `NumPy <http://numpy.org/>`_ 1.11.0 or newer,
* `SciPy <https://www.scipy.org/>`_ 0.17.0 or newer,
* `NumPy <http://numpy.org/>`_ 1.13.3 or newer,
* `SciPy <https://www.scipy.org/>`_ 0.19.1 or newer,
* `LAPACK <http://netlib.org/lapack/>`_ and `BLAS <http://netlib.org/blas/>`_,
(For best performance we recommend the free `OpenBLAS
<http://www.openblas.net/>`_ or the nonfree `MKL
......@@ -43,19 +43,19 @@ a NumPy-like Python package optimized for very small arrays,
C++.
The following software is highly recommended though not strictly required:
* `matplotlib <http://matplotlib.org/>`_ 1.5.1 or newer, for the module `kwant.plotter` and the tutorial,
* `SymPy <http://sympy.org/>`_ 0.7.6 or newer, for the subpackage `kwant.continuum`.
* `matplotlib <http://matplotlib.org/>`_ 2.1.1 or newer, for the module `kwant.plotter` and the tutorial,
* `SymPy <http://sympy.org/>`_ 1.1.1 or newer, for the subpackage `kwant.continuum`.
* `Qsymm <https://pypi.org/project/qsymm/>`_ 1.2.6 or newer, for the subpackage `kwant.qsymm`.
* `MUMPS <http://graal.ens-lyon.fr/MUMPS/>`_, a sparse linear algebra library
that will in many cases speed up Kwant several times and reduce the memory
footprint. (Kwant uses only the sequential, single core version
of MUMPS. The advantages due to MUMPS as used by Kwant are thus independent
of the number of CPU cores of the machine on which Kwant runs.)
* The `py.test testing framework <http://pytest.org/>`_ 2.8 or newer for running the
* The `py.test testing framework <http://pytest.org/>`_ 3.3.2 or newer for running the
tests included with Kwant.
In addition, to build a copy of Kwant that has been checked-out directly from
version control, you will also need `Cython <http://cython.org/>`_ 0.22 or
version control, you will also need `Cython <http://cython.org/>`_ 0.26.1 or
newer. You do not need Cython to build Kwant that has been unpacked from a
source .tar.gz-file.
......@@ -144,9 +144,12 @@ Building the documentation
To build the documentation, the `Sphinx documentation generator
<http://www.sphinx-doc.org/en/stable/>`_ is required with ``numpydoc`` extension
(version 0.5 or newer). If PDF documentation is to be built, the tools
from the `libRSVG <https://wiki.gnome.org/action/show/Projects/LibRsvg>`_ (Debian/Ubuntu package
``librsvg2-bin``) are needed to convert SVG drawings into the PDF format.
(version 0.5 or newer), as well as ``jupyter-sphinx`` (version 0.2 or newer).
If PDF documentation is to be built, the tools
from the `libRSVG <https://wiki.gnome.org/action/show/Projects/LibRsvg>`_
(Debian/Ubuntu package ``librsvg2-bin``) and a Sphinx extension
``sphinxcontrib-svg2pdfconverter`` are needed to convert SVG drawings into the
PDF format.
As a prerequisite for building the documentation, Kwant must have been built
successfully using ``python3 setup.py build`` as described above (or Kwant must
......@@ -160,25 +163,6 @@ Because of some quirks of how Sphinx works, it might be necessary to execute
done, Sphinx may mistakenly use PNG files for PDF output or other problems may
appear.
When ``make html`` is run, modified tutorial example scripts are executed to
update any figures that might have changed. The machinery behind this works as
follows. The canonical source for a tutorial script, say ``graphene.py`` is
the file ``doc/source/images/graphene.py.diff``. This diff file contains the
information to recreate two versions of ``graphene.py``: a version that is
presented in the documentation (``doc/source/tutorial/graphene.py``), and a
version that is used to generate the figures for the documentation
(``doc/source/images/graphene.py``). Both versions are related but differ
e.g. in the details of the plotting. When ``make html`` is run, both versions
are extracted form the diff file.
The diff file may be modified directly. Another possible way of working is to
directly modify either the tutorial script or the figure generation script.
Then ``make html`` will use the command line tool `wiggle
<https://github.com/neilbrown/wiggle>`_ to propagate the modifications accordingly.
This will often just work, but may sometimes result in conflicts, in which case
a message will be printed. The conflicts then have to be resolved much like
with a version control system.
****************************
Hints for specific platforms
****************************
......
......@@ -3,6 +3,10 @@ Making a Kwant release
This document guides a contributor through creating a release of Kwant.
Create a release issue
######################
Use the correct `issue template <gitlab.kwant-project.org/kwant/kwant/issues/new?issuable_template=release>`_, adjust it if necessary.
Preflight checks
################
......@@ -114,21 +118,23 @@ Building the documentation requires 'sphinx' and a Latex installation.
First build the HTML and PDF documentation::
./setup.py build
cd doc
make realclean
make html latex SPHINXOPTS='-A website_deploy=True -n -W'
cd doc/build/latex
make all-pdf
make -C doc realclean
make -C doc html latex
make -C doc/build/latex all-pdf
Then create a zipped version of the HTML documentation and name the PDF
consistently, storing them, for example, in the "dist" directory along with the
source tarballs::
ln -s `pwd`/doc/build/html /tmp/kwant-doc-<version>
(cd /tmp/; zip -r kwant-doc-<version>.zip kwant-doc-<version>)
mv /tmp/kwant-doc-<version>.zip dist
version=$(git describe | sed 's/^v//') # Assumes that we are on a tag.
ln -s `pwd`/doc/build/html /tmp/kwant-doc-$version
(cd /tmp/; zip -r kwant-doc-$version.zip kwant-doc-$version)
mv /tmp/kwant-doc-$version.zip dist
mv doc/build/latex/kwant.pdf dist/kwant-doc-$version.pdf
Finally, rebuild the documentation for the website (including the web analysis javascript code)::
mv doc/build/latex/kwant.pdf dist/kwant-doc-<version>.pdf
make -C doc html SPHINXOPTS='-A website_deploy=True -n -W'
Clone the repository of the Kwant Debian package
......@@ -274,6 +280,14 @@ current Debian testing)::
ARCH=i386 DIST=<dist> git-pbuilder update
ARCH=amd64 DIST=<dist> git-pbuilder update
Make sure that the working directory is completely clear::
git clean -id
(Note that pytest has the nasty habit of creating a hidden ``.pytest_cache``
directory which gitignores itself. The above command will not delete this
directory, but git-pbuilder will complain.)
Now build the packages. First the i386 package. The option "--git-tag" tags
and signs the tag if the build is successful. In a second step, the package is
built for amd64, but only the architecture-dependent files (not the
......@@ -433,7 +447,7 @@ We will also use the following script (prepare_ppa_upload)::
for release in $@; do
cp /tmp/changelog.$$ debian/changelog
DEBEMAIL=christoph.groth@cea.fr dch -b -v "$version~$release" -u low 'Ubuntu PPA upload'
sed -i -e "1,1 s/UNRELEASED/$release/" debian/changelog
sed -i -e "1,1 s/UNRELEASED/${release%[0-9]}/" debian/changelog
debuild -S -sa
done
......@@ -514,23 +528,20 @@ Ask Christoph Groth if you need to be granted access.
Upload the zipped HTML and PDF documentation::
scp dist/kwant-doc-<version>.zip kwant-project.org:webapps/downloads/doc
scp dist/kwant-doc-<version>.pdf kwant-project.org:webapps/downloads/doc
Point the symbolic links ``latest.zip`` and ``latest.pdf`` to these new files::
ssh kwant-project.org "cd webapps/downloads/doc; ln -s kwant-doc-<version>.zip latest.zip"
ssh kwant-project.org "cd webapps/downloads/doc; ln -s kwant-doc-<version>.pdf latest.pdf"
scp dist/kwant-doc-<version>.{zip,pdf} kwant-project.org:webapps/downloads/doc
Then upload the HTML documentation for the main website::
Upload the HTML documentation for the website::
rsync -rlv --delete doc/build/html/* kwant-project.org:webapps/kwant/doc/<short-version>
where in the above ``<short-version>`` is just the major and minor version numbers.
Finally point the symbolic link ``<major-version>`` to ``<short-version>``::
Finally, create symbolic links for the website::
ssh kwant-project.org "cd webapps/kwant/doc; ln -s <major> <short-version>"
ssh kwant-project.org
for e in zip pdf; do ln -sf kwant-doc-<version>.$e webapps/downloads/doc/latest.$e; done
ln -nsf <short-version> webapps/kwant/doc/<major>
exit
Announce the release
......
# Makefile for Sphinx documentation
# Copyright 2011-2017 Kwant authors.
# Minimal makefile for Sphinx documentation
#
# This file is part of Kwant. It is subject to the license terms in the file
# LICENSE.rst found in the top-level directory of this distribution and at
# http://kwant-project.org/license. A list of Kwant authors can be found in
# the file AUTHORS.rst at the top-level directory of this distribution and at
# http://kwant-project.org/authors.
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
SOURCEDIR = source
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) source
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# We convert all SVG files to PDF for LaTeX output. For HTML output, we don't
# create PNGs but rather use the SVG files directly.
FIGURESOURCES = $(shell find source -name "*.svg")
GENERATEDPDF = $(patsubst %.svg,%.pdf,$(FIGURESOURCES))
# Figure generation from patched tutorial scripts
#
# As make does not support the generation of multiple targets by a single
# invocation of a (non-implicit) rule, we use a trick: We pretend to be
# generating a single (empty) flag file per invocation. The figure files are
# generated as well, but only as side-effects. Each flag file is used to
# remember the time at which the corresponding figure-generating script was run.
# This works perfectly unless the actual output files are deleted without
# deleting the corresponding flag file.
FIGSCRIPTS = $(patsubst %.diff,%,$(notdir $(wildcard source/code/figure/*.py.diff)))
FIGURES = $(patsubst %.py,source/code/figure/.%_flag,$(FIGSCRIPTS))
SCRIPTS = $(sort $(FIGSCRIPTS) $(notdir $(wildcard source/code/include/*.py)))
INCLUDES = $(patsubst %,source/code/include/%,$(SCRIPTS))
DOWNLOADS = $(patsubst %,source/code/download/%,$(SCRIPTS))
.PHONY: help clean realclean html dirhtml pickle json htmlhelp qthelp latex changes linkcheck doctest
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 " 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 " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@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)"
@echo
@echo "Append SPHINXOPTS='-A website_deploy=True' to include web analytics code."
clean:
-rm -rf $(BUILDDIR)/* $(GENERATEDPDF)
-rm -rf source/reference/generated
realclean: clean
-rm -f $(FIGURES)
-rm -f $(patsubst %,source/code/include/%,$(FIGSCRIPTS))
-rm -f $(DOWNLOADS)
-rm -f $(patsubst %,source/code/figure/%,$(FIGSCRIPTS))
-rm -f $(patsubst %.py,source/code/figure/%_*.png,$(FIGSCRIPTS))
-rm -f $(patsubst %.py,source/code/figure/%_*.pdf,$(FIGSCRIPTS))
html: $(FIGURES) $(INCLUDES) $(DOWNLOADS)
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml: $(FIGURES) $(INCLUDES) $(DOWNLOADS)
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
pickle: $(FIGURES) $(INCLUDES) $(DOWNLOADS)
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json: $(FIGURES) $(INCLUDES) $(DOWNLOADS)
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp: $(FIGURES) $(INCLUDES) $(DOWNLOADS)
$(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: $(FIGURES) $(INCLUDES) $(DOWNLOADS)
$(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/kwant.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/kwant.qhc"
latex: $(GENERATEDPDF) $(FIGURES) $(INCLUDES) $(DOWNLOADS)
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \
"run these through (pdf)latex."
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."
%.pdf: %.svg
inkscape --export-pdf=$@ $<
#### Tutorial and figure script generation machinery ####
# See source/code/README for an explanation.
# Make tutorial scripts by extracting the (complete!) context of the "patches".
# We make sure not to use 'wiggle' here.
.SECONDARY:
source/code/include/%.py: source/code/figure/%.py.diff
@sed -n '/^[- ]/ s/^.//p' <$< >$@
@touch -r $< $@
# Emtpy target required so that the default target is not triggered
%.svg:
source/code/download/%.py: source/code/include/%.py
@mkdir -p source/code/download
@grep -v '^#HIDDEN' <$< >$@
# Make the figure generation scripts by patching tutorial scripts. If the
# tutorial scripts haven't been modified, don't patch but directly extract the
# figure generation scripts. This means that 'wiggle' is only needed when the
# tutorial scripts have been modified.
.SECONDARY:
source/code/figure/%.py: source/code/include/%.py
@if [ $< -nt $@.diff ]; then \
cp $< $@; \
rm -f $@.porig; \
if ! wiggle --replace $@ $@.diff; then \
command -v wiggle >/dev/null 2>&1 && \
echo "Resolve conflicts by editing the files named below"; \
touch -d@0 $@; \
exit 1; \
fi \
else \
sed -n '/^[+ ]/ s/^.//p' <$@.diff >$@; \
touch -r $@.diff $@; \
fi
# Make the figure generation scripts also depend on the diffs.
define makedep
source/code/figure/$(1): source/code/figure/$(1).diff
endef
$(foreach name,$(FIGSCRIPTS),$(eval $(call makedep,$(name))))
# Run an figure generation script. When successful, and if the script is newer
# than the corresponding diff, recreate the latter. Note that the
# corresponding tutorial script cannot be newer, since if it is, the figure
# generation script is generated from it by patching.
source/code/figure/.%_flag: source/code/figure/%.py
cd $(dir $<) && python3 $(notdir $<)
@if [ ! -f $<.diff -o $< -nt $<.diff ]; then \
wiggle --diff --lines source/code/include/$(notdir $<) $< >$<.diff; \
touch -r $< $<.diff; \
fi
@rm -f $<.porig
@touch $@
clean:
rm -f $(GENERATEDPDF)
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
latex: Makefile $(GENERATEDPDF)
cd .. ; python3 setup.py build ; cd -
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
cd .. ; python3 setup.py build ; cd -
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
......@@ -94,6 +94,10 @@ div.body pre {
border: 1px solid #ac9;
}
div.body pre.CodeMirror-line {
border: unset;
}
div.body div.admonition, div.body div.impl-detail {
border-radius: 3px;
}
......
This directory contains the code examples from the documentation.
Most scripts are present in three related but different versions that
correspond to three different usages.
* Subdirectory 'figure': scripts used for figure generation. Figures
are not displayed but saved to disk.
* Subdirectory 'include': scripts that display figures on screen.
They contain commented marks for including snippets in the
documentation.
* Subdirectory 'download': complete scripts to be offered for download
by readers. Like 'include' but with the include marks removed.
Most scripts are extracted from corresponding '*.py.diff' files inside
'figure/'. These are patches from the 'include' version to the
'figure' version. The patches include complete context and as such
can be used to recreate both files. It's these patches that are kept
under version control.
running 'make html' or 'make latex' inside '/doc' will automatically
update all these scripts according to the following scheme:
---->------------->------
/ \
/ download/x.py \
figure/x.py.diff ^ \
^ \ | \
| -> include/x.py ---(patch)---> figure/x.py
| | |
| | |
\ v /
----<----------(diff)--------------<--------
Thus, it is possible to update figure/x.py.diff, include/x.py or
figure/x.py and any changes will be propagated automatically when
'make' is run. (Only download/x.py is a dead end.) The user will be
informed about any conflicts. The makefile will only update files
that are older than their sources and is careful to propagate time
stamps in order to avoid infinite loops.
Editing only figure/x.py.diff is a sure way to avoid any conflicts.
################################################################
# Make matplotlib work without X11
################################################################
import matplotlib
matplotlib.use('Agg')
################################################################
# Prepend Kwant's build directory to sys.path
################################################################
import sys
from distutils.util import get_platform
sys.path.insert(0, "../../../../build/lib.{0}-{1}.{2}".format(
get_platform(), *sys.version_info[:2]))
################################################################
# Define constants for plotting
################################################################
pt_to_in = 1. / 72.
# Default width of figures in pts
figwidth_pt = 600
figwidth_in = figwidth_pt * pt_to_in
# Width for smaller figures
figwidth_small_pt = 400
figwidth_small_in = figwidth_small_pt * pt_to_in
# Sizes for matplotlib figures
mpl_width_in = figwidth_pt * pt_to_in
mpl_label_size = None # font sizes in points
mpl_tick_size = None
# dpi for conversion from inches
dpi = 90
@@ -1,127 +1,196 @@
# Tutorial 2.3.3. Nontrivial shapes
# =================================
#
# Physics background
# ------------------
# Flux-dependent transmission through a quantum ring
#
# Kwant features highlighted
# --------------------------
# - More complex shapes with lattices
# - Allows for discussion of subtleties of `attach_lead` (not in the
# example, but in the tutorial main text)
# - Modifcations of hoppings/sites after they have been added
+import _defs
from cmath import exp
from math import pi
import kwant
# For plotting
from matplotlib import pyplot
#HIDDEN_BEGIN_eusz
def make_system(a=1, t=1.0, W=10, r1=10, r2=20):
# Start with an empty tight-binding system and a single square lattice.
# `a` is the lattice constant (by default set to 1 for simplicity).
lat = kwant.lattice.square(a)
syst = kwant.Builder()
#### Define the scattering region. ####
# Now, we aim for a more complex shape, namely a ring (or annulus)
def ring(pos):
(x, y) = pos
rsq = x ** 2 + y ** 2
return (r1 ** 2 < rsq < r2 ** 2)
#HIDDEN_END_eusz
# and add the corresponding lattice points using the `shape`-function
#HIDDEN_BEGIN_lcak
syst[lat.shape(ring, (0, r1 + 1))] = 4 * t
syst[lat.neighbors()] = -t
#HIDDEN_END_lcak
# In order to introduce a flux through the ring, we introduce a phase on
# the hoppings on the line cut through one of the arms. Since we want to
# change the flux without modifying the Builder instance repeatedly, we
# define the modified hoppings as a function that takes the flux as its
# parameter phi.
#HIDDEN_BEGIN_lvkt
def hopping_phase(site1, site2, phi):
return -t * exp(1j * phi)
def crosses_branchcut(hop):
ix0, iy0 = hop[0].tag
# builder.HoppingKind with the argument (1, 0) below
# returns hoppings ordered as ((i+1, j), (i, j))
return iy0 < 0 and ix0 == 1 # ix1 == 0 then implied
# Modify only those hopings in x-direction that cross the branch cut
def hops_across_cut(syst):
for hop in kwant.builder.HoppingKind((1, 0), lat, lat)(syst):
if crosses_branchcut(hop):
yield hop
syst[hops_across_cut] = hopping_phase
#HIDDEN_END_lvkt
#### Define the leads. ####
# left lead
#HIDDEN_BEGIN_qwgr
sym_lead = kwant.TranslationalSymmetry((-a, 0))
lead = kwant.Builder(sym_lead)
def lead_shape(pos):
(x, y) = pos
return (-W / 2 < y < W / 2)
lead[lat.shape(lead_shape, (0, 0))] = 4 * t
lead[lat.neighbors()] = -t
#HIDDEN_END_qwgr
#### Attach the leads and return the system. ####
#HIDDEN_BEGIN_skbz
syst.attach_lead(lead)
syst.attach_lead(lead.reversed())
#HIDDEN_END_skbz
return syst
+def make_system_note1(a=1, t=1.0, W=10, r1=10, r2=20):
+ lat = kwant.lattice.square(a)
+ syst = kwant.Builder()
+ def ring(pos):
+ (x, y) = pos
+ rsq = x**2 + y**2
+ return ( r1**2 < rsq < r2**2)
+ syst[lat.shape(ring, (0, 11))] = 4 * t
+ syst[lat.neighbors()] = -t
+ sym_lead0 = kwant.TranslationalSymmetry((-a, 0))
+ lead0 = kwant.Builder(sym_lead0)
+ def lead_shape(pos):
+ (x, y) = pos
+ return (-1 < x < 1) and ( 0.5 * W < y < 1.5 * W )
+ lead0[lat.shape(lead_shape, (0, W))] = 4 * t
+ lead0[lat.neighbors()] = -t
+ lead1 = lead0.reversed()
+ syst.attach_lead(lead0)
+ syst.attach_lead(lead1)
+ return syst
+
+
+def make_system_note2(a=1, t=1.0, W=10, r1=10, r2=20):
+ lat = kwant.lattice.square(a)
+ syst = kwant.Builder()
+ def ring(pos):
+ (x, y) = pos
+ rsq = x**2 + y**2
+ return ( r1**2 < rsq < r2**2)
+ syst[lat.shape(ring, (0, 11))] = 4 * t
+ syst[lat.neighbors()] = -t
+ sym_lead0 = kwant.TranslationalSymmetry((-a, 0))
+ lead0 = kwant.Builder(sym_lead0)
+ def lead_shape(pos):
+ (x, y) = pos
+ return (-1 < x < 1) and ( -W/2 < y < W/2 )
+ lead0[lat.shape(lead_shape, (0, 0))] = 4 * t
+ lead0[lat.neighbors()] = -t
+ lead1 = lead0.reversed()
+ syst.attach_lead(lead0)
+ syst.attach_lead(lead1, lat(0, 0))
+ return syst
+
+
def plot_conductance(syst, energy, fluxes):
# compute conductance
normalized_fluxes = [flux / (2 * pi) for flux in fluxes]
data = []
for flux in fluxes:
smatrix = kwant.smatrix(syst, energy, params=dict(phi=flux))
data.append(smatrix.transmission(1, 0))
- pyplot.figure()
+ fig = pyplot.figure()
pyplot.plot(normalized_fluxes, data)
- pyplot.xlabel("flux [flux quantum]")
- pyplot.ylabel("conductance [e^2/h]")
- pyplot.show()
+ pyplot.xlabel("flux [flux quantum]",
+ fontsize=_defs.mpl_label_size)
+ pyplot.ylabel("conductance [e^2/h]",
+ fontsize=_defs.mpl_label_size)
+ pyplot.setp(fig.get_axes()[0].get_xticklabels(),
+ fontsize=_defs.mpl_tick_size)
+ pyplot.setp(fig.get_axes()[0].get_yticklabels(),
+ fontsize=_defs.mpl_tick_size)
+ fig.set_size_inches(_defs.mpl_width_in, _defs.mpl_width_in * 3. / 4.)
+ fig.subplots_adjust(left=0.15, right=0.95, top=0.95, bottom=0.15)
+ fig.savefig("ab_ring_result.pdf")
+ fig.savefig("ab_ring_result.png", dpi=_defs.dpi)
def main():
syst = make_system()
# Check that the system looks as intended.
- kwant.plot(syst)
+ size = (_defs.figwidth_in, _defs.figwidth_in)
+ for extension in ('pdf', 'png'):
+ kwant.plot(syst, file="ab_ring_syst." + extension,
+ fig_size=size, dpi=_defs.dpi)
+
# Finalize the system.
syst = syst.finalized()
# We should see a conductance that is periodic with the flux quantum
plot_conductance(syst, energy=0.15, fluxes=[0.01 * i * 3 * 2 * pi
for i in range(100)])
+ # Finally, some plots needed for the notes
+ syst = make_system_note1()
+ for extension in ('pdf', 'png'):
+ kwant.plot(syst, file="ab_ring_note1." + extension,
+ fig_size=size, dpi=_defs.dpi)
+ syst = make_system_note2()
+ for extension in ('pdf', 'png'):
+ kwant.plot(syst, file="ab_ring_note2." + extension,
+ fig_size=size, dpi=_defs.dpi)
+
+
# Call the main function if the script gets executed (as opposed to imported).
# See <http://docs.python.org/library/__main__.html>.
if __name__ == '__main__':
main()
@@ -1,52 +1,62 @@
# Tutorial 2.4.1. Band structure calculations
# ===========================================
#
# Physics background
# ------------------
# band structure of a simple quantum wire in tight-binding approximation
#
# Kwant features highlighted
# --------------------------
# - Computing the band structure of a finalized lead.
+import _defs
import kwant
# For plotting.
from matplotlib import pyplot
#HIDDEN_BEGIN_zxip
def make_lead(a=1, t=1.0, W=10):
# Start with an empty lead with a single square lattice
lat = kwant.lattice.square(a)
sym_lead = kwant.TranslationalSymmetry((-a, 0))
lead = kwant.Builder(sym_lead)
# build up one unit cell of the lead, and add the hoppings
# to the next unit cell
for j in range(W):
lead[lat(0, j)] = 4 * t
if j > 0:
lead[lat(0, j), lat(0, j - 1)] = -t
lead[lat(1, j), lat(0, j)] = -t
return lead
#HIDDEN_END_zxip
#HIDDEN_BEGIN_pejz
def main():
lead = make_lead().finalized()
- kwant.plotter.bands(lead, show=False)
- pyplot.xlabel("momentum [(lattice constant)^-1]")
- pyplot.ylabel("energy [t]")
- pyplot.show()
+ fig = kwant.plotter.bands(lead, show=False)
+ pyplot.xlabel("momentum [(lattice constant)^-1]",
+ fontsize=_defs.mpl_label_size)
+ pyplot.ylabel("energy [t]", fontsize=_defs.mpl_label_size)
+ pyplot.setp(fig.get_axes()[0].get_xticklabels(),
+ fontsize=_defs.mpl_tick_size)
+ pyplot.setp(fig.get_axes()[0].get_yticklabels(),
+ fontsize=_defs.mpl_tick_size)
+ fig.set_size_inches(_defs.mpl_width_in, _defs.mpl_width_in * 3. / 4.)
+ fig.subplots_adjust(left=0.15, right=0.95, top=0.95, bottom=0.15)
+ for extension in ('pdf', 'png'):
+ fig.savefig("band_structure_result." + extension, dpi=_defs.dpi)
+
#HIDDEN_END_pejz
# Call the main function if the script gets executed (as opposed to imported).
# See <http://docs.python.org/library/__main__.html>.
if __name__ == '__main__':
main()
@@ -1,144 +1,161 @@
# Tutorial 2.4.2. Closed systems
# ==============================
#
# Physics background
# ------------------
# Fock-darwin spectrum of a quantum dot (energy spectrum in
# as a function of a magnetic field)
#
# Kwant features highlighted
# --------------------------
# - Use of `hamiltonian_submatrix` in order to obtain a Hamiltonian
# matrix.
+import _defs
from cmath import exp
import numpy as np
import kwant
# For eigenvalue computation
#HIDDEN_BEGIN_tibv
import scipy.sparse.linalg as sla
#HIDDEN_END_tibv
# For plotting
from matplotlib import pyplot
def make_system(a=1, t=1.0, r=10):
# Start with an empty tight-binding system and a single square lattice.
# `a` is the lattice constant (by default set to 1 for simplicity).
#HIDDEN_BEGIN_qlyd
lat = kwant.lattice.square(a, norbs=1)
syst = kwant.Builder()
# Define the quantum dot
def circle(pos):
(x, y) = pos
rsq = x ** 2 + y ** 2
return rsq < r ** 2
def hopx(site1, site2, B):
# The magnetic field is controlled by the parameter B
y = site1.pos[1]
return -t * exp(-1j * B * y)
syst[lat.shape(circle, (0, 0))] = 4 * t
# hoppings in x-direction
syst[kwant.builder.HoppingKind((1, 0), lat, lat)] = hopx
# hoppings in y-directions
syst[kwant.builder.HoppingKind((0, 1), lat, lat)] = -t
# It's a closed system for a change, so no leads
return syst
#HIDDEN_END_qlyd
#HIDDEN_BEGIN_yvri
def plot_spectrum(syst, Bfields):
energies = []
for B in Bfields:
# Obtain the Hamiltonian as a sparse matrix
ham_mat = syst.hamiltonian_submatrix(params=dict(B=B), sparse=True)
# we only calculate the 15 lowest eigenvalues
ev = sla.eigsh(ham_mat.tocsc(), k=15, sigma=0,
return_eigenvectors=False)
energies.append(ev)
- pyplot.figure()
+ fig = pyplot.figure()
pyplot.plot(Bfields, energies)
- pyplot.xlabel("magnetic field [arbitrary units]")
- pyplot.ylabel("energy [t]")
- pyplot.show()
+ pyplot.xlabel("magnetic field [arbitrary units]",
+ fontsize=_defs.mpl_label_size)
+ pyplot.ylabel("energy [t]", fontsize=_defs.mpl_label_size)
+ pyplot.setp(fig.get_axes()[0].get_xticklabels(),
+ fontsize=_defs.mpl_tick_size)
+ pyplot.setp(fig.get_axes()[0].get_yticklabels(),
+ fontsize=_defs.mpl_tick_size)
+ fig.set_size_inches(_defs.mpl_width_in, _defs.mpl_width_in * 3. / 4.)
+ fig.subplots_adjust(left=0.15, right=0.95, top=0.95, bottom=0.15)
+ for extension in ('pdf', 'png'):
+ fig.savefig("closed_system_result." + extension, dpi=_defs.dpi)
#HIDDEN_END_yvri
def sorted_eigs(ev):
evals, evecs = ev
evals, evecs = map(np.array, zip(*sorted(zip(evals, evecs.transpose()))))
return evals, evecs.transpose()
#HIDDEN_BEGIN_wave
def plot_wave_function(syst, B=0.001):
+ size = (_defs.figwidth_in, _defs.figwidth_in)
+
# Calculate the wave functions in the system.
ham_mat = syst.hamiltonian_submatrix(sparse=True, params=dict(B=B))
evals, evecs = sorted_eigs(sla.eigsh(ham_mat.tocsc(), k=20, sigma=0))
# Plot the probability density of the 10th eigenmode.
- kwant.plotter.map(syst, np.abs(evecs[:, 9])**2,
- colorbar=False, oversampling=1)
+ for extension in ('pdf', 'png'):
+ kwant.plotter.map(
+ syst, np.abs(evecs[:, 9])**2, colorbar=False, oversampling=1,
+ file="closed_system_eigenvector." + extension,
+ fig_size=size, dpi=_defs.dpi)
#HIDDEN_END_wave
#HIDDEN_BEGIN_current
def plot_current(syst, B=0.001):
+ size = (_defs.figwidth_in, _defs.figwidth_in)
+
# Calculate the wave functions in the system.
ham_mat = syst.hamiltonian_submatrix(sparse=True, params=dict(B=B))
evals, evecs = sorted_eigs(sla.eigsh(ham_mat.tocsc(), k=20, sigma=0))
# Calculate and plot the local current of the 10th eigenmode.
J = kwant.operator.Current(syst)
current = J(evecs[:, 9], params=dict(B=B))
- kwant.plotter.current(syst, current, colorbar=False)
+ for extension in ('pdf', 'png'):
+ kwant.plotter.current(
+ syst, current, colorbar=False,
+ file="closed_system_current." + extension,
+ fig_size=size, dpi=_defs.dpi)
#HIDDEN_END_current
def main():
syst = make_system()
- # Check that the system looks as intended.
- kwant.plot(syst)
-
# Finalize the system.
syst = syst.finalized()
# The following try-clause can be removed once SciPy 0.9 becomes uncommon.
try:
# We should observe energy levels that flow towards Landau
# level energies with increasing magnetic field.
plot_spectrum(syst, [iB * 0.002 for iB in range(100)])
# Plot an eigenmode of a circular dot. Here we create a larger system for
# better spatial resolution.
syst = make_system(r=30).finalized()
plot_wave_function(syst)
plot_current(syst)
except ValueError as e:
if e.message == "Input matrix is not real-valued.":
print("The calculation of eigenvalues failed because of a bug in SciPy 0.9.")
print("Please upgrade to a newer version of SciPy.")
else:
raise
# Call the main function if the script gets executed (as opposed to imported).
# See <http://docs.python.org/library/__main__.html>.
if __name__ == '__main__':
main()
@@ -1,225 +1,239 @@
# Tutorial 2.9. Processing continuum Hamiltonians with discretize
# ===============================================================
#
# Physics background
# ------------------
# - tight-binding approximation of continuous Hamiltonians
#
# Kwant features highlighted
# --------------------------
# - kwant.continuum.discretize
+import _defs
import kwant
#HIDDEN_BEGIN_import
import kwant.continuum
#HIDDEN_END_import
import scipy.sparse.linalg
import scipy.linalg
import numpy as np
# For plotting
import matplotlib as mpl
from matplotlib import pyplot as plt
+def save_figure(file_name):
+ if not file_name:
+ return
+ for extension in ('pdf', 'png'):
+ plt.savefig('.'.join((file_name,extension)),
+ dpi=_defs.dpi, bbox_inches='tight')
+
+
def stadium_system(L=20, W=20):
#HIDDEN_BEGIN_template
hamiltonian = "k_x**2 + k_y**2 + V(x, y)"
template = kwant.continuum.discretize(hamiltonian)
- print(template)
+ with open('discretizer_verbose.txt', 'w') as f:
+ print(template, file=f)
#HIDDEN_END_template
#HIDDEN_BEGIN_fill
def stadium(site):
(x, y) = site.pos
x = max(abs(x) - 20, 0)
return x**2 + y**2 < 30**2
syst = kwant.Builder()
syst.fill(template, stadium, (0, 0));
syst = syst.finalized()
#HIDDEN_END_fill
return syst
#HIDDEN_BEGIN_plot_eigenstate
def plot_eigenstate(syst, n=2, Vx=.0003, Vy=.0005):
def potential(x, y):
return Vx * x + Vy * y
ham = syst.hamiltonian_submatrix(params=dict(V=potential), sparse=True)
evecs = scipy.sparse.linalg.eigsh(ham, k=10, which='SM')[1]
kwant.plotter.density(syst, abs(evecs[:, n])**2, show=False)
#HIDDEN_END_plot_eigenstate
- plt.show()
+ save_figure('discretizer_gs')
def qsh_system(a=20, L=2000, W=1000):
#HIDDEN_BEGIN_define_qsh
hamiltonian = """
+ C * identity(4) + M * kron(sigma_0, sigma_z)
- B * (k_x**2 + k_y**2) * kron(sigma_0, sigma_z)
- D * (k_x**2 + k_y**2) * kron(sigma_0, sigma_0)
+ A * k_x * kron(sigma_z, sigma_x)
- A * k_y * kron(sigma_0, sigma_y)
"""
template = kwant.continuum.discretize(hamiltonian, grid=a)
#HIDDEN_END_define_qsh
#HIDDEN_BEGIN_define_qsh_build
def shape(site):
(x, y) = site.pos
return (0 <= y < W and 0 <= x < L)
def lead_shape(site):
(x, y) = site.pos
return (0 <= y < W)
syst = kwant.Builder()
syst.fill(template, shape, (0, 0))
lead = kwant.Builder(kwant.TranslationalSymmetry([-a, 0]))
lead.fill(template, lead_shape, (0, 0))
syst.attach_lead(lead)
syst.attach_lead(lead.reversed())
syst = syst.finalized()
#HIDDEN_END_define_qsh_build
return syst
def analyze_qsh():
params = dict(A=3.65, B=-68.6, D=-51.1, M=-0.01, C=0)
syst = qsh_system()
#HIDDEN_BEGIN_plot_qsh_band
kwant.plotter.bands(syst.leads[0], params=params,
momenta=np.linspace(-0.3, 0.3, 201), show=False)
#HIDDEN_END_plot_qsh_band
plt.grid()
plt.xlim(-.3, 0.3)
plt.ylim(-0.05, 0.05)
plt.xlabel('momentum [1/A]')
plt.ylabel('energy [eV]')
- plt.show()
+ save_figure('discretizer_qsh_band')
#HIDDEN_BEGIN_plot_qsh_wf
+
# get scattering wave functions at E=0
wf = kwant.wave_function(syst, energy=0, params=params)
# prepare density operators
sigma_z = np.array([[1, 0], [0, -1]])
prob_density = kwant.operator.Density(syst, np.eye(4))
spin_density = kwant.operator.Density(syst, np.kron(sigma_z, np.eye(2)))
# calculate expectation values and plot them
wf_sqr = sum(prob_density(psi) for psi in wf(0)) # states from left lead
rho_sz = sum(spin_density(psi) for psi in wf(0)) # states from left lead
fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True, figsize=(16, 4))
kwant.plotter.density(syst, wf_sqr, ax=ax1)
kwant.plotter.density(syst, rho_sz, ax=ax2)
#HIDDEN_END_plot_qsh_wf
ax = ax1
im = [obj for obj in ax.get_children()
if isinstance(obj, mpl.image.AxesImage)][0]
fig.colorbar(im, ax=ax)
ax = ax2
im = [obj for obj in ax.get_children()
if isinstance(obj, mpl.image.AxesImage)][0]
fig.colorbar(im, ax=ax)
ax1.set_title('Probability density')
ax2.set_title('Spin density')
- plt.show()
+ save_figure('discretizer_qsh_wf')
def lattice_spacing():
#HIDDEN_BEGIN_ls_def
hamiltonian = "k_x**2 * identity(2) + alpha * k_x * sigma_y"
params = dict(alpha=.5)
#HIDDEN_END_ls_def
def plot(ax, a=1):
#HIDDEN_BEGIN_ls_hk_cont
h_k = kwant.continuum.lambdify(hamiltonian, locals=params)
k_cont = np.linspace(-4, 4, 201)
e_cont = [scipy.linalg.eigvalsh(h_k(k_x=ki)) for ki in k_cont]
#HIDDEN_END_ls_hk_cont
#HIDDEN_BEGIN_ls_hk_tb
template = kwant.continuum.discretize(hamiltonian, grid=a)
syst = kwant.wraparound.wraparound(template).finalized()
def h_k(k_x):
p = dict(k_x=k_x, **params)
return syst.hamiltonian_submatrix(params=p)
k_tb = np.linspace(-np.pi/a, np.pi/a, 201)
e_tb = [scipy.linalg.eigvalsh(h_k(k_x=a*ki)) for ki in k_tb]
#HIDDEN_END_ls_hk_tb
ax.plot(k_cont, e_cont, 'r-')
ax.plot(k_tb, e_tb, 'k-')
ax.plot([], [], 'r-', label='continuum')
ax.plot([], [], 'k-', label='tight-binding')
ax.set_xlim(-4, 4)
ax.set_ylim(-1, 14)
ax.set_title('a={}'.format(a))
ax.set_xlabel('momentum [a.u.]')
ax.set_ylabel('energy [a.u.]')
ax.grid()
ax.legend()
_, (ax1, ax2) = plt.subplots(1, 2, sharey=True, figsize=(12, 4))
plot(ax1, a=1)
plot(ax2, a=.25)
- plt.show()
+ save_figure('discretizer_lattice_spacing')
def substitutions():
#HIDDEN_BEGIN_subs_1
sympify = kwant.continuum.sympify
subs = {'sx': [[0, 1], [1, 0]], 'sz': [[1, 0], [0, -1]]}
e = (
sympify('[[k_x**2, alpha * k_x], [k_x * alpha, -k_x**2]]'),
sympify('k_x**2 * sigma_z + alpha * k_x * sigma_x'),
sympify('k_x**2 * sz + alpha * k_x * sx', locals=subs),
)
- print(e[0] == e[1] == e[2])
+ with open('discretizer_subs_1.txt', 'w') as f:
+ print(e[0] == e[1] == e[2], file=f)
#HIDDEN_END_subs_1
#HIDDEN_BEGIN_subs_2
subs = {'A': 'A(x) + B', 'V': 'V(x) + V_0', 'C': 5}
- print(sympify('k_x * A * k_x + V + C', locals=subs))
+ with open('discretizer_subs_2.txt', 'w') as f:
+ print(sympify('k_x * A * k_x + V + C', locals=subs), file=f)
#HIDDEN_END_subs_2
def main():
#HIDDEN_BEGIN_symbolic_discretization
template = kwant.continuum.discretize('k_x * A(x) * k_x')
- print(template)
+ with open('discretizer_intro_verbose.txt', 'w') as f:
+ print(template, file=f)
#HIDDEN_END_symbolic_discretization
syst = stadium_system()
plot_eigenstate(syst)
analyze_qsh()
lattice_spacing()
substitutions()
# Call the main function if the script gets executed (as opposed to imported).
# See <http://docs.python.org/library/__main__.html>.
if __name__ == '__main__':
main()
@@ -1,450 +1,479 @@
# Frequently asked questions
#
# This script is a disorganized collection of code snippets. As a whole, it is
# not meant as an example of good programming practice.
+import _defs
import kwant
import numpy as np
import tinyarray
import matplotlib
from matplotlib import pyplot as plt
matplotlib.rcParams['figure.figsize'] = (3.5, 3.5)
+def save_figure(file_name):
+ for extension in ('pdf', 'png'):
+ plt.savefig('.'.join((file_name, extension)),
+ dpi=_defs.dpi, bbox_inches='tight')
+
+
#### What is a Site?
#HIDDEN_BEGIN_site
a = 1
lat = kwant.lattice.square(a)
syst = kwant.Builder()
syst[lat(1, 0)] = 4
syst[lat(1, 1)] = 4
kwant.plot(syst)
+save_figure("faq_site")
#HIDDEN_END_site
#### What is a hopping?
a = 1
lat = kwant.lattice.square(a)
syst = kwant.Builder()
syst[lat(1, 0)] = 4
syst[lat(1, 1)] = 4
#HIDDEN_BEGIN_hopping
syst[(lat(1, 0), lat(1, 1))] = 1j
#HIDDEN_END_hopping
kwant.plot(syst)
+save_figure("faq_hopping")
#### What is a lattice?
#HIDDEN_BEGIN_lattice_monatomic
# Two monatomic lattices
primitive_vectors = [(1, 0), (0, 1)]
lat_a = kwant.lattice.Monatomic(primitive_vectors, offset=(0, 0))
lat_b = kwant.lattice.Monatomic(primitive_vectors, offset=(0.5, 0.5))
# lat1 is equivalent to kwant.lattice.square()
syst = kwant.Builder()
syst[lat_a(0, 0)] = 4
syst[lat_b(0, 0)] = 4
kwant.plot(syst)
+save_figure("faq_lattice")
#HIDDEN_END_lattice_monatomic
#HIDDEN_BEGIN_lattice_polyatomic
# One polyatomic lattice containing two sublattices
lat = kwant.lattice.Polyatomic([(1, 0), (0, 1)], [(0, 0), (0.5, 0.5)])
sub_a, sub_b = lat.sublattices
#HIDDEN_END_lattice_polyatomic
#### How to make a hole in a system?
#HIDDEN_BEGIN_hole
# Define the lattice and the (empty) system
a = 2
lat = kwant.lattice.cubic(a)
syst = kwant.Builder()
L = 10
W = 10
H = 2
# Add sites to the system in a cuboid
syst[(lat(i, j, k) for i in range(L) for j in range(W) for k in range(H))] = 4
kwant.plot(syst)
+save_figure("faq_hole1")
# Delete sites to create a hole
def in_hole(site):
x, y, z = site.pos / a - (L/2, W/2, H/2) # position relative to centre
return abs(x) < L / 4 and abs(y) < W / 4
for site in filter(in_hole, list(syst.sites())):
del syst[site]
kwant.plot(syst)
+save_figure("faq_hole2")
#HIDDEN_END_hole
#### How can we get access to the sites of our system?
builder = kwant.Builder()
lat = kwant.lattice.square()
builder[(lat(i, j) for i in range(3) for j in range(3))] = 4
#HIDDEN_BEGIN_sites1
# Before finalizing the system
sites = list(builder.sites()) # sites() doe *not* return a list
#HIDDEN_END_sites1
#HIDDEN_BEGIN_sites2
# After finalizing the system
syst = builder.finalized()
sites = syst.sites # syst.sites is an actual list
#HIDDEN_END_sites2
#HIDDEN_BEGIN_sites3
i = syst.id_by_site[lat(0, 2)] # we want the id of the site lat(0, 2)
#HIDDEN_END_sites3
#### How to plot a polyatomic lattice with different colors?
#HIDDEN_BEGIN_colors1
lat = kwant.lattice.kagome()
syst = kwant.Builder()
a, b, c = lat.sublattices # The kagome lattice has 3 sublattices
#HIDDEN_END_colors1
#HIDDEN_BEGIN_colors2
# Plot sites from different families in different colors
def family_color(site):
if site.family == a:
return 'red'
if site.family == b:
return 'green'
else:
return 'blue'
def plot_system(syst):
kwant.plot(syst, site_lw=0.1, site_color=family_color)
## Add sites and hoppings.
for i in range(4):
for j in range (4):
syst[a(i, j)] = 4
syst[b(i, j)] = 4
syst[c(i, j)] = 4
syst[lat.neighbors()] = -1
## Plot the system.
plot_system(syst)
+save_figure("faq_colors")
#HIDDEN_END_colors2
-
#### How to create all hoppings in a given direction using Hoppingkind?
# Monatomic lattice
#HIDDEN_BEGIN_direction1
# Create hopping between neighbors with HoppingKind
a = 1
syst = kwant.Builder()
lat = kwant.lattice.square(a)
syst[ (lat(i, j) for i in range(5) for j in range(5)) ] = 4
syst[kwant.builder.HoppingKind((1, 0), lat)] = -1
kwant.plot(syst)
+save_figure("faq_direction1")
#HIDDEN_END_direction1
# Polyatomic lattice
lat = kwant.lattice.kagome()
syst = kwant.Builder()
a, b, c = lat.sublattices # The kagome lattice has 3 sublattices
def family_color(site):
if site.family == a:
return 'red'
if site.family == b:
return 'green'
else:
return 'blue'
def plot_system(syst):
kwant.plot(syst, site_size=0.15, site_lw=0.05, site_color=family_color)
for i in range(4):
for j in range (4):
syst[a(i, j)] = 4
syst[b(i, j)] = 4
syst[c(i, j)] = 4
#HIDDEN_BEGIN_direction2
# equivalent to syst[kwant.builder.HoppingKind((0, 1), b)] = -1
syst[kwant.builder.HoppingKind((0, 1), b, b)] = -1
#HIDDEN_END_direction2
plot_system(syst)
+save_figure("faq_direction2")
# Delete the hoppings previously created
del syst[kwant.builder.HoppingKind((0, 1), b, b)]
#HIDDEN_BEGIN_direction3
syst[kwant.builder.HoppingKind((0, 0), a, b)] = -1
syst[kwant.builder.HoppingKind((0, 0), a, c)] = -1
syst[kwant.builder.HoppingKind((0, 0), c, b)] = -1
#HIDDEN_END_direction3
plot_system(syst)
+save_figure("faq_direction3")
#### How to create the hoppings between adjacent sites?
# Monatomic lattice
#HIDDEN_BEGIN_adjacent1
# Create hoppings with lat.neighbors()
syst = kwant.Builder()
lat = kwant.lattice.square()
syst[(lat(i, j) for i in range(3) for j in range(3))] = 4
syst[lat.neighbors()] = -1 # Equivalent to lat.neighbors(1)
kwant.plot(syst)
+save_figure("faq_adjacent1")
del syst[lat.neighbors()] # Delete all nearest-neighbor hoppings
syst[lat.neighbors(2)] = -1
kwant.plot(syst)
+save_figure("faq_adjacent2")
#HIDDEN_END_adjacent1
# Polyatomic lattice
#HIDDEN_BEGIN_FAQ6
# Hoppings using .neighbors()
#HIDDEN_BEGIN_adjacent2
# Create the system
lat = kwant.lattice.kagome()
syst = kwant.Builder()
a, b, c = lat.sublattices # The kagome lattice has 3 sublattices
for i in range(4):
for j in range (4):
syst[a(i, j)] = 4 # red
syst[b(i, j)] = 4 # green
syst[c(i, j)] = 4 # blue
syst[lat.neighbors()] = -1
#HIDDEN_END_adjacent2
plot_system(syst)
+save_figure("faq_adjacent3")
del syst[lat.neighbors()] # Delete the hoppings previously created
#HIDDEN_BEGIN_adjacent3
syst[a.neighbors()] = -1
#HIDDEN_END_adjacent3
plot_system(syst)
+save_figure("faq_adjacent4")
del syst[a.neighbors()] # Delete the hoppings previously created
syst[lat.neighbors(2)] = -1
plot_system(syst)
del syst[lat.neighbors(2)]
#### How to create a lead with a lattice different from the scattering region?
# Plot sites from different families in different colors
def plot_system(syst):
def family_color(site):
if site.family == subA:
return 'blue'
if site.family == subB:
return 'yellow'
else:
return 'green'
kwant.plot(syst, site_lw=0.1, site_color=family_color)
#HIDDEN_BEGIN_different_lattice1
# Define the scattering Region
L = 5
W = 5
lat = kwant.lattice.honeycomb()
subA, subB = lat.sublattices
syst = kwant.Builder()
syst[(subA(i, j) for i in range(L) for j in range(W))] = 4
syst[(subB(i, j) for i in range(L) for j in range(W))] = 4
syst[lat.neighbors()] = -1
#HIDDEN_END_different_lattice1
plot_system(syst)
+save_figure("faq_different_lattice1")
#HIDDEN_BEGIN_different_lattice2
# Create a lead
lat_lead = kwant.lattice.square()
sym_lead1 = kwant.TranslationalSymmetry((0, 1))
lead1 = kwant.Builder(sym_lead1)
lead1[(lat_lead(i, 0) for i in range(2, 7))] = 4
lead1[lat_lead.neighbors()] = -1
#HIDDEN_END_different_lattice2
plot_system(lead1)
+save_figure("faq_different_lattice2")
#HIDDEN_BEGIN_different_lattice3
syst[(lat_lead(i, 5) for i in range(2, 7))] = 4
syst[lat_lead.neighbors()] = -1
# Manually attach sites from graphene to square lattice
syst[((lat_lead(i+2, 5), subB(i, 4)) for i in range(5))] = -1
#HIDDEN_END_different_lattice3
plot_system(syst)
+save_figure("faq_different_lattice3")
#HIDDEN_BEGIN_different_lattice4
syst.attach_lead(lead1)
#HIDDEN_END_different_lattice4
plot_system(syst)
+save_figure("faq_different_lattice4")
#### How to cut a finite system out of a system with translationnal symmetries?
#HIDDEN_BEGIN_fill1
# Create 3d model.
cubic = kwant.lattice.cubic()
sym_3d = kwant.TranslationalSymmetry([1, 0, 0], [0, 1, 0], [0, 0, 1])
model = kwant.Builder(sym_3d)
model[cubic(0, 0, 0)] = 4
model[cubic.neighbors()] = -1
#HIDDEN_END_fill1
#HIDDEN_BEGIN_fill2
# Build scattering region (white).
def cuboid_shape(site):
x, y, z = abs(site.pos)
return x < 4 and y < 10 and z < 3
cuboid = kwant.Builder()
cuboid.fill(model, cuboid_shape, (0, 0, 0));
#HIDDEN_END_fill2
kwant.plot(cuboid);
+save_figure("faq_fill2")
#HIDDEN_BEGIN_fill3
# Build electrode (black).
def electrode_shape(site):
x, y, z = site.pos - (0, 5, 2)
return y**2 + z**2 < 2.3**2
electrode = kwant.Builder(kwant.TranslationalSymmetry([1, 0, 0]))
electrode.fill(model, electrode_shape, (0, 5, 2)) # lead
# Scattering region
cuboid.fill(electrode, lambda s: abs(s.pos[0]) < 7, (0, 5, 4))
cuboid.attach_lead(electrode)
#HIDDEN_END_fill3
kwant.plot(cuboid);
+save_figure("faq_fill3")
#### How does Kwant order the propagating modes of a lead?
#HIDDEN_BEGIN_pm
lat = kwant.lattice.square()
lead = kwant.Builder(kwant.TranslationalSymmetry((-1, 0)))
lead[(lat(0, i) for i in range(3))] = 4
lead[lat.neighbors()] = -1
flead = lead.finalized()
E = 2.5
prop_modes, _ = flead.modes(energy=E)
#HIDDEN_END_pm
def plot_and_label_modes(lead, E):
# Plot the different modes
pmodes, _ = lead.modes(energy=E)
kwant.plotter.bands(lead, show=False)
for i, k in enumerate(pmodes.momenta):
plt.plot(k, E, 'ko')
plt.annotate(str(i), xy=(k, E), xytext=(-5, 8),
textcoords='offset points',
bbox=dict(boxstyle='round,pad=0.1',fc='white', alpha=0.7))
plt.plot([-3, 3], [E, E], 'r--')
plt.ylim(E-1, E+1)
plt.xlim(-2, 2)
plt.xlabel("momentum")
plt.ylabel("energy")
plt.show()
plot_and_label_modes(flead, E)
+save_figure('faq_pm1')
# More involved example
s0 = np.eye(2)
sz = np.array([[1, 0], [0, -1]])
lead2 = kwant.Builder(kwant.TranslationalSymmetry((-1, 0)))
lead2[(lat(0, i) for i in range(2))] = np.diag([1.8, -1])
lead2[lat.neighbors()] = -1 * sz
flead2 = lead2.finalized()
plot_and_label_modes(flead2, 1)
+save_figure('faq_pm2')
#### How does Kwant order components of an individual wavefunction?
def circle(R):
return lambda r: np.linalg.norm(r) < R
def make_system(lat):
norbs = lat.norbs
syst = kwant.Builder()
syst[lat.shape(circle(3), (0, 0))] = 4 * np.eye(norbs)
syst[lat.neighbors()] = -1 * np.eye(norbs)
lead = kwant.Builder(kwant.TranslationalSymmetry((-1, 0)))
lead[(lat(0, i) for i in range(-1, 2))] = 4 * np.eye(norbs)
lead[lat.neighbors()] = -1 * np.eye(norbs)
syst.attach_lead(lead)
syst.attach_lead(lead.reversed())
return syst.finalized()
#HIDDEN_BEGIN_ord1
lat = kwant.lattice.square(norbs=1)
syst = make_system(lat)
scattering_states = kwant.wave_function(syst, energy=1)
wf = scattering_states(0)[0] # scattering state from lead 0 incoming in mode 0
idx = syst.id_by_site[lat(0, 0)] # look up index of site
-print('wavefunction on lat(0, 0): ', wf[idx])
+with open('faq_ord1.txt', 'w') as f:
+ print('wavefunction on lat(0, 0): ', wf[idx], file=f)
#HIDDEN_END_ord1
#HIDDEN_BEGIN_ord2
lat = kwant.lattice.square(norbs=2)
syst = make_system(lat)
scattering_states = kwant.wave_function(syst, energy=1)
wf = scattering_states(0)[0] # scattering state from lead 0 incoming in mode 0
idx = syst.id_by_site[lat(0, 0)] # look up index of site
# Group consecutive degrees of freedom from 'wf' together; these correspond
# to degrees of freedom on the same site.
wf = wf.reshape(-1, 2)
-print('wavefunction on lat(0, 0): ', wf[idx])
+with open('faq_ord2.txt', 'w') as f:
+ print('wavefunction on lat(0, 0): ', wf[idx], file=f)
#HIDDEN_END_ord2
@@ -1,179 +1,203 @@
# Tutorial 2.5. Beyond square lattices: graphene
# ==============================================
#
# Physics background
# ------------------
# Transport through a graphene quantum dot with a pn-junction
#
# Kwant features highlighted
# --------------------------
# - Application of all the aspects of tutorials 1-3 to a more complicated
# lattice, namely graphene
+import _defs
from math import pi, sqrt, tanh
import kwant
# For computing eigenvalues
import scipy.sparse.linalg as sla
# For plotting
from matplotlib import pyplot
# Define the graphene lattice
sin_30, cos_30 = (1 / 2, sqrt(3) / 2)
#HIDDEN_BEGIN_hnla
graphene = kwant.lattice.general([(1, 0), (sin_30, cos_30)],
[(0, 0), (0, 1 / sqrt(3))])
a, b = graphene.sublattices
#HIDDEN_END_hnla
#HIDDEN_BEGIN_shzy
def make_system(r=10, w=2.0, pot=0.1):
#### Define the scattering region. ####
# circular scattering region
def circle(pos):
x, y = pos
return x ** 2 + y ** 2 < r ** 2
syst = kwant.Builder()
# w: width and pot: potential maximum of the p-n junction
def potential(site):
(x, y) = site.pos
d = y * cos_30 + x * sin_30
return pot * tanh(d / w)
syst[graphene.shape(circle, (0, 0))] = potential
#HIDDEN_END_shzy
# specify the hoppings of the graphene lattice in the
# format expected by builder.HoppingKind
#HIDDEN_BEGIN_hsmc
hoppings = (((0, 0), a, b), ((0, 1), a, b), ((-1, 1), a, b))
#HIDDEN_END_hsmc
#HIDDEN_BEGIN_bfwb
syst[[kwant.builder.HoppingKind(*hopping) for hopping in hoppings]] = -1
#HIDDEN_END_bfwb
# Modify the scattering region
#HIDDEN_BEGIN_efut
del syst[a(0, 0)]
syst[a(-2, 1), b(2, 2)] = -1
#HIDDEN_END_efut
#### Define the leads. ####
#HIDDEN_BEGIN_aakh
# left lead
sym0 = kwant.TranslationalSymmetry(graphene.vec((-1, 0)))
def lead0_shape(pos):
x, y = pos
return (-0.4 * r < y < 0.4 * r)
lead0 = kwant.Builder(sym0)
lead0[graphene.shape(lead0_shape, (0, 0))] = -pot
lead0[[kwant.builder.HoppingKind(*hopping) for hopping in hoppings]] = -1
# The second lead, going to the top right
sym1 = kwant.TranslationalSymmetry(graphene.vec((0, 1)))
def lead1_shape(pos):
v = pos[1] * sin_30 - pos[0] * cos_30
return (-0.4 * r < v < 0.4 * r)
lead1 = kwant.Builder(sym1)
lead1[graphene.shape(lead1_shape, (0, 0))] = pot
lead1[[kwant.builder.HoppingKind(*hopping) for hopping in hoppings]] = -1
#HIDDEN_END_aakh
#HIDDEN_BEGIN_kmmw
return syst, [lead0, lead1]
#HIDDEN_END_kmmw
#HIDDEN_BEGIN_zydk
def compute_evs(syst):
# Compute some eigenvalues of the closed system
sparse_mat = syst.hamiltonian_submatrix(sparse=True)
evs = sla.eigs(sparse_mat, 2)[0]
print(evs.real)
#HIDDEN_END_zydk
def plot_conductance(syst, energies):
# Compute transmission as a function of energy
data = []
for energy in energies:
smatrix = kwant.smatrix(syst, energy)
data.append(smatrix.transmission(0, 1))
- pyplot.figure()
+ fig = pyplot.figure()
pyplot.plot(energies, data)
- pyplot.xlabel("energy [t]")
- pyplot.ylabel("conductance [e^2/h]")
- pyplot.show()
+ pyplot.xlabel("energy [t]",
+ fontsize=_defs.mpl_label_size)
+ pyplot.ylabel("conductance [e^2/h]",
+ fontsize=_defs.mpl_label_size)
+ pyplot.setp(fig.get_axes()[0].get_xticklabels(),
+ fontsize=_defs.mpl_tick_size)
+ pyplot.setp(fig.get_axes()[0].get_yticklabels(),
+ fontsize=_defs.mpl_tick_size)
+ fig.set_size_inches(_defs.mpl_width_in, _defs.mpl_width_in * 3. / 4.)
+ fig.subplots_adjust(left=0.15, right=0.95, top=0.95, bottom=0.15)
+ for extension in ('pdf', 'png'):
+ fig.savefig("graphene_result." + extension, dpi=_defs.dpi)
def plot_bandstructure(flead, momenta):
bands = kwant.physics.Bands(flead)
energies = [bands(k) for k in momenta]
- pyplot.figure()
+ fig = pyplot.figure()
pyplot.plot(momenta, energies)
- pyplot.xlabel("momentum [(lattice constant)^-1]")
- pyplot.ylabel("energy [t]")
- pyplot.show()
+ pyplot.xlabel("momentum [(lattice constant)^-1]",
+ fontsize=_defs.mpl_label_size)
+ pyplot.ylabel("energy [t]",
+ fontsize=_defs.mpl_label_size)
+ pyplot.setp(fig.get_axes()[0].get_xticklabels(),
+ fontsize=_defs.mpl_tick_size)
+ pyplot.setp(fig.get_axes()[0].get_yticklabels(),
+ fontsize=_defs.mpl_tick_size)
+ fig.set_size_inches(_defs.mpl_width_in, _defs.mpl_width_in * 3. / 4.)
+ fig.subplots_adjust(left=0.15, right=0.95, top=0.95, bottom=0.15)
+ for extension in ('pdf', 'png'):
+ fig.savefig("graphene_bs." + extension, dpi=_defs.dpi)
#HIDDEN The part of the following code block which begins with family_colors
#HIDDEN is included verbatim in the tutorial text because nested code examples
#HIDDEN are not supported. Remember to update the tutorial text when you
#HIDDEN modify this block.
#HIDDEN_BEGIN_itkk
def main():
pot = 0.1
syst, leads = make_system(pot=pot)
# To highlight the two sublattices of graphene, we plot one with
# a filled, and the other one with an open circle:
def family_colors(site):
return 0 if site.family == a else 1
- # Plot the closed system without leads.
- kwant.plot(syst, site_color=family_colors, site_lw=0.1, colorbar=False)
+ size = (_defs.figwidth_in, _defs.figwidth_in)
+ for extension in ('pdf', 'png'):
+ kwant.plot(syst, site_color=family_colors, site_lw=0.1, colorbar=False,
+ file="graphene_syst1." + extension,
+ fig_size=size, dpi=_defs.dpi)
#HIDDEN_END_itkk
# Compute some eigenvalues.
#HIDDEN_BEGIN_jmbi
compute_evs(syst.finalized())
#HIDDEN_END_jmbi
# Attach the leads to the system.
for lead in leads:
syst.attach_lead(lead)
- # Then, plot the system with leads.
- kwant.plot(syst, site_color=family_colors, site_lw=0.1,
- lead_site_lw=0, colorbar=False)
+ size = (_defs.figwidth_in, 0.9 * _defs.figwidth_in)
+ for extension in ('pdf', 'png'):
+ kwant.plot(syst, site_color=family_colors, colorbar=False, site_lw=0.1,
+ file="graphene_syst2." + extension,
+ fig_size=size, dpi=_defs.dpi, lead_site_lw=0)
# Finalize the system.
syst = syst.finalized()
# Compute the band structure of lead 0.
momenta = [-pi + 0.02 * pi * i for i in range(101)]
plot_bandstructure(syst.leads[0], momenta)
# Plot conductance.
energies = [-2 * pot + 4. / 50. * pot * i for i in range(51)]
plot_conductance(syst, energies)
# Call the main function if the script gets executed (as opposed to imported).
# See <http://docs.python.org/library/__main__.html>.
if __name__ == '__main__':
main()
@@ -1,341 +1,367 @@
# Tutorial 2.8. Calculating spectral density with the Kernel Polynomial Method
# ============================================================================
#
# Physics background
# ------------------
# - Chebyshev polynomials, random trace approximation, spectral densities.
#
# Kwant features highlighted
# --------------------------
# - kpm module,kwant operators.
import scipy
+import _defs
+from contextlib import redirect_stdout
+
# For plotting
from matplotlib import pyplot as plt
#HIDDEN_BEGIN_sys1
# necessary imports
import kwant
import numpy as np
# define the system
def make_syst(r=30, t=-1, a=1):
syst = kwant.Builder()
lat = kwant.lattice.honeycomb(a, norbs=1)
def circle(pos):
x, y = pos
return x ** 2 + y ** 2 < r ** 2
syst[lat.shape(circle, (0, 0))] = 0.
syst[lat.neighbors()] = t
syst.eradicate_dangling()
return syst
#HIDDEN_END_sys1
#HIDDEN_BEGIN_sys2
# define a Haldane system
def make_syst_topo(r=30, a=1, t=1, t2=0.5):
syst = kwant.Builder()
lat = kwant.lattice.honeycomb(a, norbs=1, name=['a', 'b'])
def circle(pos):
x, y = pos
return x ** 2 + y ** 2 < r ** 2
syst[lat.shape(circle, (0, 0))] = 0.
syst[lat.neighbors()] = t
# add second neighbours hoppings
syst[lat.a.neighbors()] = 1j * t2
syst[lat.b.neighbors()] = -1j * t2
syst.eradicate_dangling()
return lat, syst.finalized()
#HIDDEN_END_sys2
#HIDDEN_BEGIN_sys3
# define the system
def make_syst_staggered(r=30, t=-1, a=1, m=0.1):
syst = kwant.Builder()
lat = kwant.lattice.honeycomb(a, norbs=1)
def circle(pos):
x, y = pos
return x ** 2 + y ** 2 < r ** 2
syst[lat.a.shape(circle, (0, 0))] = m
syst[lat.b.shape(circle, (0, 0))] = -m
syst[lat.neighbors()] = t
syst.eradicate_dangling()
return syst
#HIDDEN_END_sys3
# Plot several density of states curves on the same axes.
-def plot_dos(labels_to_data):
+def plot_dos(labels_to_data, file_name=None, ylabel="DoS [a.u.]"):
plt.figure(figsize=(5,4))
for label, (x, y) in labels_to_data:
plt.plot(x, y.real, label=label, linewidth=2)
plt.legend(loc=2, framealpha=0.5)
plt.xlabel("energy [t]")
plt.ylabel(ylabel)
- plt.show()
+ save_figure(file_name)
plt.clf()
# Plot fill density of states plus curves on the same axes.
-def plot_dos_and_curves(dos labels_to_data):
+def plot_dos_and_curves(dos, labels_to_data, file_name=None, ylabel="DoS [a.u.]"):
plt.figure(figsize=(5,4))
plt.fill_between(dos[0], dos[1], label="DoS [a.u.]",
alpha=0.5, color='gray')
for label, (x, y) in labels_to_data:
plt.plot(x, y, label=label, linewidth=2)
plt.legend(loc=2, framealpha=0.5)
plt.xlabel("energy [t]")
plt.ylabel(ylabel)
- plt.show()
+ save_figure(file_name)
plt.clf()
def site_size_conversion(densities):
return 3 * np.abs(densities) / max(densities)
# Plot several local density of states maps in different subplots
def plot_ldos(syst, densities, file_name=None):
fig, axes = plt.subplots(1, len(densities), figsize=(7*len(densities), 7))
for ax, (title, rho) in zip(axes, densities):
kwant.plotter.density(syst, rho.real, ax=ax)
ax.set_title(title)
ax.set(adjustable='box', aspect='equal')
- plt.show()
+ save_figure(file_name)
plt.clf()
+def save_figure(file_name):
+ if not file_name:
+ return
+ for extension in ('pdf', 'png'):
+ plt.savefig('.'.join((file_name,extension)),
+ dpi=_defs.dpi, bbox_inches='tight')
+
+
def simple_dos_example():
#HIDDEN_BEGIN_kpm1
fsyst = make_syst().finalized()
spectrum = kwant.kpm.SpectralDensity(fsyst, rng=0)
#HIDDEN_END_kpm1
#HIDDEN_BEGIN_kpm2
energies, densities = spectrum()
#HIDDEN_END_kpm2
#HIDDEN_BEGIN_kpm3
energy_subset = np.linspace(0, 2)
density_subset = spectrum(energy_subset)
#HIDDEN_END_kpm3
plot_dos([
('densities', (energies, densities)),
('density subset', (energy_subset, density_subset)),
- ])
+ ],
+ file_name='kpm_dos'
+ )
def dos_integrating_example(fsyst):
spectrum = kwant.kpm.SpectralDensity(fsyst, rng=0)
#HIDDEN_BEGIN_int1
- print('identity resolution:', spectrum.integrate())
+ with open('kpm_normalization.txt', 'w') as f:
+ with redirect_stdout(f):
+ print('identity resolution:', spectrum.integrate())
#HIDDEN_END_int1
#HIDDEN_BEGIN_int2
# Fermi energy 0.1 and temperature 0.2
fermi = lambda E: 1 / (np.exp((E - 0.1) / 0.2) + 1)
- print('number of filled states:', spectrum.integrate(fermi))
+ with open('kpm_total_states.txt', 'w') as f:
+ with redirect_stdout(f):
+ print('number of filled states:', spectrum.integrate(fermi))
#HIDDEN_END_int2
def increasing_accuracy_example(fsyst):
spectrum = kwant.kpm.SpectralDensity(fsyst, rng=0)
original_dos = spectrum() # get unaltered DoS
#HIDDEN_BEGIN_acc1
spectrum.add_moments(energy_resolution=0.03)
#HIDDEN_END_acc1
increased_resolution_dos = spectrum()
plot_dos([
('density', original_dos),
('higher energy resolution', increased_resolution_dos),
- ])
+ ],
+ file_name='kpm_dos_acc'
+ )
#HIDDEN_BEGIN_acc2
spectrum.add_moments(100)
spectrum.add_vectors(5)
#HIDDEN_END_acc2
increased_moments_dos = spectrum()
plot_dos([
('density', original_dos),
('higher number of moments', increased_moments_dos),
- ])
+ ],
+ file_name='kpm_dos_r'
+ )
def operator_example(fsyst):
#HIDDEN_BEGIN_op1
# identity matrix
matrix_op = scipy.sparse.eye(len(fsyst.sites))
matrix_spectrum = kwant.kpm.SpectralDensity(fsyst, operator=matrix_op, rng=0)
#HIDDEN_END_op1
#HIDDEN_BEGIN_op2
# 'sum=True' means we sum over all the sites
kwant_op = kwant.operator.Density(fsyst, sum=True)
operator_spectrum = kwant.kpm.SpectralDensity(fsyst, operator=kwant_op, rng=0)
#HIDDEN_END_op2
plot_dos([
('identity matrix', matrix_spectrum()),
('kwant.operator.Density', operator_spectrum()),
])
def ldos_example(fsyst):
#HIDDEN_BEGIN_op3
# 'sum=False' is the default, but we include it explicitly here for clarity.
kwant_op = kwant.operator.Density(fsyst, sum=False)
local_dos = kwant.kpm.SpectralDensity(fsyst, operator=kwant_op, rng=0)
#HIDDEN_END_op3
#HIDDEN_BEGIN_op4
zero_energy_ldos = local_dos(energy=0)
finite_energy_ldos = local_dos(energy=1)
plot_ldos(fsyst, [
('energy = 0', zero_energy_ldos),
('energy = 1', finite_energy_ldos)
- ])
+ ],
+ file_name='kpm_ldos'
+ )
#HIDDEN_END_op4
def ldos_sites_example():
fsyst = make_syst_staggered().finalized()
#HIDDEN_BEGIN_op5
# find 'A' and 'B' sites in the unit cell at the center of the disk
center_tag = np.array([0, 0])
where = lambda s: s.tag == center_tag
# make local vectors
vector_factory = kwant.kpm.LocalVectors(fsyst, where)
#HIDDEN_END_op5
#HIDDEN_BEGIN_op6
# 'num_vectors' can be unspecified when using 'LocalVectors'
local_dos = kwant.kpm.SpectralDensity(fsyst, num_vectors=None,
vector_factory=vector_factory,
mean=False,
rng=0)
energies, densities = local_dos()
plot_dos([
('A sublattice', (energies, densities[:, 0])),
('B sublattice', (energies, densities[:, 1])),
- ])
+ ],
+ file_name='kpm_ldos_sites'
+ )
#HIDDEN_END_op6
def vector_factory_example(fsyst):
spectrum = kwant.kpm.SpectralDensity(fsyst, rng=0)
#HIDDEN_BEGIN_fact1
# construct a generator of vectors with n random elements -1 or +1.
n = fsyst.hamiltonian_submatrix(sparse=True).shape[0]
def binary_vectors():
while True:
yield np.rint(np.random.random_sample(n)) * 2 - 1
custom_factory = kwant.kpm.SpectralDensity(fsyst,
vector_factory=binary_vectors(),
rng=0)
#HIDDEN_END_fact1
plot_dos([
('default vector factory', spectrum()),
('binary vector factory', custom_factory()),
])
def bilinear_map_operator_example(fsyst):
#HIDDEN_BEGIN_blm
rho = kwant.operator.Density(fsyst, sum=True)
# sesquilinear map that does the same thing as `rho`
def rho_alt(bra, ket):
return np.vdot(bra, ket)
rho_spectrum = kwant.kpm.SpectralDensity(fsyst, operator=rho, rng=0)
rho_alt_spectrum = kwant.kpm.SpectralDensity(fsyst, operator=rho_alt, rng=0)
#HIDDEN_END_blm
plot_dos([
('kwant.operator.Density', rho_spectrum()),
('bilinear operator', rho_alt_spectrum()),
])
def conductivity_example():
#HIDDEN_BEGIN_cond
# construct the Haldane model
lat, fsyst = make_syst_topo()
# find 'A' and 'B' sites in the unit cell at the center of the disk
where = lambda s: np.linalg.norm(s.pos) < 1
# component 'xx'
s_factory = kwant.kpm.LocalVectors(fsyst, where)
cond_xx = kwant.kpm.conductivity(fsyst, alpha='x', beta='x', mean=True,
num_vectors=None, vector_factory=s_factory,
rng=0)
# component 'xy'
s_factory = kwant.kpm.LocalVectors(fsyst, where)
cond_xy = kwant.kpm.conductivity(fsyst, alpha='x', beta='y', mean=True,
num_vectors=None, vector_factory=s_factory,
rng=0)
energies = cond_xx.energies
cond_array_xx = np.array([cond_xx(e, temperature=0.01) for e in energies])
cond_array_xy = np.array([cond_xy(e, temperature=0.01) for e in energies])
# area of the unit cell per site
area_per_site = np.abs(np.cross(*lat.prim_vecs)) / len(lat.sublattices)
cond_array_xx /= area_per_site
cond_array_xy /= area_per_site
#HIDDEN_END_cond
# ldos
s_factory = kwant.kpm.LocalVectors(fsyst, where)
spectrum = kwant.kpm.SpectralDensity(fsyst, num_vectors=None,
vector_factory=s_factory,
rng=0)
plot_dos_and_curves(
(spectrum.energies, spectrum.densities * 8),
[
(r'Longitudinal conductivity $\sigma_{xx} / 4$',
(energies, cond_array_xx / 4)),
(r'Hall conductivity $\sigma_{xy}$',
(energies, cond_array_xy))],
ylabel=r'$\sigma [e^2/h]$',
file_name='kpm_cond'
)
def main():
simple_dos_example()
fsyst = make_syst().finalized()
dos_integrating_example(fsyst)
increasing_accuracy_example(fsyst)
operator_example(fsyst)
ldos_example(fsyst)
ldos_sites_example()
vector_factory_example(fsyst)
bilinear_map_operator_example(fsyst)
conductivity_example()
# Call the main function if the script gets executed (as opposed to imported).
# See <http://docs.python.org/library/__main__.html>.
if __name__ == '__main__':
main()
@@ -1,245 +1,268 @@
# Tutorial 2.7. Spin textures
# ===========================
#
# Physics background
# ------------------
# - Spin textures
# - Skyrmions
#
# Kwant features highlighted
# --------------------------
# - operators
# - plotting vector fields
+import _defs
+from contextlib import redirect_stdout
+
from math import sin, cos, tanh, pi
import itertools
import numpy as np
import tinyarray as ta
import matplotlib.pyplot as plt
import kwant
sigma_0 = ta.array([[1, 0], [0, 1]])
sigma_x = ta.array([[0, 1], [1, 0]])
sigma_y = ta.array([[0, -1j], [1j, 0]])
sigma_z = ta.array([[1, 0], [0, -1]])
# vector of Pauli matrices σ_αiβ where greek
# letters denote spinor indices
sigma = np.rollaxis(np.array([sigma_x, sigma_y, sigma_z]), 1)
#HIDDEN_BEGIN_model
def field_direction(pos, r0, delta):
x, y = pos
r = np.linalg.norm(pos)
r_tilde = (r - r0) / delta
theta = (tanh(r_tilde) - 1) * (pi / 2)
if r == 0:
m_i = [0, 0, -1]
else:
m_i = [
(x / r) * sin(theta),
(y / r) * sin(theta),
cos(theta),
]
return np.array(m_i)
def scattering_onsite(site, r0, delta, J):
m_i = field_direction(site.pos, r0, delta)
return J * np.dot(m_i, sigma)
def lead_onsite(site, J):
return J * sigma_z
#HIDDEN_END_model
#HIDDEN_BEGIN_syst
lat = kwant.lattice.square(norbs=2)
def make_system(L=80):
syst = kwant.Builder()
def square(pos):
return all(-L/2 < p < L/2 for p in pos)
syst[lat.shape(square, (0, 0))] = scattering_onsite
syst[lat.neighbors()] = -sigma_0
lead = kwant.Builder(kwant.TranslationalSymmetry((-1, 0)),
conservation_law=-sigma_z)
lead[lat.shape(square, (0, 0))] = lead_onsite
lead[lat.neighbors()] = -sigma_0
syst.attach_lead(lead)
syst.attach_lead(lead.reversed())
return syst
#HIDDEN_END_syst
-def plot_vector_field(syst, params):
+def save_plot(fname):
+ for extension in ('.pdf', '.png'):
+ plt.savefig(fname + extension,
+ dpi=_defs.dpi, bbox_inches='tight')
+
+
+def plot_vector_field(syst, params, fname=None):
xmin, ymin = min(s.tag for s in syst.sites)
xmax, ymax = max(s.tag for s in syst.sites)
x, y = np.meshgrid(np.arange(xmin, xmax+1), np.arange(ymin, ymax+1))
m_i = [field_direction(p, **params) for p in zip(x.flat, y.flat)]
m_i = np.reshape(m_i, x.shape + (3,))
m_i = np.rollaxis(m_i, 2, 0)
- fig, ax = plt.subplots(1, 1)
+ fig, ax = plt.subplots(1, 1, figsize=(9, 7))
im = ax.quiver(x, y, *m_i, pivot='mid', scale=75)
fig.colorbar(im)
- plt.show()
+ if fname:
+ save_plot(fname)
+ else:
+ plt.show()
-def plot_densities(syst, densities):
- fig, axes = plt.subplots(1, len(densities))
+def plot_densities(syst, densities, fname=None):
+ fig, axes = plt.subplots(1, len(densities), figsize=(7*len(densities), 7))
for ax, (title, rho) in zip(axes, densities):
kwant.plotter.density(syst, rho, ax=ax)
ax.set_title(title)
- plt.show()
+ if fname:
+ save_plot(fname)
+ else:
+ plt.show()
-def plot_currents(syst, currents):
- fig, axes = plt.subplots(1, len(currents))
+
+def plot_currents(syst, currents, fname=None):
+ fig, axes = plt.subplots(1, len(currents), figsize=(7*len(currents), 7))
if not hasattr(axes, '__len__'):
axes = (axes,)
for ax, (title, current) in zip(axes, currents):
kwant.plotter.current(syst, current, ax=ax, colorbar=False)
ax.set_title(title)
- plt.show()
+ if fname:
+ save_plot(fname)
+ else:
+ plt.show()
def main():
syst = make_system().finalized()
#HIDDEN_BEGIN_wavefunction
params = dict(r0=20, delta=10, J=1)
wf = kwant.wave_function(syst, energy=-1, params=params)
psi = wf(0)[0]
#HIDDEN_END_wavefunction
- plot_vector_field(syst, dict(r0=20, delta=10))
+ plot_vector_field(syst, dict(r0=20, delta=10), fname='mag_field_direction')
#HIDDEN_BEGIN_ldos
# even (odd) indices correspond to spin up (down)
up, down = psi[::2], psi[1::2]
density = np.abs(up)**2 + np.abs(down)**2
#HIDDEN_END_ldos
#HIDDEN_BEGIN_lsdz
# spin down components have a minus sign
spin_z = np.abs(up)**2 - np.abs(down)**2
#HIDDEN_END_lsdz
#HIDDEN_BEGIN_lsdy
# spin down components have a minus sign
spin_y = 1j * (down.conjugate() * up - up.conjugate() * down)
#HIDDEN_END_lsdy
#HIDDEN_BEGIN_lden
rho = kwant.operator.Density(syst)
rho_sz = kwant.operator.Density(syst, sigma_z)
rho_sy = kwant.operator.Density(syst, sigma_y)
# calculate the expectation values of the operators with 'psi'
density = rho(psi)
spin_z = rho_sz(psi)
spin_y = rho_sy(psi)
#HIDDEN_END_lden
plot_densities(syst, [
('$σ_0$', density),
('$σ_z$', spin_z),
('$σ_y$', spin_y),
- ])
+ ], fname='spin_densities')
#HIDDEN_BEGIN_current
J_0 = kwant.operator.Current(syst)
J_z = kwant.operator.Current(syst, sigma_z)
J_y = kwant.operator.Current(syst, sigma_y)
# calculate the expectation values of the operators with 'psi'
current = J_0(psi)
spin_z_current = J_z(psi)
spin_y_current = J_y(psi)
#HIDDEN_END_current
plot_currents(syst, [
('$J_{σ_0}$', current),
('$J_{σ_z}$', spin_z_current),
('$J_{σ_y}$', spin_y_current),
- ])
+ ], fname='spin_currents')
#HIDDEN_BEGIN_following
def following_m_i(site, r0, delta):
m_i = field_direction(site.pos, r0, delta)
return np.dot(m_i, sigma)
J_m = kwant.operator.Current(syst, following_m_i)
# evaluate the operator
m_current = J_m(psi, params=dict(r0=25, delta=10))
#HIDDEN_END_following
plot_currents(syst, [
(r'$J_{\mathbf{m}_i}$', m_current),
('$J_{σ_z}$', spin_z_current),
- ])
+ ], fname='spin_current_comparison')
#HIDDEN_BEGIN_density_cut
def circle(site):
return np.linalg.norm(site.pos) < 20
rho_circle = kwant.operator.Density(syst, where=circle, sum=True)
all_states = np.vstack((wf(0), wf(1)))
dos_in_circle = sum(rho_circle(p) for p in all_states) / (2 * pi)
- print('density of states in circle:', dos_in_circle)
+ with open('circle_dos.txt', 'w') as f:
+ with redirect_stdout(f):
+ print('density of states in circle:', dos_in_circle)
#HIDDEN_END_density_cut
#HIDDEN_BEGIN_current_cut
def left_cut(site_to, site_from):
return site_from.pos[0] <= -39 and site_to.pos[0] > -39
def right_cut(site_to, site_from):
return site_from.pos[0] < 39 and site_to.pos[0] >= 39
J_left = kwant.operator.Current(syst, where=left_cut, sum=True)
J_right = kwant.operator.Current(syst, where=right_cut, sum=True)
Jz_left = kwant.operator.Current(syst, sigma_z, where=left_cut, sum=True)
Jz_right = kwant.operator.Current(syst, sigma_z, where=right_cut, sum=True)
- print('J_left:', J_left(psi), ' J_right:', J_right(psi))
- print('Jz_left:', Jz_left(psi), ' Jz_right:', Jz_right(psi))
+ with open('current_cut.txt', 'w') as f:
+ with redirect_stdout(f):
+ print('J_left:', J_left(psi), ' J_right:', J_right(psi))
+ print('Jz_left:', Jz_left(psi), ' Jz_right:', Jz_right(psi))
#HIDDEN_END_current_cut
#HIDDEN_BEGIN_bind
J_m = kwant.operator.Current(syst, following_m_i)
J_z = kwant.operator.Current(syst, sigma_z)
J_m_bound = J_m.bind(params=dict(r0=25, delta=10, J=1))
J_z_bound = J_z.bind(params=dict(r0=25, delta=10, J=1))
# Sum current local from all scattering states on the left at energy=-1
wf_left = wf(0)
J_m_left = sum(J_m_bound(p) for p in wf_left)
J_z_left = sum(J_z_bound(p) for p in wf_left)
#HIDDEN_END_bind
plot_currents(syst, [
(r'$J_{\mathbf{m}_i}$ (from left)', J_m_left),
(r'$J_{σ_z}$ (from left)', J_z_left),
- ])
+ ], fname='bound_current')
if __name__ == '__main__':
main()
@@ -1,112 +1,130 @@
# Tutorial 2.8.1. 2D example: graphene quantum dot
# ================================================
#
# Physics background
# ------------------
# - graphene edge states
#
# Kwant features highlighted
# --------------------------
# - demonstrate different ways of plotting
+import _defs
import kwant
from matplotlib import pyplot
#HIDDEN_BEGIN_makesyst
lat = kwant.lattice.honeycomb()
a, b = lat.sublattices
def make_system(r=8, t=-1, tp=-0.1):
def circle(pos):
x, y = pos
return x**2 + y**2 < r**2
syst = kwant.Builder()
- syst[lat.shape(circle, (0, 0))] = 0
+ syst[lat.shape(circle, (0,0))] = 0
syst[lat.neighbors()] = t
syst.eradicate_dangling()
if tp:
syst[lat.neighbors(2)] = tp
return syst
#HIDDEN_END_makesyst
#HIDDEN_BEGIN_plotsyst1
def plot_system(syst):
- kwant.plot(syst)
#HIDDEN_END_plotsyst1
- # the standard plot is ok, but not very intelligible. One can do
- # better by playing wioth colors and linewidths
+ # standard plot - not very intelligible for this particular situation
+ size = (_defs.figwidth_in, _defs.figwidth_in)
+ for extension in ('pdf', 'png'):
+ kwant.plot(syst, file="plot_graphene_syst1." + extension,
+ fig_size=size, dpi=_defs.dpi)
# use color and linewidths to get a better plot
#HIDDEN_BEGIN_plotsyst2
def family_color(site):
return 'black' if site.family == a else 'white'
def hopping_lw(site1, site2):
return 0.04 if site1.family == site2.family else 0.1
- kwant.plot(syst, site_lw=0.1, site_color=family_color, hop_lw=hopping_lw)
+ size = (_defs.figwidth_in, _defs.figwidth_in)
+ for extension in ('pdf', 'png'):
+ kwant.plot(syst, site_lw=0.1, site_color=family_color,
+ hop_lw=hopping_lw, file="plot_graphene_syst2." + extension,
+ fig_size=size, dpi=_defs.dpi)
#HIDDEN_END_plotsyst2
#HIDDEN_BEGIN_plotdata1
def plot_data(syst, n):
import scipy.linalg as la
syst = syst.finalized()
ham = syst.hamiltonian_submatrix()
evecs = la.eigh(ham)[1]
wf = abs(evecs[:, n])**2
#HIDDEN_END_plotdata1
# the usual - works great in general, looks just a bit crufty for
# small systems
#HIDDEN_BEGIN_plotdata2
- kwant.plotter.map(syst, wf, oversampling=10, cmap='gist_heat_r')
+ size = (_defs.figwidth_in, _defs.figwidth_in)
+ for extension in ('pdf', 'png'):
+ kwant.plotter.map(syst, wf, oversampling=10, cmap='gist_heat_r',
+ file="plot_graphene_data1." + extension,
+ fig_size=size, dpi=_defs.dpi)
#HIDDEN_END_plotdata2
# use two different sort of triangles to cleanly fill the space
#HIDDEN_BEGIN_plotdata3
def family_shape(i):
site = syst.sites[i]
return ('p', 3, 180) if site.family == a else ('p', 3, 0)
def family_color(i):
return 'black' if syst.sites[i].family == a else 'white'
- kwant.plot(syst, site_color=wf, site_symbol=family_shape,
- site_size=0.5, hop_lw=0, cmap='gist_heat_r')
+ size = (_defs.figwidth_in, _defs.figwidth_in)
+ for extension in ('pdf', 'png'):
+ kwant.plot(syst, site_color=wf, site_symbol=family_shape,
+ site_size=0.5, hop_lw=0, cmap='gist_heat_r',
+ file="plot_graphene_data2." + extension,
+ fig_size=size, dpi=_defs.dpi)
#HIDDEN_END_plotdata3
# plot by changing the symbols itself
#HIDDEN_BEGIN_plotdata4
def site_size(i):
return 3 * wf[i] / wf.max()
- kwant.plot(syst, site_size=site_size, site_color=(0, 0, 1, 0.3),
- hop_lw=0.1)
+ size = (_defs.figwidth_in, _defs.figwidth_in)
+ for extension in ('pdf', 'png'):
+ kwant.plot(syst, site_size=site_size, site_color=(0,0,1,0.3),
+ hop_lw=0.1, file="plot_graphene_data3." + extension,
+ fig_size=size, dpi=_defs.dpi)
#HIDDEN_END_plotdata4
def main():
# plot the graphene system in different styles
syst = make_system()
plot_system(syst)
# compute a wavefunction (number 225) and plot it in different
# styles
syst = make_system(tp=0)
plot_data(syst, 225)
# Call the main function if the script gets executed (as opposed to imported).
# See <http://docs.python.org/library/__main__.html>.
if __name__ == '__main__':
main()
@@ -1,72 +1,76 @@
# Comprehensive example: quantum anomalous Hall effect
# ====================================================
#
# Physics background
# ------------------
# + Quantum anomalous Hall effect
#
# Features highlighted
# --------------------
# + Use of `kwant.continuum` to discretize a continuum Hamiltonian
# + Use of `kwant.operator` to compute local current
# + Use of `kwant.plotter.current` to plot local current
+import _defs
import math
import matplotlib.pyplot
import kwant
import kwant.continuum
# 2 band model exhibiting quantum anomalous Hall effect
#HIDDEN_BEGIN_model
def make_model(a):
ham = ("alpha * (k_x * sigma_x - k_y * sigma_y)"
"+ (m + beta * kk) * sigma_z"
"+ (gamma * kk + U) * sigma_0")
subs = {"kk": "k_x**2 + k_y**2"}
return kwant.continuum.discretize(ham, locals=subs, grid=a)
#HIDDEN_END_model
def make_system(model, L):
def lead_shape(site):
x, y = site.pos / L
return abs(y) < 0.5
# QPC shape: a rectangle with 2 gaussians
# etched out of the top and bottom edge.
def central_shape(site):
x, y = site.pos / L
return abs(x) < 3/5 and abs(y) < 0.5 - 0.4 * math.exp(-40 * x**2)
lead = kwant.Builder(kwant.TranslationalSymmetry(
model.lattice.vec((-1, 0))))
lead.fill(model, lead_shape, (0, 0))
syst = kwant.Builder()
syst.fill(model, central_shape, (0, 0))
syst.attach_lead(lead)
syst.attach_lead(lead.reversed())
return syst.finalized()
def main():
# Set up our model and system, and define the model parameters.
params = dict(alpha=0.365, beta=0.686, gamma=0.512, m=-0.01, U=0)
model = make_model(1)
syst = make_system(model, 70)
kwant.plot(syst)
# Calculate the scattering states at energy 'm' coming from the left
# lead, and the associated particle current.
psi = kwant.wave_function(syst, energy=params['m'], params=params)(0)
#HIDDEN_BEGIN_current
J = kwant.operator.Current(syst).bind(params=params)
current = sum(J(p) for p in psi)
- kwant.plotter.current(syst, current)
+ for extension in ('pdf', 'png'):
+ kwant.plotter.current(syst, current,
+ file="plot_qahe_current." + extension,
+ dpi=_defs.dpi)
#HIDDEN_END_current
if __name__ == '__main__':
main()