├── .coveragerc ├── .gitignore ├── .pylintrc ├── .readthedocs.yml ├── .travis.yml ├── LICENSE ├── MANIFEST.in ├── Makefile ├── README.rst ├── doc ├── Makefile ├── _ext │ └── edit_on_github.py ├── _static │ ├── favicon.ico │ ├── logo_new.png │ ├── logo_new_small.png │ ├── num_auto.png │ ├── num_auto.svg │ ├── opt_var.png │ ├── qmlt.png │ ├── qmlt_old.png │ ├── sup_var.png │ ├── supervised_tutorial_epoch1.png │ ├── supervised_tutorial_epoch1.svg │ ├── supervised_tutorial_epoch_100.png │ ├── supervised_tutorial_epoch_100.svg │ ├── unsup_var.png │ ├── variational_detail.png │ ├── variational_detail.svg │ ├── variational_rough.png │ ├── variational_rough.svg │ ├── workflow.png │ └── workflow.svg ├── code.rst ├── code │ ├── helpers.rst │ ├── numerical.helpers.rst │ ├── numerical.losses.rst │ ├── numerical.plot.rst │ ├── numerical.regularizers.rst │ ├── numerical.rst │ ├── tf.helpers.rst │ ├── tf.losses.rst │ └── tf.rst ├── conf.py ├── definitions.rst ├── index.rst ├── installing.rst ├── macros.tex ├── references.bib ├── requirements.txt ├── research.rst ├── tasks.rst ├── tutorials │ ├── examples.rst │ ├── numerical.rst │ └── tensorflow.rst ├── variational.rst ├── xanadu_theme │ ├── LICENSE │ ├── comments.html │ ├── globaltoc.html │ ├── layout.html │ ├── localtoc.html │ ├── logo-text.html │ ├── search.html │ ├── searchbox.html │ ├── sourcelink.html │ ├── static │ │ ├── css │ │ │ ├── bootstrap-theme.min.css │ │ │ ├── bootstrap.min.css │ │ │ └── nanoscroller.css │ │ ├── fonts │ │ │ ├── glyphicons-halflings-regular.eot │ │ │ ├── glyphicons-halflings-regular.svg │ │ │ ├── glyphicons-halflings-regular.ttf │ │ │ ├── glyphicons-halflings-regular.woff │ │ │ ├── open-sans │ │ │ │ ├── fonts │ │ │ │ │ ├── OpenSans-Bold-webfont.eot │ │ │ │ │ ├── OpenSans-Bold-webfont.svg │ │ │ │ │ ├── OpenSans-Bold-webfont.ttf │ │ │ │ │ ├── OpenSans-Bold-webfont.woff │ │ │ │ │ ├── OpenSans-BoldItalic-webfont.eot │ │ │ │ │ ├── OpenSans-BoldItalic-webfont.svg │ │ │ │ │ ├── OpenSans-BoldItalic-webfont.ttf │ │ │ │ │ ├── OpenSans-BoldItalic-webfont.woff │ │ │ │ │ ├── OpenSans-ExtraBold-webfont.eot │ │ │ │ │ ├── OpenSans-ExtraBold-webfont.svg │ │ │ │ │ ├── OpenSans-ExtraBold-webfont.ttf │ │ │ │ │ ├── OpenSans-ExtraBold-webfont.woff │ │ │ │ │ ├── OpenSans-ExtraBoldItalic-webfont.eot │ │ │ │ │ ├── OpenSans-ExtraBoldItalic-webfont.svg │ │ │ │ │ ├── OpenSans-ExtraBoldItalic-webfont.ttf │ │ │ │ │ ├── OpenSans-ExtraBoldItalic-webfont.woff │ │ │ │ │ ├── OpenSans-Italic-webfont.eot │ │ │ │ │ ├── OpenSans-Italic-webfont.svg │ │ │ │ │ ├── OpenSans-Italic-webfont.ttf │ │ │ │ │ ├── OpenSans-Italic-webfont.woff │ │ │ │ │ ├── OpenSans-Light-webfont.eot │ │ │ │ │ ├── OpenSans-Light-webfont.svg │ │ │ │ │ ├── OpenSans-Light-webfont.ttf │ │ │ │ │ ├── OpenSans-Light-webfont.woff │ │ │ │ │ ├── OpenSans-LightItalic-webfont.eot │ │ │ │ │ ├── OpenSans-LightItalic-webfont.svg │ │ │ │ │ ├── OpenSans-LightItalic-webfont.ttf │ │ │ │ │ ├── OpenSans-LightItalic-webfont.woff │ │ │ │ │ ├── OpenSans-Regular-webfont.eot │ │ │ │ │ ├── OpenSans-Regular-webfont.svg │ │ │ │ │ ├── OpenSans-Regular-webfont.ttf │ │ │ │ │ ├── OpenSans-Regular-webfont.woff │ │ │ │ │ ├── OpenSans-Semibold-webfont.eot │ │ │ │ │ ├── OpenSans-Semibold-webfont.svg │ │ │ │ │ ├── OpenSans-Semibold-webfont.ttf │ │ │ │ │ ├── OpenSans-Semibold-webfont.woff │ │ │ │ │ ├── OpenSans-SemiboldItalic-webfont.eot │ │ │ │ │ ├── OpenSans-SemiboldItalic-webfont.svg │ │ │ │ │ ├── OpenSans-SemiboldItalic-webfont.ttf │ │ │ │ │ └── OpenSans-SemiboldItalic-webfont.woff │ │ │ │ └── stylesheet.css │ │ │ └── source-serif-pro │ │ │ │ ├── EOT │ │ │ │ ├── SourceSerifPro-Black.eot │ │ │ │ ├── SourceSerifPro-Bold.eot │ │ │ │ ├── SourceSerifPro-ExtraLight.eot │ │ │ │ ├── SourceSerifPro-Light.eot │ │ │ │ ├── SourceSerifPro-Regular.eot │ │ │ │ └── SourceSerifPro-Semibold.eot │ │ │ │ ├── LICENSE.txt │ │ │ │ ├── OTF │ │ │ │ ├── SourceSerifPro-Black.otf │ │ │ │ ├── SourceSerifPro-Bold.otf │ │ │ │ ├── SourceSerifPro-ExtraLight.otf │ │ │ │ ├── SourceSerifPro-Light.otf │ │ │ │ ├── SourceSerifPro-Regular.otf │ │ │ │ └── SourceSerifPro-Semibold.otf │ │ │ │ ├── README.md │ │ │ │ ├── ReadMe.html │ │ │ │ ├── SourceSerifProReadMe.html │ │ │ │ ├── TTF │ │ │ │ ├── SourceSerifPro-Black.ttf │ │ │ │ ├── SourceSerifPro-Bold.ttf │ │ │ │ ├── SourceSerifPro-ExtraLight.ttf │ │ │ │ ├── SourceSerifPro-Light.ttf │ │ │ │ ├── SourceSerifPro-Regular.ttf │ │ │ │ └── SourceSerifPro-Semibold.ttf │ │ │ │ ├── WOFF │ │ │ │ ├── OTF │ │ │ │ │ ├── SourceSerifPro-Black.otf.woff │ │ │ │ │ ├── SourceSerifPro-Bold.otf.woff │ │ │ │ │ ├── SourceSerifPro-ExtraLight.otf.woff │ │ │ │ │ ├── SourceSerifPro-Light.otf.woff │ │ │ │ │ ├── SourceSerifPro-Regular.otf.woff │ │ │ │ │ └── SourceSerifPro-Semibold.otf.woff │ │ │ │ └── TTF │ │ │ │ │ ├── SourceSerifPro-Black.ttf.woff │ │ │ │ │ ├── SourceSerifPro-Bold.ttf.woff │ │ │ │ │ ├── SourceSerifPro-ExtraLight.ttf.woff │ │ │ │ │ ├── SourceSerifPro-Light.ttf.woff │ │ │ │ │ ├── SourceSerifPro-Regular.ttf.woff │ │ │ │ │ └── SourceSerifPro-Semibold.ttf.woff │ │ │ │ ├── bower.json │ │ │ │ └── source-serif-pro.css │ │ ├── jquery.js │ │ ├── jquery.min.map │ │ ├── js │ │ │ ├── bootstrap.js │ │ │ ├── bootstrap.min.js │ │ │ └── nanoscroller.min.js │ │ ├── tomorrow.css │ │ ├── tomorrow_night.css │ │ └── xanadu.css_t │ └── theme.conf └── z_references.rst ├── examples ├── .gitignore ├── numerical │ ├── optimization_advanced_num.py │ ├── optimization_num.py │ ├── supervised_advanced_num.py │ ├── supervised_num.py │ ├── unsupervised_advanced_num.py │ └── unsupervised_num.py └── tf │ ├── optimization_advanced_tf.py │ ├── optimization_tf.py │ ├── supervised_advanced_tf.py │ ├── supervised_tf.py │ ├── unsupervised_advanced_tf.py │ └── unsupervised_tf.py ├── qmlt ├── __init__.py ├── _version.py ├── helpers.py ├── numerical │ ├── __init__.py │ ├── helpers.py │ ├── learner.py │ ├── losses.py │ ├── plot.py │ └── regularizers.py └── tf │ ├── __init__.py │ ├── helpers.py │ ├── learner.py │ └── losses.py ├── requirements.txt ├── setup.py └── tests ├── .coverage ├── __init__.py ├── test_helpers.py ├── test_learners.py ├── test_losses.py ├── test_optimizers.py └── test_plots.py /.coveragerc: -------------------------------------------------------------------------------- 1 | # .coveragerc to control coverage.py 2 | [run] 3 | source = qmlt 4 | 5 | [report] 6 | # Regexes for lines to exclude from consideration 7 | exclude_lines = 8 | # Have to re-enable the standard pragma 9 | pragma: no cover 10 | 11 | # Don't complain about missing debug-only code: 12 | def __repr__ 13 | def __eq__ 14 | if self\.debug 15 | 16 | # print statements 17 | def __str__ 18 | def _print_list 19 | 20 | # Don't complain if tests don't hit defensive assertion code: 21 | raise AssertionError 22 | raise NotImplementedError 23 | raise NotApplicableError 24 | raise Exception 25 | raise ValueError 26 | raise ZeroDivisionError 27 | raise TypeError 28 | raise RuntimeError 29 | raise IndexError 30 | raise FileNotFoundError 31 | raise NotADirectoryError 32 | return __version__ 33 | if len(lst) != self._num_modes: 34 | elif max(lst) >= self._trunc: 35 | except NotImplementedError as err 36 | 37 | # Don't complain if non-runnable code isn't run: 38 | if 0: 39 | pass 40 | if __name__ == .__main__.: 41 | 42 | ignore_errors = True 43 | 44 | [html] 45 | directory = coverage_html_report 46 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | *.pyc 3 | doc/_build 4 | build 5 | dist 6 | qit.egg-info 7 | .idea 8 | examples/*ipynp* 9 | *.egg-info* 10 | /examples/tf/logsAUTO/* 11 | /examples/numeric/logsNUM/* 12 | /examples/tf/logsAUTO/ 13 | /examples/numeric/logsNUM/ 14 | /tests/logsAUTO 15 | /tests/logsNUM 16 | /logsAUTO 17 | /logsNUM 18 | -------------------------------------------------------------------------------- /.pylintrc: -------------------------------------------------------------------------------- 1 | [MASTER] 2 | # A comma-separated list of package or module names from where C extensions may 3 | # be loaded. Extensions are loading into the active Python interpreter and may 4 | # run arbitrary code 5 | extension-pkg-whitelist= 6 | 7 | [TYPECHECK] 8 | 9 | # List of module names for which member attributes should not be checked 10 | # (useful for modules/projects where namespaces are manipulated during runtime 11 | # and thus existing member attributes cannot be deduced by static analysis. It 12 | # supports qualified module names, as well as Unix pattern matching. 13 | ignored-modules=numpy,tensorflow,scipy,networkx,sklearn,strawberryfields,matplotlib,matplotlib.cm,sklearn.datasets 14 | 15 | # List of classes names for which member attributes should not be checked 16 | # (useful for classes with attributes dynamically set). This supports can work 17 | # with qualified names. 18 | ignored-classes=numpy,tensorflow,scipy,sklearn,strawberryfields,matplotlib,matplotlib.cm,sklearn.datasets 19 | 20 | [MESSAGES CONTROL] 21 | 22 | # Enable the message, report, category or checker with the given id(s). You can 23 | # either give multiple identifier separated by comma (,) or put this option 24 | # multiple time. 25 | #enable= 26 | 27 | # Disable the message, report, category or checker with the given id(s). You 28 | # can either give multiple identifier separated by comma (,) or put this option 29 | # multiple time (only on the command line, not in the configuration file where 30 | # it should appear only once). 31 | disable=line-too-long,invalid-name,too-many-lines,redefined-builtin,too-many-locals,duplicate-code -------------------------------------------------------------------------------- /.readthedocs.yml: -------------------------------------------------------------------------------- 1 | requirements_file: doc/requirements.txt 2 | 3 | build: 4 | image: latest 5 | 6 | python: 7 | version: 3.5 8 | 9 | # Don't build any extra formats 10 | formats: 11 | - none -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | cache: pip 3 | python: 4 | - 3.5 5 | env: 6 | install: 7 | - pip install -r requirements.txt 8 | - pip install wheel codecov 9 | - python3 setup.py bdist_wheel 10 | - pip install dist/qmlt*.whl 11 | script: 12 | - make coverage 13 | after_success: 14 | - codecov 15 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.rst 2 | include doc/* 3 | include LICENSE 4 | include examples/* 5 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | PYTHON3 := $(shell which python3 2>/dev/null) 2 | COVERAGE3 := $(shell which coverage3 2>/dev/null) 3 | 4 | PYTHON := python3 5 | COVERAGE := coverage3 6 | COPTS := run --append 7 | TESTRUNNER := -m unittest discover tests 8 | 9 | .PHONY: help 10 | help: 11 | @echo "Please use \`make ' where is one of" 12 | @echo " install to install QML Toolbox" 13 | @echo " wheel to build the QML Toolbox wheel" 14 | @echo " dist to package the source distribution" 15 | @echo " clean to delete all temporary, cache, and build files" 16 | @echo " clean-docs to delete all built documentation" 17 | @echo " test to run the test suite" 18 | @echo " coverage to generate a coverage report" 19 | 20 | .PHONY: install 21 | install: 22 | ifndef PYTHON3 23 | @echo "To install QML Toolbox you need to have Python 3 installed" 24 | endif 25 | $(PYTHON) setup.py install 26 | 27 | .PHONY: wheel 28 | wheel: 29 | $(PYTHON) setup.py bdist_wheel 30 | 31 | .PHONY: dist 32 | dist: 33 | $(PYTHON) setup.py sdist 34 | 35 | .PHONY : clean 36 | clean: 37 | rm -rf qmlt/__pycache__ 38 | rm -rf qmlt/numeric/__pycache__ 39 | rm -rf qmlt/tf/__pycache__ 40 | rm -rf tests/__pycache__ 41 | rm -rf logsNUM logsAUTO 42 | rm -rf tests/logsNUM 43 | rm -rf tests/logsAUTO 44 | rm -rf examples/logsNUM 45 | rm -rf examples/logsAUTO 46 | rm -rf dist 47 | rm -rf build 48 | rm -rf .coverage coverage_html_report/ 49 | 50 | docs: 51 | make -C doc html 52 | 53 | .PHONY : clean-docs 54 | clean-docs: 55 | make -C doc clean 56 | 57 | 58 | test: 59 | $(PYTHON) $(TESTRUNNER) 60 | rm -rf logsAUTO logsNUM newpath 61 | 62 | coverage: 63 | @echo "Generating coverage report..." 64 | $(COVERAGE) $(COPTS) $(TESTRUNNER) 65 | $(COVERAGE) report 66 | $(COVERAGE) html 67 | rm -rf logsAUTO logsNUM 68 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | Notice: This library is no longer actively maintained. Its spiritual successor is `PennyLane `_ 2 | ############################################################################################################################################## 3 | 4 | Quantum Machine Learning Toolbox (QMLT) 5 | ########################################### 6 | 7 | .. image:: https://img.shields.io/travis/XanaduAI/QMLT/master.svg?style=for-the-badge 8 | :alt: Travis 9 | :target: https://travis-ci.org/XanaduAI/QMLT 10 | 11 | .. image:: https://img.shields.io/codecov/c/github/xanaduai/qmlt/master.svg?style=for-the-badge 12 | :alt: Codecov coverage 13 | :target: https://codecov.io/gh/XanaduAI/QMLT 14 | 15 | .. image:: https://img.shields.io/codacy/grade/acc9267c77f14a84ae8105732429a799.svg?style=for-the-badge 16 | :alt: Codacy grade 17 | :target: https://app.codacy.com/app/XanaduAI/QMLT?utm_source=github.com&utm_medium=referral&utm_content=XanaduAI/QMLT&utm_campaign=badger 18 | 19 | .. image:: https://img.shields.io/readthedocs/qmlt.svg?style=for-the-badge 20 | :alt: Read the Docs 21 | :target: https://qmlt.readthedocs.io 22 | 23 | .. image:: https://img.shields.io/pypi/pyversions/QMLT.svg?style=for-the-badge 24 | :alt: PyPI - Python Version 25 | :target: https://pypi.org/project/QMLT 26 | 27 | 28 | The Quantum Machine Learning Toolbox (QMLT) is a `Strawberry Fields `_ application that simplifies the optimization of variational quantum circuits. Tasks for the QMLT range from variational eigensolvers and unitary learning to supervised and unsupervised machine learning with models based on a variational circuit. 29 | 30 | Features 31 | ======== 32 | 33 | 34 | The Quantum Machine Learning Toolbox supports: 35 | 36 | * The training of user-provided variational circuits 37 | 38 | * Automatic and numerical differentiation methods to compute gradients of circuit outputs 39 | 40 | * Optimization, supervised and unsupervised learning tasks 41 | 42 | * Regularization of circuit parameters 43 | 44 | * Logging of training results 45 | 46 | * Monitoring and visualization of training through matplotlib and TensorBoard 47 | 48 | * Saving and restoring trained models 49 | 50 | * Parallel computation/GPU usage for TensorFlow-based models 51 | 52 | To get started, please see the online `documentation `_. 53 | 54 | 55 | Installation 56 | ============ 57 | 58 | Installation of the QMLT, as well as all required Python packages mentioned above, can be done using pip: 59 | :: 60 | 61 | $ python -m pip install qmlt 62 | 63 | 64 | Tests 65 | ===== 66 | 67 | To run all tests please run the following line from the main directory: 68 | :: 69 | 70 | $ python -m unittest discover tests 71 | 72 | Code authors 73 | ============ 74 | 75 | Maria Schuld and Josh Izaac. 76 | 77 | If you are doing research using Strawberry Fields, please cite `our whitepaper `_ and the QMLT documentation: 78 | 79 | Nathan Killoran, Josh Izaac, Nicolás Quesada, Ville Bergholm, Matthew Amy, and Christian Weedbrook. Strawberry Fields: A Software Platform for Photonic Quantum Computing. *arXiv*, 2018. arXiv:1804.03159 80 | 81 | Maria Schuld and Josh Izaac. Xanadu Quantum Machine Learning Toolbox documentation. https://qmlt.readthedocs.io. 82 | 83 | 84 | Support 85 | ======= 86 | 87 | - **Source Code:** https://github.com/XanaduAI/QMLT 88 | - **Issue Tracker:** https://github.com/XanaduAI/QMLT/issues 89 | 90 | If you are having issues, please let us know by posting the issue on our Github issue tracker. 91 | 92 | We also have a `Strawberry Fields Slack channel `_ - 93 | come join the discussion and chat with our Strawberry Fields team. 94 | 95 | 96 | License 97 | ======= 98 | 99 | QMLT is **free** and **open source**, released under the Apache License, Version 2.0. 100 | -------------------------------------------------------------------------------- /doc/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help 23 | help: 24 | @echo "Please use \`make ' where is one of" 25 | @echo " html to make standalone HTML files" 26 | @echo " dirhtml to make HTML files named index.html in directories" 27 | @echo " singlehtml to make a single large HTML file" 28 | @echo " pickle to make pickle files" 29 | @echo " json to make JSON files" 30 | @echo " htmlhelp to make HTML files and a HTML help project" 31 | @echo " qthelp to make HTML files and a qthelp project" 32 | @echo " applehelp to make an Apple Help Book" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | @echo " coverage to run coverage check of the documentation (if enabled)" 49 | 50 | .PHONY: clean 51 | clean: 52 | rm -rf $(BUILDDIR)/* 53 | 54 | .PHONY: html 55 | html: 56 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 57 | @echo 58 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 59 | 60 | .PHONY: dirhtml 61 | dirhtml: 62 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 63 | @echo 64 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 65 | 66 | .PHONY: singlehtml 67 | singlehtml: 68 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 69 | @echo 70 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 71 | 72 | .PHONY: pickle 73 | pickle: 74 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 75 | @echo 76 | @echo "Build finished; now you can process the pickle files." 77 | 78 | .PHONY: json 79 | json: 80 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 81 | @echo 82 | @echo "Build finished; now you can process the JSON files." 83 | 84 | .PHONY: htmlhelp 85 | htmlhelp: 86 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 87 | @echo 88 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 89 | ".hhp project file in $(BUILDDIR)/htmlhelp." 90 | 91 | .PHONY: qthelp 92 | qthelp: 93 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 94 | @echo 95 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 96 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 97 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Xanaduquantumcompiler.qhcp" 98 | @echo "To view the help file:" 99 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Xanaduquantumcompiler.qhc" 100 | 101 | .PHONY: applehelp 102 | applehelp: 103 | $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp 104 | @echo 105 | @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." 106 | @echo "N.B. You won't be able to view it unless you put it in" \ 107 | "~/Library/Documentation/Help or install it in your application" \ 108 | "bundle." 109 | 110 | .PHONY: devhelp 111 | devhelp: 112 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 113 | @echo 114 | @echo "Build finished." 115 | @echo "To view the help file:" 116 | @echo "# mkdir -p $$HOME/.local/share/devhelp/Xanaduquantumcompiler" 117 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Xanaduquantumcompiler" 118 | @echo "# devhelp" 119 | 120 | .PHONY: epub 121 | epub: 122 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 123 | @echo 124 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 125 | 126 | .PHONY: latex 127 | latex: 128 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 129 | @echo 130 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 131 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 132 | "(use \`make latexpdf' here to do that automatically)." 133 | 134 | .PHONY: latexpdf 135 | latexpdf: 136 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 137 | @echo "Running LaTeX files through pdflatex..." 138 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 139 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 140 | 141 | .PHONY: latexpdfja 142 | latexpdfja: 143 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 144 | @echo "Running LaTeX files through platex and dvipdfmx..." 145 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 146 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 147 | 148 | .PHONY: text 149 | text: 150 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 151 | @echo 152 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 153 | 154 | .PHONY: man 155 | man: 156 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 157 | @echo 158 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 159 | 160 | .PHONY: texinfo 161 | texinfo: 162 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 163 | @echo 164 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 165 | @echo "Run \`make' in that directory to run these through makeinfo" \ 166 | "(use \`make info' here to do that automatically)." 167 | 168 | .PHONY: info 169 | info: 170 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 171 | @echo "Running Texinfo files through makeinfo..." 172 | make -C $(BUILDDIR)/texinfo info 173 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 174 | 175 | .PHONY: gettext 176 | gettext: 177 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 178 | @echo 179 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 180 | 181 | .PHONY: changes 182 | changes: 183 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 184 | @echo 185 | @echo "The overview file is in $(BUILDDIR)/changes." 186 | 187 | .PHONY: linkcheck 188 | linkcheck: 189 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 190 | @echo 191 | @echo "Link check complete; look for any errors in the above output " \ 192 | "or in $(BUILDDIR)/linkcheck/output.txt." 193 | 194 | .PHONY: doctest 195 | doctest: 196 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 197 | @echo "Testing of doctests in the sources finished, look at the " \ 198 | "results in $(BUILDDIR)/doctest/output.txt." 199 | 200 | .PHONY: coverage 201 | coverage: 202 | $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage 203 | @echo "Testing of coverage in the sources finished, look at the " \ 204 | "results in $(BUILDDIR)/coverage/python.txt." 205 | 206 | .PHONY: xml 207 | xml: 208 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 209 | @echo 210 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 211 | 212 | .PHONY: pseudoxml 213 | pseudoxml: 214 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 215 | @echo 216 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 217 | -------------------------------------------------------------------------------- /doc/_ext/edit_on_github.py: -------------------------------------------------------------------------------- 1 | """ 2 | Sphinx extension to add ReadTheDocs-style "Edit on GitHub" links to the 3 | sidebar. 4 | Loosely based on https://github.com/astropy/astropy/pull/347 5 | """ 6 | 7 | import os 8 | import warnings 9 | 10 | 11 | __licence__ = 'BSD (3 clause)' 12 | 13 | 14 | def get_github_url(app, view, path): 15 | return 'https://github.com/{project}/{view}/{branch}/{path}'.format( 16 | project=app.config.edit_on_github_project, 17 | view=view, 18 | branch=app.config.edit_on_github_branch, 19 | path=path) 20 | 21 | 22 | def html_page_context(app, pagename, templatename, context, doctree): 23 | if templatename != 'page.html': 24 | return 25 | 26 | if not app.config.edit_on_github_project: 27 | warnings.warn("edit_on_github_project not specified") 28 | return 29 | 30 | if not doctree: 31 | return 32 | 33 | path = os.path.relpath(doctree.get('source'), app.builder.srcdir) 34 | show_url = get_github_url(app, 'blob', path) 35 | edit_url = get_github_url(app, 'edit', path) 36 | 37 | context['show_on_github_url'] = show_url 38 | context['edit_on_github_url'] = edit_url 39 | 40 | 41 | def setup(app): 42 | app.add_config_value('edit_on_github_project', '', True) 43 | app.add_config_value('edit_on_github_branch', 'master', True) 44 | app.connect('html-page-context', html_page_context) -------------------------------------------------------------------------------- /doc/_static/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/_static/favicon.ico -------------------------------------------------------------------------------- /doc/_static/logo_new.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/_static/logo_new.png -------------------------------------------------------------------------------- /doc/_static/logo_new_small.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/_static/logo_new_small.png -------------------------------------------------------------------------------- /doc/_static/num_auto.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/_static/num_auto.png -------------------------------------------------------------------------------- /doc/_static/opt_var.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/_static/opt_var.png -------------------------------------------------------------------------------- /doc/_static/qmlt.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/_static/qmlt.png -------------------------------------------------------------------------------- /doc/_static/qmlt_old.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/_static/qmlt_old.png -------------------------------------------------------------------------------- /doc/_static/sup_var.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/_static/sup_var.png -------------------------------------------------------------------------------- /doc/_static/supervised_tutorial_epoch1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/_static/supervised_tutorial_epoch1.png -------------------------------------------------------------------------------- /doc/_static/supervised_tutorial_epoch_100.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/_static/supervised_tutorial_epoch_100.png -------------------------------------------------------------------------------- /doc/_static/unsup_var.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/_static/unsup_var.png -------------------------------------------------------------------------------- /doc/_static/variational_detail.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/_static/variational_detail.png -------------------------------------------------------------------------------- /doc/_static/variational_rough.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/_static/variational_rough.png -------------------------------------------------------------------------------- /doc/_static/workflow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/_static/workflow.png -------------------------------------------------------------------------------- /doc/code.rst: -------------------------------------------------------------------------------- 1 | .. _code: 2 | 3 | Overview 4 | ================== 5 | 6 | The Quantum Machine Learning Toolbox consists of the two :class:`CircuitLearner` classes for automatic and numerical differentation. These classes can be used for optimization, supervised and unsupervised learning with variational circuits. 7 | 8 | Software components 9 | ------------------- 10 | 11 | **Frontend:** 12 | 13 | * :mod:`qmlt.helpers` - collection of learner-independent helpers; these can be used with either backend. 14 | 15 | **Numerical backend:** 16 | 17 | * :mod:`qmlt.numerical` - learner class for the training of user-provided quantum circuits. 18 | * :mod:`qmlt.numerical.losses` - collection of loss functions. 19 | * :mod:`qmlt.numerical.regularizers` - collection of regularizers. 20 | * :mod:`qmlt.numerical.helpers` - collection of helpers to set up an experiment with the learners. 21 | * :mod:`qmlt.numerical.plot` - collection of functions for plotting the outputs of log files. 22 | 23 | 24 | **TF backend:** 25 | 26 | * :mod:`qmlt.tf` - learner class for the training of user-provided quantum circuits. 27 | * :mod:`qmlt.tf.helpers` - collection of helpers to set up an experiment with the learners. 28 | 29 | 30 | Code details 31 | ------------ 32 | .. automodule:: qmlt 33 | :members: 34 | :inherited-members: 35 | 36 | -------------------------------------------------------------------------------- /doc/code/helpers.rst: -------------------------------------------------------------------------------- 1 | .. automodule:: qmlt.helpers 2 | :members: 3 | -------------------------------------------------------------------------------- /doc/code/numerical.helpers.rst: -------------------------------------------------------------------------------- 1 | .. automodule:: qmlt.numerical.helpers 2 | :members: 3 | -------------------------------------------------------------------------------- /doc/code/numerical.losses.rst: -------------------------------------------------------------------------------- 1 | .. _losses: 2 | 3 | .. automodule:: qmlt.numerical.losses 4 | :members: 5 | :inherited-members: 6 | :private-members: 7 | -------------------------------------------------------------------------------- /doc/code/numerical.plot.rst: -------------------------------------------------------------------------------- 1 | .. automodule:: qmlt.numerical.plot 2 | :members: 3 | :private-members: 4 | -------------------------------------------------------------------------------- /doc/code/numerical.regularizers.rst: -------------------------------------------------------------------------------- 1 | .. _regularisers: 2 | 3 | .. automodule:: qmlt.numerical.regularizers 4 | :members: 5 | :inherited-members: 6 | :private-members: 7 | -------------------------------------------------------------------------------- /doc/code/numerical.rst: -------------------------------------------------------------------------------- 1 | .. automodule:: qmlt.numerical 2 | :members: 3 | :inherited-members: 4 | :private-members: -------------------------------------------------------------------------------- /doc/code/tf.helpers.rst: -------------------------------------------------------------------------------- 1 | .. automodule:: qmlt.tf.helpers 2 | :members: 3 | :inherited-members: 4 | :private-members: 5 | -------------------------------------------------------------------------------- /doc/code/tf.losses.rst: -------------------------------------------------------------------------------- 1 | .. automodule:: qmlt.tf.losses 2 | :members: 3 | :inherited-members: 4 | :private-members: 5 | -------------------------------------------------------------------------------- /doc/code/tf.rst: -------------------------------------------------------------------------------- 1 | .. automodule:: qmlt.tf 2 | :members: 3 | :inherited-members: 4 | :private-members: 5 | -------------------------------------------------------------------------------- /doc/definitions.rst: -------------------------------------------------------------------------------- 1 | .. role:: raw-latex(raw) 2 | :format: latex 3 | 4 | .. role:: html(raw) 5 | :format: html 6 | 7 | .. _definitions: 8 | 9 | Definitions 10 | =========== 11 | 12 | .. sectionauthor:: Maria Schuld 13 | 14 | 15 | The machine learning toolbox uses a number of terms and concepts from machine learning that can have variuous meanings in different textbook. This little glossary gives some pointers of how we use them here. 16 | 17 | .. glossary:: 18 | 19 | Automatic differentiation 20 | A programming technique that associates each computational operation with a gradient taken with respect to some user-defined variables. This allows the analytic derivative of a variational circuit output to be retrieved without the need to numerically calculate the gradients on paper. A popular framework that supports automatic differentiation is Tensorflow. 21 | 22 | .. seealso:: :ref:`automatic_training` for more details. Automatic differentiation is supported by :mod:`qmlt.tf`. 23 | 24 | Epoch 25 | One run through all training data during training. One epoch is equivalent to a number of steps equal to (number of training inputs)/(batch size). 26 | 27 | Circuit parameters 28 | Trainable parameters of the quantum circuit. 29 | 30 | Cost 31 | The overall objective. In the QMLT teminology, the cost is the sum of the loss and the regularization. The goal of optimizing a variational circuit is to minimize the loss. 32 | 33 | Hyperparameters 34 | Configuration settings for the model and the training algorithm 35 | 36 | Learning rate 37 | Step size in the gradient updates. Can depend on the step or the value of the gradient if the learning rate is adaptive. 38 | 39 | Logging 40 | Printing out information on the values of variables during training. 41 | 42 | Loss 43 | The first term in the objective that measures how good a model is. 44 | 45 | Model directory 46 | Folder in which training logs and model is saved 47 | 48 | Monitoring 49 | Tagging a variable for visualization by plotting. 50 | 51 | Numerical differentiation 52 | The use of numerical methods to compute approximations to the gradient, for instance `finite differences `_ methods. 53 | 54 | .. seealso:: :ref:`numerical_differentation` for more details. Numerical differentiation is supported by :mod:`qmlt.numerical`. 55 | 56 | Regularization 57 | A penalty term in the cost function that depends on the parameters. Can be used to keep certain parameters low, or to limit the model flexibility and prevent overfitting. 58 | 59 | Step 60 | One iteration of the parameter update during optimization. 61 | 62 | Stochastic gradient descent 63 | Gradient descent optimization in which a batch of training inputs is sampled in each step. Introduces stochasticity to the training. As a consequence, the cost is not necessarily decreased in each step. 64 | 65 | Warm start 66 | Starting training with the parameters that the previous training ended with. 67 | 68 | -------------------------------------------------------------------------------- /doc/index.rst: -------------------------------------------------------------------------------- 1 | Quantum Machine Learning Toolbox 2 | ################################ 3 | 4 | :Release: |release| 5 | :Date: |today| 6 | 7 | The Quantum Machine Learning Toolbox (QMLT) is a `Strawberry Fields `_ application that simplifies the optimization of variational quantum circuits (also known as *parametrized quantum circuits*). Tasks for the QMLT range from variational eigensolvers and unitary learning to supervised and unsupervised machine learning with models based on a parametrized circuit. 8 | 9 | | 10 | 11 | .. _fig_varrough: 12 | 13 | .. figure:: _static/variational_rough.png 14 | :align: center 15 | :width: 350px 16 | 17 | The idea of :ref:`variational quantum circuits ` is to classically optimize the gate parameters according to an objective. 18 | 19 | | 20 | 21 | The quantum machine learning toolbox is designed to be used on top of the Strawberry Fields' continuous-variable quantum computing simulator, but can in principle be combined with other quantum programming languages as well. 22 | 23 | 24 | Features 25 | ======== 26 | 27 | The Quantum Machine Learning Toolbox supports: 28 | 29 | * The training of user-provided variational circuits 30 | 31 | * Automatic and numerical differentiation methods to compute gradients of circuit outputs 32 | 33 | * Optimization, supervised and unsupervised learning tasks 34 | 35 | * Regularization of circuit parameters 36 | 37 | * Logging of training results 38 | 39 | * Monitoring and visualization of training through matplotlib and TensorBoard 40 | 41 | * Saving and restoring trained models 42 | 43 | * Parallel computation/GPU usage for TensorFlow-based models 44 | 45 | 46 | Getting started 47 | =============== 48 | 49 | To install the QMLT on your system, begin at the :ref:`download and installation guide `. Then, familiarise yourself with :ref:`variational circuits ` and :ref:`things you can do with them `. 50 | 51 | For getting started with writing your QMLT code, have a look at the tutorials for the :ref:`numerical learner ` and the :ref:`TensorFlow learner `. 52 | 53 | Finally, detailed documentation on the :ref:`QMLT code ` is provided. 54 | 55 | Support 56 | ======= 57 | 58 | - **Source Code:** https://github.com/XanaduAI/QMLT 59 | - **Issue Tracker:** https://github.com/XanaduAI/QMLT/issues 60 | 61 | If you are having issues, please let us know, either by email or by posting the issue on our GitHub issue tracker. 62 | 63 | We have a mailing list located at: support@xanadu.ai. 64 | 65 | License 66 | ======= 67 | 68 | The Quantum Machine Learning Toolbox is **free** and **open-source**, released under the Apache License, Version 2.0. 69 | 70 | .. toctree:: 71 | :maxdepth: 2 72 | :caption: Getting started 73 | :hidden: 74 | 75 | installing 76 | research 77 | 78 | 79 | .. toctree:: 80 | :maxdepth: 2 81 | :caption: Background 82 | :hidden: 83 | 84 | variational 85 | tasks 86 | definitions 87 | z_references 88 | 89 | .. toctree:: 90 | :maxdepth: 2 91 | :caption: Tutorials 92 | :hidden: 93 | 94 | tutorials/numerical 95 | tutorials/tensorflow 96 | tutorials/examples 97 | 98 | .. toctree:: 99 | :maxdepth: 2 100 | :caption: Machine Learning Toolbox API 101 | :hidden: 102 | 103 | code 104 | code/helpers 105 | 106 | .. toctree:: 107 | :maxdepth: 2 108 | :caption: Numerical Learner 109 | :hidden: 110 | 111 | code/numerical 112 | code/numerical.losses 113 | code/numerical.regularizers 114 | code/numerical.helpers 115 | code/numerical.plot 116 | 117 | 118 | .. toctree:: 119 | :maxdepth: 2 120 | :caption: TF Learner 121 | :hidden: 122 | 123 | code/tf 124 | code/tf.losses 125 | code/tf.helpers 126 | 127 | 128 | Indices and tables 129 | ================== 130 | 131 | * :ref:`genindex` 132 | * :ref:`modindex` 133 | * :ref:`search` 134 | -------------------------------------------------------------------------------- /doc/installing.rst: -------------------------------------------------------------------------------- 1 | .. _installation: 2 | 3 | Installation and Downloads 4 | ################################# 5 | 6 | Dependencies 7 | ============ 8 | 9 | Before installing the Quantum Machine Learning Toolbox, the following dependencies need to be installed: 10 | 11 | * `Python `_ >= 3.5 12 | * `matplotlib `_ >= 2.0 13 | * `scikit-learn `_ >= 0.19 14 | * `Strawberry Fields `_ >= 0.7.3 15 | 16 | These packages will be installed automatically if using ``pip``, see below for details. For additional information on Strawberry Fields, please see the Strawberry Fields documentation. 17 | 18 | 19 | Installation 20 | ============ 21 | .. highlight:: console 22 | 23 | Installation of the Xanadu Quantum Machine Learning Toolbox, as well as all required Python packages mentioned above, can be done via pip: 24 | :: 25 | 26 | $ python -m pip install qmlt 27 | 28 | Make sure you are using the Python 3 version of pip. 29 | 30 | 31 | Documentation 32 | ============= 33 | 34 | To build the documentation, the following additional packages are required: 35 | 36 | * `Sphinx `_ >=1.5 37 | * `sphinxcontrib-bibtex `_ >=0.3.6 38 | 39 | If using Ubuntu, they can be installed via a combination of ``apt`` and ``pip``: 40 | :: 41 | 42 | $ pip3 install sphinx --user 43 | $ pip3 install sphinxcontrib-bibtex --user 44 | 45 | To build the HTML documentation, go to the top-level directory and run the command 46 | :: 47 | 48 | $ make docs 49 | 50 | The documentation can then be found in the :file:`doc/_build/html/` directory. 51 | -------------------------------------------------------------------------------- /doc/macros.tex: -------------------------------------------------------------------------------- 1 | % % LaTeX macros for the Sphinx docs. 2 | % Deprecated (see xanadu_theme/layout.html instead), 3 | % but sphinx complains if the file is not found 4 | % 5 | % 6 | % \usepackage{bbm} 7 | % 8 | % \newcommand{\pr}[1]{| #1 \rangle \langle #1|} 9 | % \newcommand{\ket}[1]{| #1 \rangle} % generic ket, also Fock state 10 | % \newcommand{\bra}[1]{\langle #1 |} % generic bra, also Fock costate 11 | % \newcommand{\xket}[1]{| #1 \rangle_x} % position eigenket 12 | % \newcommand{\xbra}[1]{\langle #1 |_x} % position eigenbra 13 | % \newcommand{\braket}[1]{\langle #1 \rangle} 14 | % \newcommand{\ketbra}[2]{| #1 \rangle\langle #2 |} 15 | % \newcommand{\hc}{\text{h.c.}} % hermitian conjugate 16 | % \newcommand{\cc}{\text{c.c.}} % complex conjugate 17 | % \newcommand{\h}{\hat} 18 | % \newcommand{\nn}{\nonumber} 19 | % \newcommand{\di}[1]{\frac{d}{d #1}} 20 | % \newcommand{\uu}{\mathcal{U}} 21 | % \newcommand{\inn}{\text{in}} 22 | % \newcommand{\out}{\text{out}} 23 | % \newcommand{\vac}{\text{vac}} 24 | % \newcommand{\nbar}{\overline{n}} 25 | % \newcommand{\x}{\hat{x}} 26 | % \newcommand{\p}{\hat{p}} 27 | % \newcommand{\a}{\hat{a}} 28 | % \newcommand{\ad}{\a^\dagger} 29 | % \newcommand{\b}{\hat{b}} 30 | % \newcommand{\I}{\mathbbm{1}} % vector/Hilbert space identity operator 31 | % \newcommand{\sech}{\mathrm{sech~}} 32 | % 33 | % \DeclareMathOperator{\re}{Re} % real part 34 | % \DeclareMathOperator{\im}{Im} % imaginary part 35 | % \DeclareMathOperator{\sign}{sign} % sign function 36 | -------------------------------------------------------------------------------- /doc/references.bib: -------------------------------------------------------------------------------- 1 | % Literature references for the ML Toolbox 2 | % bibtex file for sphinxcontrib-bibtex 3 | 4 | 5 | 6 | 7 | @article{mcclean16, 8 | title={The theory of variational hybrid quantum-classical algorithms}, 9 | author={McClean, Jarrod R and Romero, Jonathan and Babbush, Ryan and Aspuru-Guzik, Al{\'a}n}, 10 | journal={New Journal of Physics}, 11 | volume={18}, 12 | number={2}, 13 | pages={023023}, 14 | year={2016}, 15 | publisher={IOP Publishing} 16 | } 17 | 18 | @article{peruzzo14, 19 | title={A variational eigenvalue solver on a photonic quantum processor}, 20 | author={Peruzzo, Alberto and McClean, Jarrod and Shadbolt, Peter and Yung, Man-Hong and Zhou, Xiao-Qi and Love, Peter J and Aspuru-Guzik, Al{\'a}n and O’brien, Jeremy L}, 21 | journal={Nature communications}, 22 | volume={5}, 23 | year={2014}, 24 | publisher={Nature Publishing Group} 25 | } 26 | 27 | @article{kandala17, 28 | title={Hardware-efficient variational quantum eigensolver for small molecules and quantum magnets}, 29 | author={Kandala, Abhinav and Mezzacapo, Antonio and Temme, Kristan and Takita, Maika and Brink, Markus and Chow, Jerry M and Gambetta, Jay M}, 30 | journal={Nature}, 31 | volume={549}, 32 | number={7671}, 33 | pages={242}, 34 | year={2017}, 35 | publisher={Nature Publishing Group} 36 | } 37 | 38 | @article{farhi18, 39 | title={Classification with Quantum Neural Networks on Near Term Processors}, 40 | author={Farhi, Edward and Neven, Hartmut}, 41 | journal={arXiv preprint arXiv:1802.06002}, 42 | year={2018} 43 | } 44 | 45 | @article{schuld18cc, 46 | title={Circuit-centric quantum classifiers}, 47 | author={Maria Schuld, Alex Bocharov, Krysta Svore and Nathan Wiebe}, 48 | journal={arXiv preprint arXiv:1804.00633}, 49 | year={2018} 50 | } 51 | 52 | -------------------------------------------------------------------------------- /doc/requirements.txt: -------------------------------------------------------------------------------- 1 | sphinxcontrib-bibtex 2 | -------------------------------------------------------------------------------- /doc/research.rst: -------------------------------------------------------------------------------- 1 | Research and Contribution 2 | =============================== 3 | 4 | Research 5 | --------------- 6 | 7 | If you are doing research using Strawberry Fields, please cite `our whitepaper `_ and the QMLT documentation: 8 | 9 | Nathan Killoran, Josh Izaac, Nicolás Quesada, Ville Bergholm, Matthew Amy, and Christian Weedbrook. Strawberry Fields: A Software Platform for Photonic Quantum Computing. *arXiv*, 2018. arXiv:1804.03159 10 | 11 | Maria Schuld and Josh Izaac. Xanadu Quantum Machine Learning Toolbox documentation. https://qmlt.readthedocs.io. 12 | 13 | We are always open for collaboration, and can be contacted at research@xanadu.ai. 14 | 15 | Contribution 16 | ------------- 17 | 18 | If you would like to get involved with the Quantum Machine Learning Toolbox, or you would like to contribute, simply fork our Github repository, and make a descriptive pull request. 19 | 20 | - **Source Code:** https://github.com/XanaduAI/QMLT 21 | - **Issue Tracker:** https://github.com/XanaduAI/QMLT/issues 22 | 23 | 24 | Support 25 | -------- 26 | 27 | If you are having issues, please let us know, either by email or by posting the issue on our Github issue tracker. 28 | 29 | We have a mailing list located at: support@xanadu.ai 30 | -------------------------------------------------------------------------------- /doc/tasks.rst: -------------------------------------------------------------------------------- 1 | .. role:: raw-latex(raw) 2 | :format: latex 3 | 4 | .. role:: html(raw) 5 | :format: html 6 | 7 | .. _task: 8 | 9 | 10 | Tasks 11 | ============================================= 12 | 13 | .. sectionauthor:: Maria Schuld 14 | 15 | We define three tasks of variational circuits: 16 | 17 | * optimization, 18 | * unsupervised learning, and 19 | * supervised learning. 20 | 21 | All tasks have the goal of optimizing a variational circuit. But while the pure *optimization task* merely intends to find the extremal points of the objective, the goal of learning is to generalise from unlabelled or labelled data. Optimization is therefore a sub-task of learning, while the problem of learning from data exceeds optimization. 22 | 23 | To simplify this notion, we define the task depending on the potential data set given with the problem that the QMLT is supposed to solve. If there is no data given, we speak of an optimization task. If the data set is a collection of *inputs* which we assume to be real vectors, we have an unsupervised learning task. If in addition there is a *target label* given for each input, we have a supervised learning task. 24 | 25 | | 26 | 27 | .. rst-class:: docstable-small 28 | 29 | .. table:: 30 | :align: center 31 | 32 | +-----------------------+------------+-----------+ 33 | | Task | Inputs | Targets | 34 | +=======================+============+===========+ 35 | | Optimization | No | No | 36 | +-----------------------+------------+-----------+ 37 | | Unsupervised learning | Yes | No | 38 | +-----------------------+------------+-----------+ 39 | | Supervised learning | Yes | Yes | 40 | +-----------------------+------------+-----------+ 41 | 42 | | 43 | 44 | Let's go through them one by one. 45 | 46 | 47 | Optimization 48 | ------------ 49 | 50 | **Optimization** is the most basic application for variational circuits. The circuit parameters are updated with candidates that lead to a better objective until the objective is maximized or minimized, or the maximum number of steps has been reached. 51 | 52 | | 53 | 54 | .. _fig_opt_var: 55 | .. figure:: _static/opt_var.png 56 | :align: center 57 | :width: 350px 58 | 59 | | 60 | 61 | Possible applications are 62 | 63 | * **Variational quantum eigensolvers** :cite:`peruzzo14`. The output of the circuit is an expectation value with respect to the final state. The objective is to minimize this expectation value. For example, minimizing the energy expectation value, the optimal circuit prepares an approximation to the ground state of a quantum system. 64 | * **Unitary learning**. Here the output of the circuit is a quantum state, and the goal is to learn the circuit that prepares a final state with a certain property. For example, one could maximize the fidelity between the state prepared by the variational circuit and a given target state. One could also use a measure of entanglement as the objective and try to learn a circuit that prepares a maximally entangled state. 65 | 66 | 67 | 68 | Unsupervised learning 69 | ---------------------- 70 | 71 | In **unsupervised learning** the goal is to generalize patterns found in a dataset of input feature vectors. 72 | ''Generalizing'' can refer to many different tasks, such as clustering, data compression or generating new data samples. 73 | 74 | The data is used to formulate the training objective, which means that the training inputs define the objective 75 | function. A typical objective is maximum likelihood estimation, where one wants to increase the 76 | probability of observing the training data with regards to a model distribution. 77 | 78 | | 79 | 80 | .. _fig_unsup_var: 81 | .. figure:: _static/unsup_var.png 82 | :align: center 83 | :width: 350px 84 | 85 | | 86 | 87 | Possible applications are 88 | 89 | * **Training of generative models** . A quantum state defines probabilities over basis states (for example Fock states). If we associate these basis states with possible data samples, the quantum state defines a probability distribution over data. Given a set of some data samples drawn from a ''true'' distribution, the goal is to prepare a quantum state that corresponds to a distribution which is as close as possible to this ''true'' distribution. In other words, we have to find a circuit that prepares a quantum state from which measurements sample basis states that are somehow similar to the given data. 90 | * **Quantum clustering**. We want to assign the data samples to n clusters. We can learn a circuit that corresponds to a Hamiltonian such that the potential energy is high in areas of high data density of one class. 91 | 92 | 93 | Supervised learning 94 | ------------------- 95 | 96 | In **supervised learning** one wants to generalise the input-output relation of a dataset that contains sample inputs 97 | and target outputs. The variational circuit defines an ansatz of such a input-output function, and the goal is to 98 | learn a circuit which - if fed with new inputs - produced outputs according to the rule with which the data was 99 | produced. This is why here the quantum circuit depends on data inputs and produces outputs that are predictions for 100 | these inputs. The objective compares the predictions with the target outputs and measures how close they are. 101 | 102 | | 103 | 104 | .. _fig_sup_var: 105 | .. figure:: _static/sup_var.png 106 | :align: center 107 | :width: 350px 108 | 109 | | 110 | 111 | Possible applications are 112 | 113 | * **Quantum models for classification and regression** :cite:`farhi18` :cite:`schuld18cc`: The quantum circuit is an ansatz for a classical machine learning model that is trained to run new inputs. 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | -------------------------------------------------------------------------------- /doc/tutorials/examples.rst: -------------------------------------------------------------------------------- 1 | .. _examples: 2 | 3 | Examples 4 | ========== 5 | 6 | The example Python scripts discussed in the tutorials are available for download here. 7 | 8 | Numerical learner examples 9 | -------------------------- 10 | 11 | 1. Simple optimization task: :download:`optimization_num.py <../../examples/numerical/optimization_num.py>` 12 | 2. Introducing custom logging as well as regularization and monitoring of circuit parameters: :download:`optimization_advanced_num.py <../../examples/numerical/optimization_advanced_num.py>` 13 | 3. Simple unsupervised learning task: :download:`unsupervised_num.py <../../examples/numerical/unsupervised_num.py>` 14 | 4. Introducing layered circuit architectures: :download:`unsupervised_advanced_num.py <../../examples/numerical/unsupervised_advanced_num.py>` 15 | 5. Simple supervised learning task: :download:`supervised_num.py <../../examples/numerical/supervised_num.py>` 16 | 6. Introducing adaptive learning rate, printing, warm start and batched training: :download:`supervised_advanced_num.py <../../examples/numerical/supervised_advanced_num.py>` 17 | 18 | 19 | TensorFlow learner examples 20 | --------------------------- 21 | 22 | 1. Simple optimization task: :download:`optimization_tf.py <../../examples/tf/optimization_tf.py>` 23 | 2. Introducing custom logging as well as regularization and monitoring of circuit parameters: :download:`optimization_advanced_tf.py <../../examples/tf/optimization_advanced_tf.py>` 24 | 3. Simple unsupervised learning task: :download:`unsupervised_tf.py <../../examples/tf/unsupervised_tf.py>` 25 | 4. Introducing layered circuit architectures: :download:`unsupervised_advanced_tf.py <../../examples/tf/unsupervised_advanced_tf.py>` 26 | 5. Simple supervised learning task: :download:`supervised_tf.py <../../examples/tf/supervised_tf.py>` 27 | 6. Introducing adaptive learning rate, printing, warm start and batched training: :download:`supervised_advanced_tf.py <../../examples/tf/supervised_advanced_tf.py>` 28 | -------------------------------------------------------------------------------- /doc/variational.rst: -------------------------------------------------------------------------------- 1 | .. role:: raw-latex(raw) 2 | :format: latex 3 | 4 | .. role:: html(raw) 5 | :format: html 6 | 7 | .. _variational: 8 | 9 | 10 | Variational Circuits 11 | ====================== 12 | 13 | .. sectionauthor:: Maria Schuld 14 | 15 | Variational circuits (also called *parametrized quantum circuits*) are a family of hybrid quantum-classical algorithms :cite:`mcclean16`. At the core of the algorithm is a *quantum circuit* :math:`U` which depends on a set of :term:`circuit parameters ` :math:`\theta`, as well as an *objective function* which defines a scalar score for each set of parameters. The goal is to optimise or train the circuit with respect to the objective. 16 | 17 | | 18 | 19 | .. _fig_variational: 20 | .. figure:: _static/variational_detail.png 21 | :align: center 22 | :width: 350px 23 | 24 | The principle of a variational circuit. 25 | 26 | | 27 | 28 | Typically, variational circuits are trained by a classical optimization algorithm that makes queries to the quantum device. The optimization is usually an iterative scheme that finds better candidates for the parameters :math:`\theta` in every step, starting with either random or pre-trained initial parameters. 29 | 30 | When running a StrawberryFields simulation one can use *numerical* or *automatic* strategies to update the parameters in each step. 31 | 32 | Numerical training 33 | ------------------------ 34 | 35 | Numerical training methods use the quantum circuit as a blackbox. There are basically two subgroups of these methods: 36 | 37 | Derivative-free optimization 38 | **************************** 39 | 40 | `Derivative-free training methods `_ do not compute gradients to determine the search direction for the parameter update. 41 | 42 | Examples of such methods are 43 | 44 | * The `Nelder-Mead `_ or simplex method 45 | * Evolutionary algorithms 46 | * Particle swarm optimization 47 | 48 | Most derivative-free methods treat the objective and thereby the variational circuit as a black-box to query. They are hence easy to use, but not always numerically stable. Especially for large sets of parameters, one might be better of with gradient-based methods. 49 | 50 | .. _numerical_differentation: 51 | 52 | Gradient-based optimization 53 | **************************** 54 | 55 | Gradient-based training methods take information on the direction of steepest descent in the objective function into account, but at the cost of having to compute derivatives of the objective, and thereby of the variational circuit outputs. 56 | 57 | 58 | Numerical gradient-based methods compute approximations to the gradients. Usually this is done by the `finite-differences `_ method. The value of the objective function is evaluated at two positions close to the current circuit parameters :math:`\theta`. 59 | 60 | More precisely, let :math:`\mu \in \theta` be the parameter that we want to update, and let :math:`C(\mu)` be the objective function that depends on :math:`\mu`. The approximation of the gradient is then given by 61 | 62 | .. math:: 63 | 64 | \partial_{\mu} C(\mu) \approx \frac{C(\mu - \frac{1}{2}\Delta \mu ) - C(\mu + \frac{1}{2} \Delta \mu)}{\Delta \mu} 65 | 66 | One problem is that :math:`\Delta \mu` has to be as small as possible for good approximations, but still large enough to make the finite difference larger than the error in estimating :math:`C(\mu)`, which can be quite significant in current quantum technologies. 67 | 68 | .. note:: 69 | 70 | The finite-difference method can in principle also be used if the simulation is replaced by quantum hardware. 71 | 72 | 73 | .. _automatic_training: 74 | 75 | Automatic training 76 | ------------------ 77 | 78 | Automatic training is based on `automatic differentiation `_, which is a programming technique that associates each computational operation with a gradient taken with respect to some user-defined variables. Whatever computation is performed, one can automatically compute the gradient of the result. This is very useful for quantum machine learning, because it allows us to retrieve the analytic derivative of a variational circuit output without finding gradients on paper for each circuit architecture, and then implementing them as a training algorithm. 79 | 80 | A popular framework that supports automatic differentiation is `TensorFlow `_. The ``'tf'`` backend of StrawberryFields is coded in TensorFlow and when a circuit is run with this backend (and in the ``run()`` method for the engine we set ``evaluation=False``), the result of the circuit are tensors that have gradients associated with them. The machine learning toolbox uses this to build machine learning models. 81 | 82 | .. note:: 83 | 84 | Automatic differentiation is a feature of simulations only, and has no equivalent when using real quantum hardware! 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | -------------------------------------------------------------------------------- /doc/xanadu_theme/LICENSE: -------------------------------------------------------------------------------- 1 | Original work Copyright (c) 2013 Michael Dowling 2 | Modified work Copyright (c) 2018 Xanadu Quantum Technologies Inc. 3 | 4 | Permission is hereby granted, free of charge, to any person obtaining a copy 5 | of this software and associated documentation files (the "Software"), to deal 6 | in the Software without restriction, including without limitation the rights 7 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | copies of the Software, and to permit persons to whom the Software is 9 | furnished to do so, subject to the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be included in 12 | all copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /doc/xanadu_theme/comments.html: -------------------------------------------------------------------------------- 1 | {% if theme_disqus_comments_shortname %} 2 |
3 |
4 | 13 | 14 | comments powered by Disqus 15 |
16 | {% endif %} 17 | -------------------------------------------------------------------------------- /doc/xanadu_theme/globaltoc.html: -------------------------------------------------------------------------------- 1 | 2 | 15 | -------------------------------------------------------------------------------- /doc/xanadu_theme/localtoc.html: -------------------------------------------------------------------------------- 1 | {%- if display_toc %} 2 | 10 | {%- endif %} 11 | -------------------------------------------------------------------------------- /doc/xanadu_theme/logo-text.html: -------------------------------------------------------------------------------- 1 | 6 | -------------------------------------------------------------------------------- /doc/xanadu_theme/search.html: -------------------------------------------------------------------------------- 1 | {%- extends "basic/search.html" %} 2 | 3 | {% block body %} 4 |

{{ _('Search') }}

5 |
6 | 7 |

8 | {% trans %}Please activate JavaScript to enable the search 9 | functionality.{% endtrans %} 10 |

11 |
12 |

13 | From here you can search the full 14 | {{ theme_project_nav_name or shorttitle }} documentation. 15 |

16 |

17 | {% trans %} Note that the search function will only return results containing all of the search terms; if you can't find the page you are looking for, try removing some search terms and searching again.{% endtrans %} 18 |

19 |
20 | 21 |
22 |
23 |
24 | 25 | 26 | 27 | 28 |
29 | 30 |
31 |
32 | 33 | {% if search_performed %} 34 |

{{ _('Search Results') }}

35 | {% if not search_results %} 36 |

{{ _('Your search did not match any documents. Please make sure that all words are spelled correctly and that you\'ve selected enough categories.') }}

37 | {% endif %} 38 | {% endif %} 39 |
40 | {% if search_results %} 41 |
    42 | {% for href, caption, context in search_results %} 43 |
  • {{ caption }} 44 |
    {{ context|e }}
    45 |
  • 46 | {% endfor %} 47 |
48 | {% endif %} 49 |
50 | {% endblock %} 51 | -------------------------------------------------------------------------------- /doc/xanadu_theme/searchbox.html: -------------------------------------------------------------------------------- 1 | {%- if pagename != "search" %} 2 | 22 | {%- endif %} 23 | -------------------------------------------------------------------------------- /doc/xanadu_theme/sourcelink.html: -------------------------------------------------------------------------------- 1 | {%- if show_source and has_source and sourcename %} 2 | 30 | {%- endif %} -------------------------------------------------------------------------------- /doc/xanadu_theme/static/css/nanoscroller.css: -------------------------------------------------------------------------------- 1 | /** initial setup **/ 2 | .nano { 3 | position : relative; 4 | width : 100%; 5 | height : 100%; 6 | overflow : hidden; 7 | } 8 | .nano > .nano-content { 9 | position : absolute; 10 | overflow : scroll; 11 | overflow-x : hidden; 12 | top : 0; 13 | right : 0; 14 | bottom : 0; 15 | left : 0; 16 | } 17 | .nano > .nano-content:focus { 18 | outline: thin dotted; 19 | } 20 | .nano > .nano-content::-webkit-scrollbar { 21 | display: none; 22 | } 23 | .has-scrollbar > .nano-content::-webkit-scrollbar { 24 | display: block; 25 | } 26 | .nano > .nano-pane { 27 | background : rgba(0,0,0,.25); 28 | position : absolute; 29 | width : 10px; 30 | right : 0; 31 | top : 0; 32 | bottom : 0; 33 | visibility : hidden\9; /* Target only IE7 and IE8 with this hack */ 34 | opacity : .01; 35 | -webkit-transition : .2s; 36 | -moz-transition : .2s; 37 | -o-transition : .2s; 38 | transition : .2s; 39 | -moz-border-radius : 5px; 40 | -webkit-border-radius : 5px; 41 | border-radius : 5px; 42 | } 43 | .nano > .nano-pane > .nano-slider { 44 | background: #444; 45 | background: rgba(0,0,0,.5); 46 | position : relative; 47 | margin : 0 1px; 48 | -moz-border-radius : 3px; 49 | -webkit-border-radius : 3px; 50 | border-radius : 3px; 51 | } 52 | .nano:hover > .nano-pane, .nano-pane.active, .nano-pane.flashed { 53 | visibility : visible\9; /* Target only IE7 and IE8 with this hack */ 54 | opacity : 0.99; 55 | } 56 | -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/glyphicons-halflings-regular.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/glyphicons-halflings-regular.eot -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/glyphicons-halflings-regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/glyphicons-halflings-regular.ttf -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/glyphicons-halflings-regular.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/glyphicons-halflings-regular.woff -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-Bold-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-Bold-webfont.eot -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-Bold-webfont.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-Bold-webfont.ttf -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-Bold-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-Bold-webfont.woff -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-BoldItalic-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-BoldItalic-webfont.eot -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-BoldItalic-webfont.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-BoldItalic-webfont.ttf -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-BoldItalic-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-BoldItalic-webfont.woff -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-ExtraBold-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-ExtraBold-webfont.eot -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-ExtraBold-webfont.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-ExtraBold-webfont.ttf -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-ExtraBold-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-ExtraBold-webfont.woff -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-ExtraBoldItalic-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-ExtraBoldItalic-webfont.eot -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-ExtraBoldItalic-webfont.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-ExtraBoldItalic-webfont.ttf -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-ExtraBoldItalic-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-ExtraBoldItalic-webfont.woff -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-Italic-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-Italic-webfont.eot -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-Italic-webfont.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-Italic-webfont.ttf -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-Italic-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-Italic-webfont.woff -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-Light-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-Light-webfont.eot -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-Light-webfont.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-Light-webfont.ttf -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-Light-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-Light-webfont.woff -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-LightItalic-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-LightItalic-webfont.eot -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-LightItalic-webfont.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-LightItalic-webfont.ttf -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-LightItalic-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-LightItalic-webfont.woff -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-Regular-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-Regular-webfont.eot -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-Regular-webfont.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-Regular-webfont.ttf -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-Regular-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-Regular-webfont.woff -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-Semibold-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-Semibold-webfont.eot -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-Semibold-webfont.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-Semibold-webfont.ttf -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-Semibold-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-Semibold-webfont.woff -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-SemiboldItalic-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-SemiboldItalic-webfont.eot -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-SemiboldItalic-webfont.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-SemiboldItalic-webfont.ttf -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-SemiboldItalic-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/open-sans/fonts/OpenSans-SemiboldItalic-webfont.woff -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/open-sans/stylesheet.css: -------------------------------------------------------------------------------- 1 | /***** Font Definition for Open Sans. This stylesheet comes from qrohlf.com/posts/better-opensans *****/ 2 | 3 | /* Regular */ 4 | @font-face { 5 | font-family: 'Open Sans'; 6 | 7 | src: url('fonts/OpenSans-Regular-webfont.eot'); 8 | src: url('fonts/OpenSans-Regular-webfont.eot?#iefix') format('embedded-opentype'), 9 | url('fonts/OpenSans-Regular-webfont.woff') format('woff'), 10 | url('fonts/OpenSans-Regular-webfont.ttf') format('truetype'), 11 | url('fonts/OpenSans-Regular-webfont.svg#OpenSansRegular') format('svg'); 12 | font-weight: normal; 13 | font-weight: 400; 14 | font-style: normal; 15 | 16 | } 17 | 18 | /* Italic */ 19 | @font-face { 20 | font-family: 'Open Sans'; 21 | src: url('fonts/OpenSans-Italic-webfont.eot'); 22 | src: url('fonts/OpenSans-Italic-webfont.eot?#iefix') format('embedded-opentype'), 23 | url('fonts/OpenSans-Italic-webfont.woff') format('woff'), 24 | url('fonts/OpenSans-Italic-webfont.ttf') format('truetype'), 25 | url('fonts/OpenSans-Italic-webfont.svg#OpenSansItalic') format('svg'); 26 | font-weight: normal; 27 | font-weight: 400; 28 | font-style: italic; 29 | 30 | } 31 | 32 | /* Light */ 33 | @font-face { 34 | font-family: 'Open Sans'; 35 | src: url('fonts/OpenSans-Light-webfont.eot'); 36 | src: url('fonts/OpenSans-Light-webfont.eot?#iefix') format('embedded-opentype'), 37 | url('fonts/OpenSans-Light-webfont.woff') format('woff'), 38 | url('fonts/OpenSans-Light-webfont.ttf') format('truetype'), 39 | url('fonts/OpenSans-Light-webfont.svg#OpenSansLight') format('svg'); 40 | font-weight: 200; 41 | font-style: normal; 42 | 43 | } 44 | 45 | /* Light Italic */ 46 | @font-face { 47 | font-family: 'Open Sans'; 48 | src: url('fonts/OpenSans-LightItalic-webfont.eot'); 49 | src: url('fonts/OpenSans-LightItalic-webfont.eot?#iefix') format('embedded-opentype'), 50 | url('fonts/OpenSans-LightItalic-webfont.woff') format('woff'), 51 | url('fonts/OpenSans-LightItalic-webfont.ttf') format('truetype'), 52 | url('fonts/OpenSans-LightItalic-webfont.svg#OpenSansLightItalic') format('svg'); 53 | font-weight: 200; 54 | font-style: italic; 55 | 56 | } 57 | 58 | /* Semibold */ 59 | @font-face { 60 | font-family: 'Open Sans'; 61 | src: url('fonts/OpenSans-Semibold-webfont.eot'); 62 | src: url('fonts/OpenSans-Semibold-webfont.eot?#iefix') format('embedded-opentype'), 63 | url('fonts/OpenSans-Semibold-webfont.woff') format('woff'), 64 | url('fonts/OpenSans-Semibold-webfont.ttf') format('truetype'), 65 | url('fonts/OpenSans-Semibold-webfont.svg#OpenSansSemibold') format('svg'); 66 | font-weight: 500; 67 | font-style: normal; 68 | 69 | } 70 | 71 | /* Semibold Italic */ 72 | @font-face { 73 | font-family: 'Open Sans'; 74 | src: url('fonts/OpenSans-SemiboldItalic-webfont.eot'); 75 | src: url('fonts/OpenSans-SemiboldItalic-webfont.eot?#iefix') format('embedded-opentype'), 76 | url('fonts/OpenSans-SemiboldItalic-webfont.woff') format('woff'), 77 | url('fonts/OpenSans-SemiboldItalic-webfont.ttf') format('truetype'), 78 | url('fonts/OpenSans-SemiboldItalic-webfont.svg#OpenSansSemiboldItalic') format('svg'); 79 | font-weight: 500; 80 | font-style: italic; 81 | 82 | } 83 | 84 | /* Bold */ 85 | @font-face { 86 | font-family: 'Open Sans'; 87 | src: url('fonts/OpenSans-Bold-webfont.eot'); 88 | src: url('fonts/OpenSans-Bold-webfont.eot?#iefix') format('embedded-opentype'), 89 | url('fonts/OpenSans-Bold-webfont.woff') format('woff'), 90 | url('fonts/OpenSans-Bold-webfont.ttf') format('truetype'), 91 | url('fonts/OpenSans-Bold-webfont.svg#OpenSansBold') format('svg'); 92 | font-weight: bold; 93 | font-weight: 700; 94 | font-style: normal; 95 | 96 | } 97 | 98 | /* Bold Italic */ 99 | @font-face { 100 | font-family: 'Open Sans'; 101 | src: url('fonts/OpenSans-BoldItalic-webfont.eot'); 102 | src: url('fonts/OpenSans-BoldItalic-webfont.eot?#iefix') format('embedded-opentype'), 103 | url('fonts/OpenSans-BoldItalic-webfont.woff') format('woff'), 104 | url('fonts/OpenSans-BoldItalic-webfont.ttf') format('truetype'), 105 | url('fonts/OpenSans-BoldItalic-webfont.svg#OpenSansBoldItalic') format('svg'); 106 | font-weight: bold; 107 | font-weight: 700; 108 | font-style: italic; 109 | 110 | } 111 | 112 | /* Extra Bold */ 113 | @font-face { 114 | font-family: 'Open Sans'; 115 | src: url('fonts/OpenSans-ExtraBold-webfont.eot'); 116 | src: url('fonts/OpenSans-ExtraBold-webfont.eot?#iefix') format('embedded-opentype'), 117 | url('fonts/OpenSans-ExtraBold-webfont.woff') format('woff'), 118 | url('fonts/OpenSans-ExtraBold-webfont.ttf') format('truetype'), 119 | url('fonts/OpenSans-ExtraBold-webfont.svg#OpenSansExtrabold') format('svg'); 120 | font-weight: 900; 121 | font-style: normal; 122 | 123 | } 124 | 125 | /* Extra Bold Italic */ 126 | @font-face { 127 | font-family: 'Open Sans'; 128 | src: url('fonts/OpenSans-ExtraBoldItalic-webfont.eot'); 129 | src: url('fonts/OpenSans-ExtraBoldItalic-webfont.eot?#iefix') format('embedded-opentype'), 130 | url('fonts/OpenSans-ExtraBoldItalic-webfont.woff') format('woff'), 131 | url('fonts/OpenSans-ExtraBoldItalic-webfont.ttf') format('truetype'), 132 | url('fonts/OpenSans-ExtraBoldItalic-webfont.svg#OpenSansExtraboldItalic') format('svg'); 133 | font-weight: 900; 134 | font-style: italic; 135 | 136 | } 137 | -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/source-serif-pro/EOT/SourceSerifPro-Black.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/source-serif-pro/EOT/SourceSerifPro-Black.eot -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/source-serif-pro/EOT/SourceSerifPro-Bold.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/source-serif-pro/EOT/SourceSerifPro-Bold.eot -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/source-serif-pro/EOT/SourceSerifPro-ExtraLight.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/source-serif-pro/EOT/SourceSerifPro-ExtraLight.eot -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/source-serif-pro/EOT/SourceSerifPro-Light.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/source-serif-pro/EOT/SourceSerifPro-Light.eot -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/source-serif-pro/EOT/SourceSerifPro-Regular.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/source-serif-pro/EOT/SourceSerifPro-Regular.eot -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/source-serif-pro/EOT/SourceSerifPro-Semibold.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/source-serif-pro/EOT/SourceSerifPro-Semibold.eot -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/source-serif-pro/LICENSE.txt: -------------------------------------------------------------------------------- 1 | Copyright 2014 Adobe Systems Incorporated (http://www.adobe.com/), with Reserved Font Name 'Source'. All Rights Reserved. Source is a trademark of Adobe Systems Incorporated in the United States and/or other countries. 2 | 3 | This Font Software is licensed under the SIL Open Font License, Version 1.1. 4 | 5 | This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL 6 | 7 | 8 | ----------------------------------------------------------- 9 | SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 10 | ----------------------------------------------------------- 11 | 12 | PREAMBLE 13 | The goals of the Open Font License (OFL) are to stimulate worldwide 14 | development of collaborative font projects, to support the font creation 15 | efforts of academic and linguistic communities, and to provide a free and 16 | open framework in which fonts may be shared and improved in partnership 17 | with others. 18 | 19 | The OFL allows the licensed fonts to be used, studied, modified and 20 | redistributed freely as long as they are not sold by themselves. The 21 | fonts, including any derivative works, can be bundled, embedded, 22 | redistributed and/or sold with any software provided that any reserved 23 | names are not used by derivative works. The fonts and derivatives, 24 | however, cannot be released under any other type of license. The 25 | requirement for fonts to remain under this license does not apply 26 | to any document created using the fonts or their derivatives. 27 | 28 | DEFINITIONS 29 | "Font Software" refers to the set of files released by the Copyright 30 | Holder(s) under this license and clearly marked as such. This may 31 | include source files, build scripts and documentation. 32 | 33 | "Reserved Font Name" refers to any names specified as such after the 34 | copyright statement(s). 35 | 36 | "Original Version" refers to the collection of Font Software components as 37 | distributed by the Copyright Holder(s). 38 | 39 | "Modified Version" refers to any derivative made by adding to, deleting, 40 | or substituting -- in part or in whole -- any of the components of the 41 | Original Version, by changing formats or by porting the Font Software to a 42 | new environment. 43 | 44 | "Author" refers to any designer, engineer, programmer, technical 45 | writer or other person who contributed to the Font Software. 46 | 47 | PERMISSION & CONDITIONS 48 | Permission is hereby granted, free of charge, to any person obtaining 49 | a copy of the Font Software, to use, study, copy, merge, embed, modify, 50 | redistribute, and sell modified and unmodified copies of the Font 51 | Software, subject to the following conditions: 52 | 53 | 1) Neither the Font Software nor any of its individual components, 54 | in Original or Modified Versions, may be sold by itself. 55 | 56 | 2) Original or Modified Versions of the Font Software may be bundled, 57 | redistributed and/or sold with any software, provided that each copy 58 | contains the above copyright notice and this license. These can be 59 | included either as stand-alone text files, human-readable headers or 60 | in the appropriate machine-readable metadata fields within text or 61 | binary files as long as those fields can be easily viewed by the user. 62 | 63 | 3) No Modified Version of the Font Software may use the Reserved Font 64 | Name(s) unless explicit written permission is granted by the corresponding 65 | Copyright Holder. This restriction only applies to the primary font name as 66 | presented to the users. 67 | 68 | 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font 69 | Software shall not be used to promote, endorse or advertise any 70 | Modified Version, except to acknowledge the contribution(s) of the 71 | Copyright Holder(s) and the Author(s) or with their explicit written 72 | permission. 73 | 74 | 5) The Font Software, modified or unmodified, in part or in whole, 75 | must be distributed entirely under this license, and must not be 76 | distributed under any other license. The requirement for fonts to 77 | remain under this license does not apply to any document created 78 | using the Font Software. 79 | 80 | TERMINATION 81 | This license becomes null and void if any of the above conditions are 82 | not met. 83 | 84 | DISCLAIMER 85 | THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 86 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF 87 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT 88 | OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE 89 | COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 90 | INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL 91 | DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 92 | FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM 93 | OTHER DEALINGS IN THE FONT SOFTWARE. 94 | -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/source-serif-pro/OTF/SourceSerifPro-Black.otf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/source-serif-pro/OTF/SourceSerifPro-Black.otf -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/source-serif-pro/OTF/SourceSerifPro-Bold.otf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/source-serif-pro/OTF/SourceSerifPro-Bold.otf -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/source-serif-pro/OTF/SourceSerifPro-ExtraLight.otf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/source-serif-pro/OTF/SourceSerifPro-ExtraLight.otf -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/source-serif-pro/OTF/SourceSerifPro-Light.otf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/source-serif-pro/OTF/SourceSerifPro-Light.otf -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/source-serif-pro/OTF/SourceSerifPro-Regular.otf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/source-serif-pro/OTF/SourceSerifPro-Regular.otf -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/source-serif-pro/OTF/SourceSerifPro-Semibold.otf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/source-serif-pro/OTF/SourceSerifPro-Semibold.otf -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/source-serif-pro/README.md: -------------------------------------------------------------------------------- 1 | # Source Serif Pro 2 | 3 | Source Serif Pro is a set of OpenType fonts to complement the [Source Sans Pro](https://github.com/adobe-fonts/source-sans-pro) family. 4 | In addition to a functional OpenType font, this open source project provides all of the source files that were used to build this OpenType font by using the AFDKO makeotf tool. 5 | 6 | ## Installation instructions 7 | 8 | * [Mac OS X](http://support.apple.com/kb/HT2509) 9 | * [Windows](http://windows.microsoft.com/en-us/windows-vista/install-or-uninstall-fonts) 10 | * [Linux/Unix-based systems](https://github.com/adobe-fonts/source-code-pro/issues/17#issuecomment-8967116) 11 | 12 | ## Getting Involved 13 | 14 | Send suggestions for changes to the Source Serif OpenType font project maintainer, [Frank Grießhammer](mailto:opensourcefonts@adobe.com?subject=[GitHub] Source Serif Pro), for consideration. 15 | 16 | ## Further information 17 | 18 | For information about the design and background of Source Serif, please refer to the [official font readme file](http://htmlpreview.github.io/?https://github.com/adobe-fonts/source-serif-pro/blob/master/SourceSerifProReadMe.html). 19 | -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/source-serif-pro/ReadMe.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Read Me File for Adobe® OpenType® Fonts 5 | 6 | 7 | 8 |

Adobe® OpenType® Fonts

10 |

Thank 11 | you for licensing Adobe OpenType fonts. In order to ensure that you 12 | have the most up-to-date product information, Adobe has posted an OpenType 14 | Read Me file on the Adobe web site that contains information such 15 | as minimum system requirements, technical support contact information 16 | and software installation notes. We have also posted an OpenType 18 | User's Guide in PDF format on the Adobe web site that can be 19 | viewed online and downloaded to your computer.

If you have 20 | licensed an Adobe OpenType Pro font, there may be additional PDF 21 | documents, such as a specimen book, a glyph complement showing, and a 22 | typeface-specific Read Me file, available on the typeface’s 23 | product pages on the Adobe web site. These additional files may be 24 | viewed online or downloaded to your computer.

To get you started 25 | quickly, below are links to localized installation instructions for 26 | your fonts. 27 | 28 |

Installation Instructions


29 |

English
30 | Instructions for installing this font can be found online at http://www.adobe.com/type/browser/fontinstall/instructions_main.html.

32 |

French / Français
33 | Le mode d'installation de cette police de caractère se trouve en 34 | ligne à http://www.adobe.com/type/browser/fontinstall/instructions_main.html.

36 |

German / Deutsch
37 | Die Anweisungen zur Installation dieser Schriftart finden Sie online 38 | unter http://www.adobe.com/type/browser/fontinstall/instructions_main.html.

40 |

Italian / Italiano
41 | Le istruzioni per l'installazione di questo font sono disponibili 42 | online all'indirizzo http://www.adobe.com/type/browser/fontinstall/instructions_main.html.

44 |

Spanish / Español
45 | Las instrucciones para instalar esta fuente se pueden encontrar 46 | online en http://www.adobe.com/type/browser/fontinstall/instructions_main.html.

48 |

Dutch / Hollands
49 | De instructies voor de installatie van dit lettertype vindt u op http://www.adobe.com/type/browser/fontinstall/instructions_main.html.

51 |

Swedish / Svenska
52 | Anvisningar för hur det här teckensnittet installeras finns 53 | online på http://www.adobe.com/type/browser/fontinstall/instructions_main.html.

55 |

Norwegian / Norsk
56 | Instruksjoner for installering av skrifttypen finnes online på 57 | http://www.adobe.com/type/browser/fontinstall/instructions_main.html.

59 |

Finnish / Suomi
60 | Ohjeet tämän fontin asentamiseen löytyvät 61 | osoitteesta http://www.adobe.com/type/browser/fontinstall/instructions_main.html.

63 |

Danish / Dansk
64 | Du finder en vejledning i installation af denne skrifttype online 65 | på adressen http://www.adobe.com/type/browser/fontinstall/instructions_main.html.

67 |

Japanese / 日本語
68 | このフォントをインストールする手順は、オンラインで http://www.adobe.com/type/browser/fontinstall/instructions_main.html 70 | を参照してください。

71 | 72 | 73 | -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/source-serif-pro/TTF/SourceSerifPro-Black.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/source-serif-pro/TTF/SourceSerifPro-Black.ttf -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/source-serif-pro/TTF/SourceSerifPro-Bold.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/source-serif-pro/TTF/SourceSerifPro-Bold.ttf -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/source-serif-pro/TTF/SourceSerifPro-ExtraLight.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/source-serif-pro/TTF/SourceSerifPro-ExtraLight.ttf -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/source-serif-pro/TTF/SourceSerifPro-Light.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/source-serif-pro/TTF/SourceSerifPro-Light.ttf -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/source-serif-pro/TTF/SourceSerifPro-Regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/source-serif-pro/TTF/SourceSerifPro-Regular.ttf -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/source-serif-pro/TTF/SourceSerifPro-Semibold.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/source-serif-pro/TTF/SourceSerifPro-Semibold.ttf -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/source-serif-pro/WOFF/OTF/SourceSerifPro-Black.otf.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/source-serif-pro/WOFF/OTF/SourceSerifPro-Black.otf.woff -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/source-serif-pro/WOFF/OTF/SourceSerifPro-Bold.otf.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/source-serif-pro/WOFF/OTF/SourceSerifPro-Bold.otf.woff -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/source-serif-pro/WOFF/OTF/SourceSerifPro-ExtraLight.otf.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/source-serif-pro/WOFF/OTF/SourceSerifPro-ExtraLight.otf.woff -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/source-serif-pro/WOFF/OTF/SourceSerifPro-Light.otf.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/source-serif-pro/WOFF/OTF/SourceSerifPro-Light.otf.woff -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/source-serif-pro/WOFF/OTF/SourceSerifPro-Regular.otf.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/source-serif-pro/WOFF/OTF/SourceSerifPro-Regular.otf.woff -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/source-serif-pro/WOFF/OTF/SourceSerifPro-Semibold.otf.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/source-serif-pro/WOFF/OTF/SourceSerifPro-Semibold.otf.woff -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/source-serif-pro/WOFF/TTF/SourceSerifPro-Black.ttf.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/source-serif-pro/WOFF/TTF/SourceSerifPro-Black.ttf.woff -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/source-serif-pro/WOFF/TTF/SourceSerifPro-Bold.ttf.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/source-serif-pro/WOFF/TTF/SourceSerifPro-Bold.ttf.woff -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/source-serif-pro/WOFF/TTF/SourceSerifPro-ExtraLight.ttf.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/source-serif-pro/WOFF/TTF/SourceSerifPro-ExtraLight.ttf.woff -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/source-serif-pro/WOFF/TTF/SourceSerifPro-Light.ttf.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/source-serif-pro/WOFF/TTF/SourceSerifPro-Light.ttf.woff -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/source-serif-pro/WOFF/TTF/SourceSerifPro-Regular.ttf.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/source-serif-pro/WOFF/TTF/SourceSerifPro-Regular.ttf.woff -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/source-serif-pro/WOFF/TTF/SourceSerifPro-Semibold.ttf.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XanaduAI/QMLT/fc9487f89bf894576d2001abe5a5d07f35f19d7a/doc/xanadu_theme/static/fonts/source-serif-pro/WOFF/TTF/SourceSerifPro-Semibold.ttf.woff -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/source-serif-pro/bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "source-serif-pro", 3 | "version": "1.014", 4 | "main": "source-serif-pro.css", 5 | "homepage": "https://github.com/adobe-fonts/source-serif-pro", 6 | "repository": { 7 | "type": "git", 8 | "url": "https://github.com/adobe-fonts/source-serif-pro.git" 9 | }, 10 | "authors": [ 11 | { "name": "Frank Grießhammer" } 12 | ], 13 | "description": "Source Serif Pro font family by Adobe", 14 | "license": "SIL OFL 1.1" 15 | } 16 | -------------------------------------------------------------------------------- /doc/xanadu_theme/static/fonts/source-serif-pro/source-serif-pro.css: -------------------------------------------------------------------------------- 1 | @font-face{ 2 | font-family: 'Source Serif Pro'; 3 | font-weight: 200; 4 | font-style: normal; 5 | font-stretch: normal; 6 | src: url('EOT/SourceSerifPro-ExtraLight.eot') format('embedded-opentype'), 7 | url('WOFF/OTF/SourceSerifPro-ExtraLight.otf.woff') format('woff'), 8 | url('OTF/SourceSerifPro-ExtraLight.otf') format('opentype'), 9 | url('TTF/SourceSerifPro-ExtraLight.ttf') format('truetype'); 10 | } 11 | 12 | @font-face{ 13 | font-family: 'Source Serif Pro'; 14 | font-weight: 300; 15 | font-style: normal; 16 | font-stretch: normal; 17 | src: url('EOT/SourceSerifPro-Light.eot') format('embedded-opentype'), 18 | url('WOFF/OTF/SourceSerifPro-Light.otf.woff') format('woff'), 19 | url('OTF/SourceSerifPro-Light.otf') format('opentype'), 20 | url('TTF/SourceSerifPro-Light.ttf') format('truetype'); 21 | } 22 | 23 | @font-face{ 24 | font-family: 'Source Serif Pro'; 25 | font-weight: 400; 26 | font-style: normal; 27 | font-stretch: normal; 28 | src: url('EOT/SourceSerifPro-Regular.eot') format('embedded-opentype'), 29 | url('WOFF/OTF/SourceSerifPro-Regular.otf.woff') format('woff'), 30 | url('OTF/SourceSerifPro-Regular.otf') format('opentype'), 31 | url('TTF/SourceSerifPro-Regular.ttf') format('truetype'); 32 | } 33 | 34 | @font-face{ 35 | font-family: 'Source Serif Pro'; 36 | font-weight: 600; 37 | font-style: normal; 38 | font-stretch: normal; 39 | src: url('EOT/SourceSerifPro-Semibold.eot') format('embedded-opentype'), 40 | url('WOFF/OTF/SourceSerifPro-Semibold.otf.woff') format('woff'), 41 | url('OTF/SourceSerifPro-Semibold.otf') format('opentype'), 42 | url('TTF/SourceSerifPro-Semibold.ttf') format('truetype'); 43 | } 44 | 45 | @font-face{ 46 | font-family: 'Source Serif Pro'; 47 | font-weight: 700; 48 | font-style: normal; 49 | font-stretch: normal; 50 | src: url('EOT/SourceSerifPro-Bold.eot') format('embedded-opentype'), 51 | url('WOFF/OTF/SourceSerifPro-Bold.otf.woff') format('woff'), 52 | url('OTF/SourceSerifPro-Bold.otf') format('opentype'), 53 | url('TTF/SourceSerifPro-Bold.ttf') format('truetype'); 54 | } 55 | 56 | @font-face{ 57 | font-family: 'Source Serif Pro'; 58 | font-weight: 900; 59 | font-style: normal; 60 | font-stretch: normal; 61 | src: url('EOT/SourceSerifPro-Black.eot') format('embedded-opentype'), 62 | url('WOFF/OTF/SourceSerifPro-Black.otf.woff') format('woff'), 63 | url('OTF/SourceSerifPro-Black.otf') format('opentype'), 64 | url('TTF/SourceSerifPro-Black.ttf') format('truetype'); 65 | } 66 | -------------------------------------------------------------------------------- /doc/xanadu_theme/static/tomorrow.css: -------------------------------------------------------------------------------- 1 | .highlight .hll { background-color: #d6d6d6 } 2 | .highlight { background: #ffffff; color: #4d4d4c } 3 | .highlight .c { color: #8e908c } /* Comment */ 4 | .highlight .err { color: #c82829 } /* Error */ 5 | .highlight .k { color: #8959a8 } /* Keyword */ 6 | .highlight .l { color: #f5871f } /* Literal */ 7 | .highlight .n { color: #4d4d4c } /* Name */ 8 | .highlight .o { color: #3e999f } /* Operator */ 9 | .highlight .p { color: #4d4d4c } /* Punctuation */ 10 | .highlight .cm { color: #8e908c } /* Comment.Multiline */ 11 | .highlight .cp { color: #8e908c } /* Comment.Preproc */ 12 | .highlight .c1 { color: #8e908c } /* Comment.Single */ 13 | .highlight .cs { color: #8e908c } /* Comment.Special */ 14 | .highlight .gd { color: #c82829 } /* Generic.Deleted */ 15 | .highlight .ge { font-style: italic } /* Generic.Emph */ 16 | .highlight .gh { color: #4d4d4c; font-weight: bold } /* Generic.Heading */ 17 | .highlight .gi { color: #718c00 } /* Generic.Inserted */ 18 | /*.highlight .gp { color: #8e908c; font-weight: bold } /* Generic.Prompt */*/ 19 | .highlight .gs { font-weight: bold } /* Generic.Strong */ 20 | .highlight .gu { color: #3e999f; font-weight: bold } /* Generic.Subheading */ 21 | .highlight .kc { color: #8959a8 } /* Keyword.Constant */ 22 | .highlight .kd { color: #8959a8 } /* Keyword.Declaration */ 23 | .highlight .kn { color: #3e999f } /* Keyword.Namespace */ 24 | .highlight .kp { color: #8959a8 } /* Keyword.Pseudo */ 25 | .highlight .kr { color: #8959a8 } /* Keyword.Reserved */ 26 | .highlight .kt { color: #eab700 } /* Keyword.Type */ 27 | .highlight .ld { color: #718c00 } /* Literal.Date */ 28 | .highlight .m { color: #f5871f } /* Literal.Number */ 29 | .highlight .s { color: #718c00 } /* Literal.String */ 30 | .highlight .na { color: #4271ae } /* Name.Attribute */ 31 | .highlight .nb { color: #4d4d4c } /* Name.Builtin */ 32 | .highlight .nc { color: #eab700 } /* Name.Class */ 33 | .highlight .no { color: #c82829 } /* Name.Constant */ 34 | .highlight .nd { color: #3e999f } /* Name.Decorator */ 35 | .highlight .ni { color: #4d4d4c } /* Name.Entity */ 36 | .highlight .ne { color: #c82829 } /* Name.Exception */ 37 | .highlight .nf { color: #4271ae } /* Name.Function */ 38 | .highlight .nl { color: #4d4d4c } /* Name.Label */ 39 | .highlight .nn { color: #eab700 } /* Name.Namespace */ 40 | .highlight .nx { color: #4271ae } /* Name.Other */ 41 | .highlight .py { color: #4d4d4c } /* Name.Property */ 42 | .highlight .nt { color: #3e999f } /* Name.Tag */ 43 | .highlight .nv { color: #c82829 } /* Name.Variable */ 44 | .highlight .ow { color: #3e999f } /* Operator.Word */ 45 | .highlight .w { color: #4d4d4c } /* Text.Whitespace */ 46 | .highlight .mf { color: #f5871f } /* Literal.Number.Float */ 47 | .highlight .mh { color: #f5871f } /* Literal.Number.Hex */ 48 | .highlight .mi { color: #f5871f } /* Literal.Number.Integer */ 49 | .highlight .mo { color: #f5871f } /* Literal.Number.Oct */ 50 | .highlight .sb { color: #718c00 } /* Literal.String.Backtick */ 51 | .highlight .sc { color: #4d4d4c } /* Literal.String.Char */ 52 | .highlight .sd { color: #8e908c } /* Literal.String.Doc */ 53 | .highlight .s2 { color: #718c00 } /* Literal.String.Double */ 54 | .highlight .se { color: #f5871f } /* Literal.String.Escape */ 55 | .highlight .sh { color: #718c00 } /* Literal.String.Heredoc */ 56 | .highlight .si { color: #f5871f } /* Literal.String.Interpol */ 57 | .highlight .sx { color: #718c00 } /* Literal.String.Other */ 58 | .highlight .sr { color: #718c00 } /* Literal.String.Regex */ 59 | .highlight .s1 { color: #718c00 } /* Literal.String.Single */ 60 | .highlight .ss { color: #718c00 } /* Literal.String.Symbol */ 61 | .highlight .bp { color: #4d4d4c } /* Name.Builtin.Pseudo */ 62 | .highlight .vc { color: #c82829 } /* Name.Variable.Class */ 63 | .highlight .vg { color: #c82829 } /* Name.Variable.Global */ 64 | .highlight .vi { color: #c82829 } /* Name.Variable.Instance */ 65 | .highlight .il { color: #f5871f } /* Literal.Number.Integer.Long */ -------------------------------------------------------------------------------- /doc/xanadu_theme/static/tomorrow_night.css: -------------------------------------------------------------------------------- 1 | /*! tomorrow night; https://github.com/MozMorris/tomorrow-pygments */ 2 | /*.highlight, .highlight pre, .highlight table { background: #1d1f21 !important; color: #c5c8c6 !important; }*/ 3 | .highlight .hll { background-color: #373b41 !important; } 4 | .highlight .c { color: #969896 !important; } /* Comment */ 5 | .highlight .err { color: #cc6666 !important; } /* Error */ 6 | .highlight .k { color: #b294bb !important; } /* Keyword */ 7 | .highlight .l { color: #de935f !important; } /* Literal */ 8 | .highlight .n, .highlight .h { color: #c5c8c6 !important; } /* Name */ 9 | .highlight .o { color: #8abeb7 !important; } /* Operator */ 10 | .highlight .p { color: #c5c8c6 !important; } /* Punctuation */ 11 | .highlight .cm { color: #969896 !important; } /* Comment.Multiline */ 12 | .highlight .cp { color: #969896 !important; } /* Comment.Preproc */ 13 | .highlight .c1 { color: #969896 !important; } /* Comment.Single */ 14 | .highlight .cs { color: #969896 !important; } /* Comment.Special */ 15 | .highlight .gd { color: #cc6666 !important; } /* Generic.Deleted */ 16 | .highlight .ge { font-style: italic !important; } /* Generic.Emph */ 17 | .highlight .gh { color: #c5c8c6 !important; font-weight: bold !important; } /* Generic.Heading */ 18 | .highlight .gi { color: #b5bd68 !important; } /* Generic.Inserted */ 19 | .highlight .go { color: #b5bd68 !important; } /* Generic.Inserted */ 20 | /*.highlight .gp { color: #969896 !important; font-weight: bold !important; } /* Generic.Prompt */*/ 21 | .highlight .gs { font-weight: bold !important; } /* Generic.Strong */ 22 | .highlight .gu { color: #8abeb7 !important; font-weight: bold !important; } /* Generic.Subheading */ 23 | .highlight .kc { color: #b294bb !important; } /* Keyword.Constant */ 24 | .highlight .kd { color: #b294bb !important; } /* Keyword.Declaration */ 25 | .highlight .kn { color: #8abeb7 !important; } /* Keyword.Namespace */ 26 | .highlight .kp { color: #b294bb !important; } /* Keyword.Pseudo */ 27 | .highlight .kr { color: #b294bb !important; } /* Keyword.Reserved */ 28 | .highlight .kt { color: #f0c674 !important; } /* Keyword.Type */ 29 | .highlight .ld { color: #b5bd68 !important; } /* Literal.Date */ 30 | .highlight .m { color: #de935f !important; } /* Literal.Number */ 31 | .highlight .s { color: #b5bd68 !important; } /* Literal.String */ 32 | .highlight .na { color: #81a2be !important; } /* Name.Attribute */ 33 | .highlight .nb { color: #c5c8c6 !important; } /* Name.Builtin */ 34 | .highlight .nc { color: #f0c674 !important; } /* Name.Class */ 35 | .highlight .no { color: #cc6666 !important; } /* Name.Constant */ 36 | .highlight .nd { color: #8abeb7 !important; } /* Name.Decorator */ 37 | .highlight .ni { color: #c5c8c6 !important; } /* Name.Entity */ 38 | .highlight .ne { color: #cc6666 !important; } /* Name.Exception */ 39 | .highlight .nf { color: #81a2be !important; } /* Name.Function */ 40 | .highlight .nl { color: #c5c8c6 !important; } /* Name.Label */ 41 | .highlight .nn { color: #f0c674 !important; } /* Name.Namespace */ 42 | .highlight .nx { color: #81a2be !important; } /* Name.Other */ 43 | .highlight .py { color: #c5c8c6 !important; } /* Name.Property */ 44 | .highlight .nt { color: #8abeb7 !important; } /* Name.Tag */ 45 | .highlight .nv { color: #cc6666 !important; } /* Name.Variable */ 46 | .highlight .ow { color: #8abeb7 !important; } /* Operator.Word */ 47 | .highlight .w { color: #c5c8c6 !important; } /* Text.Whitespace */ 48 | .highlight .mf { color: #de935f !important; } /* Literal.Number.Float */ 49 | .highlight .mh { color: #de935f !important; } /* Literal.Number.Hex */ 50 | .highlight .mi { color: #de935f !important; } /* Literal.Number.Integer */ 51 | .highlight .mo { color: #de935f !important; } /* Literal.Number.Oct */ 52 | .highlight .sb { color: #b5bd68 !important; } /* Literal.String.Backtick */ 53 | .highlight .sc { color: #c5c8c6 !important; } /* Literal.String.Char */ 54 | .highlight .sd { color: #969896 !important; } /* Literal.String.Doc */ 55 | .highlight .s2 { color: #b5bd68 !important; } /* Literal.String.Double */ 56 | .highlight .se { color: #de935f !important; } /* Literal.String.Escape */ 57 | .highlight .sh { color: #b5bd68 !important; } /* Literal.String.Heredoc */ 58 | .highlight .si { color: #de935f !important; } /* Literal.String.Interpol */ 59 | .highlight .sx { color: #b5bd68 !important; } /* Literal.String.Other */ 60 | .highlight .sr { color: #b5bd68 !important; } /* Literal.String.Regex */ 61 | .highlight .s1 { color: #b5bd68 !important; } /* Literal.String.Single */ 62 | .highlight .ss { color: #b5bd68 !important; } /* Literal.String.Symbol */ 63 | .highlight .bp { color: #c5c8c6 !important; } /* Name.Builtin.Pseudo */ 64 | .highlight .vc { color: #cc6666 !important; } /* Name.Variable.Class */ 65 | .highlight .vg { color: #cc6666 !important; } /* Name.Variable.Global */ 66 | .highlight .vi { color: #cc6666 !important; } /* Name.Variable.Instance */ 67 | .highlight .il { color: #de935f !important; } /* Literal.Number.Integer.Long */ -------------------------------------------------------------------------------- /doc/xanadu_theme/theme.conf: -------------------------------------------------------------------------------- 1 | [theme] 2 | 3 | inherit = basic 4 | stylesheet = xanadu.css 5 | 6 | [options] 7 | 8 | # Set to an html template to load custom HTML for the homepage 9 | index_template = 10 | 11 | # Set the name of the project to appear in the left sidebar. 12 | project_nav_name = 13 | 14 | # Path to a touch icon 15 | touch_icon = 16 | 17 | # Set this value to enable Disqus comments 18 | disqus_comments_shortname = 19 | 20 | # Set to enable google analytics 21 | google_analytics_account = 22 | 23 | # Specify a base_url used to generate sitemap.xml links. If not specified, then 24 | # no sitemap will be built. 25 | base_url = 26 | 27 | # Allow a separate homepage from the "master_doc" 28 | homepage = 29 | 30 | # Allow the project link to be overwritten to a custom URL. 31 | projectlink = 32 | -------------------------------------------------------------------------------- /doc/z_references.rst: -------------------------------------------------------------------------------- 1 | References and further reading 2 | =============================== 3 | 4 | Further reading 5 | --------------- 6 | 7 | For more details and further information on machine learning, optimization, quantum optical circuits, and quantum machine learning, please see the following: 8 | 9 | (Coming soon.) 10 | 11 | .. bibliography:: references.bib 12 | :style: unsrt 13 | :labelprefix: FR 14 | :filter: key % "FR-" 15 | 16 | References 17 | ---------- 18 | 19 | .. bibliography:: references.bib 20 | :cited: 21 | :style: unsrt 22 | 23 | -------------------------------------------------------------------------------- /examples/.gitignore: -------------------------------------------------------------------------------- 1 | logsAuto/* 2 | logsNUM/* 3 | -------------------------------------------------------------------------------- /examples/numerical/optimization_advanced_num.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # Copyright 2018 Xanadu Quantum Technologies Inc. 4 | 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """ 18 | .. currentmodule:: qmlt.examples.numerical 19 | 20 | .. code-author:: Maria Schuld 21 | 22 | We revisit the example of a simple optimization task with the numerical circuit learner and 23 | introduce regularisation, custom logging and monitoring/plotting, 24 | and look at the final parameters. 25 | 26 | """ 27 | 28 | import strawberryfields as sf 29 | from strawberryfields.ops import Dgate 30 | from qmlt.numerical import CircuitLearner 31 | from qmlt.numerical.helpers import make_param 32 | from qmlt.numerical.regularizers import l2 33 | 34 | # This time we want to keep the parameter small via regularization and monitor its evolution 35 | # By logging it into a file and plotting it 36 | my_init_params = [make_param(name='alpha', constant=0.1, regularize=True, monitor=True)] 37 | 38 | 39 | def circuit(params): 40 | 41 | eng, q = sf.Engine(1) 42 | 43 | with eng: 44 | Dgate(params[0]) | q[0] 45 | 46 | state = eng.run('fock', cutoff_dim=7) 47 | 48 | circuit_output = state.fock_prob([1]) 49 | trace = state.trace() 50 | 51 | # Log the trace of the state to check if it is 1 52 | log = {'Prob': circuit_output, 53 | 'Trace': trace} 54 | 55 | # The second return value can be an optional log dictionary 56 | # of one or more values 57 | return circuit_output, log 58 | 59 | 60 | def myloss(circuit_output): 61 | return -circuit_output 62 | 63 | 64 | # We have to define a regularizer function that penalises large parameters that we marked to be regularized 65 | def myregularizer(regularized_params): 66 | # The function is imported from the regularizers module and simply computes the squared Euclidean length of the 67 | # vector of all parameters 68 | return l2(regularized_params) 69 | 70 | 71 | # We add the regularizer function to the model 72 | # The strength of regularizer is regulated by the 73 | # hyperparameter 'regularization_strength'. 74 | # Setting 'plot' to an integer automatically plots some default values 75 | # as well as the monitored circuit parameters. (Requires matplotlib). 76 | hyperparams = {'circuit': circuit, 77 | 'init_circuit_params': my_init_params, 78 | 'task': 'optimization', 79 | 'loss': myloss, 80 | 'regularizer': myregularizer, 81 | 'regularization_strength': 0.5, 82 | 'optimizer': 'SGD', 83 | 'init_learning_rate': 0.1, 84 | 'log_every': 1, 85 | 'plot': True 86 | } 87 | 88 | 89 | learner = CircuitLearner(hyperparams=hyperparams) 90 | 91 | learner.train_circuit(steps=50) 92 | 93 | # Print out the final parameters 94 | final_params = learner.get_circuit_parameters() 95 | # final_params is a dictionary 96 | for name, value in final_params.items(): 97 | print("Parameter {} has the final value {}.".format(name, value)) 98 | 99 | # Look in the 'logsNUM' directory, there should be a file called 'log.csv' that records what happened to alpha 100 | # during training. Play around with the 'regularization_strength' and see how a large strength forces alpha to zero. 101 | 102 | -------------------------------------------------------------------------------- /examples/numerical/optimization_num.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # Copyright 2018 Xanadu Quantum Technologies Inc. 4 | 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """ 18 | .. currentmodule:: qmlt.examples.numerical 19 | 20 | .. code-author:: Maria Schuld 21 | 22 | Example of a simple optimization task with the numerical circuit learner. 23 | 24 | """ 25 | 26 | import strawberryfields as sf 27 | from strawberryfields.ops import Dgate 28 | from qmlt.numerical import CircuitLearner 29 | from qmlt.numerical.helpers import make_param 30 | 31 | # Create a parameter with an initial value of 0.1 32 | my_init_params = [make_param(name='alpha', constant=0.1)] 33 | 34 | 35 | # Define the variational circuit and its output 36 | def circuit(params): 37 | 38 | eng, q = sf.Engine(1) 39 | 40 | with eng: 41 | Dgate(params[0]) | q[0] 42 | 43 | state = eng.run('gaussian') 44 | 45 | # As the output we take the probability of measuring one photon in the mode 46 | circuit_output = state.fock_prob([1]) 47 | return circuit_output 48 | 49 | 50 | # Define a loss function on the outputs of circuit(). 51 | # We use the negative probability of measuring |1> 52 | # so that minimization increases the probability. 53 | def myloss(circuit_output): 54 | return -circuit_output 55 | 56 | 57 | # Set the hyperparameters of the model and the training algorithm 58 | hyperparams = {'circuit': circuit, 59 | 'init_circuit_params': my_init_params, 60 | 'task': 'optimization', 61 | 'loss': myloss, 62 | 'optimizer': 'SGD', 63 | 'init_learning_rate': 0.1 64 | } 65 | 66 | # Create the learner 67 | learner = CircuitLearner(hyperparams=hyperparams) 68 | 69 | # Train the learner 70 | learner.train_circuit(steps=50) 71 | -------------------------------------------------------------------------------- /examples/numerical/supervised_advanced_num.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # Copyright 2018 Xanadu Quantum Technologies Inc. 4 | 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """ 18 | .. currentmodule:: qmlt.examples.numerical 19 | 20 | .. code-author:: Maria Schuld 21 | 22 | We revisit the example of a simple supervised learning task with the numerical circuit learner and 23 | introduce adaptive learning rate, printing, warm start and batch mode. 24 | 25 | """ 26 | 27 | import strawberryfields as sf 28 | from strawberryfields.ops import Dgate, BSgate 29 | import numpy as np 30 | from qmlt.numerical import CircuitLearner 31 | from qmlt.numerical.helpers import make_param 32 | from qmlt.numerical.losses import square_loss 33 | 34 | steps = 200 35 | batch_size = 2 36 | 37 | my_init_params = [make_param(constant=2.)] 38 | 39 | 40 | def circuit(X, params): 41 | 42 | eng, q = sf.Engine(2) 43 | 44 | def single_input_circuit(x): 45 | 46 | eng.reset() 47 | with eng: 48 | Dgate(x[0], 0.) | q[0] 49 | Dgate(x[1], 0.) | q[1] 50 | BSgate(phi=params[0]) | (q[0], q[1]) 51 | BSgate() | (q[0], q[1]) 52 | state = eng.run('fock', cutoff_dim=10, eval=True) 53 | 54 | p0 = state.fock_prob([0, 2]) 55 | p1 = state.fock_prob([2, 0]) 56 | normalization = p0 + p1 + 1e-10 57 | output = p1 / normalization 58 | return output 59 | 60 | circuit_output = [single_input_circuit(x) for x in X] 61 | 62 | return circuit_output 63 | 64 | 65 | def myloss(circuit_output, targets): 66 | return square_loss(outputs=circuit_output, targets=targets) 67 | 68 | 69 | def outputs_to_predictions(circuit_output): 70 | return round(circuit_output) 71 | 72 | 73 | X_train = np.array([[0.2, 0.4], [0.6, 0.8], [0.4, 0.2], [0.8, 0.6]]) 74 | Y_train = np.array([1., 1., 0., 0.]) 75 | X_test = np.array([[0.25, 0.5], [0.5, 0.25]]) 76 | Y_test = np.array([1., 0.]) 77 | X_pred = np.array([[0.4, 0.5], [0.5, 0.4]]) 78 | 79 | # There are some changes here: 80 | # We decay the learning rate by a factor 1/(1-decay*step) in each step. 81 | # When indicating a batch_size, we train_circuit in every step with only a (randomly selected) batch of the data. 82 | # We also print out the results every 10th step. 83 | # Finally, we choose a warm start. This loads the final parameters from the previous training. You can see 84 | # that the global step starts where it ended the last time you ran the script. 85 | hyperparams = {'circuit': circuit, 86 | 'init_circuit_params': my_init_params, 87 | 'task': 'supervised', 88 | 'loss': myloss, 89 | 'optimizer': 'SGD', 90 | 'init_learning_rate': 0.5, 91 | 'decay': 0.01, 92 | 'log_every': 10, 93 | 'warm_start': False #Set this to True after first run 94 | } 95 | 96 | # Create the learner 97 | learner = CircuitLearner(hyperparams=hyperparams) 98 | 99 | # Train the learner 100 | learner.train_circuit(X=X_train, Y=Y_train, steps=steps, batch_size=batch_size) 101 | 102 | # Evaluate the score of a test set 103 | test_score = learner.score_circuit(X=X_test, Y=Y_test, 104 | outputs_to_predictions=outputs_to_predictions) 105 | # The score_circuit() function returns a dictionary of different metrics. We select the accuracy and loss. 106 | print("\nAccuracy on test set: {}".format(test_score['accuracy'])) 107 | print("Loss on test set: {}".format(test_score['loss'])) 108 | 109 | # Predict the labels of the new inputs 110 | predictions = learner.run_circuit(X=X_pred, 111 | outputs_to_predictions=outputs_to_predictions) 112 | print("\nPredictions for new inputs: ", predictions['outputs']) 113 | 114 | 115 | 116 | 117 | -------------------------------------------------------------------------------- /examples/numerical/supervised_num.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # Copyright 2018 Xanadu Quantum Technologies Inc. 4 | 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """ 18 | .. currentmodule:: qmlt.examples.numerical 19 | 20 | .. code-author:: Maria Schuld 21 | 22 | Example of a simple supervised learning task with the numerical circuit learner. 23 | 24 | """ 25 | 26 | import strawberryfields as sf 27 | from strawberryfields.ops import Dgate, BSgate 28 | import numpy as np 29 | from qmlt.numerical import CircuitLearner 30 | from qmlt.numerical.helpers import make_param 31 | from qmlt.numerical.losses import square_loss 32 | 33 | steps = 100 34 | 35 | # Create a parameter with an initial value of 2. 36 | my_init_params = [make_param(name='phi', constant=2.)] 37 | 38 | 39 | # Define the variational circuit and its output 40 | def circuit(X, params): 41 | 42 | eng, q = sf.Engine(2) 43 | 44 | # Since X is a batch of data, define a circuit for a single input 45 | # If you use the tf backend, you can pass batches into gates 46 | # like in the supervised tf learner example. 47 | def single_input_circuit(x): 48 | 49 | eng.reset() 50 | with eng: 51 | Dgate(x[0], 0.) | q[0] 52 | Dgate(x[1], 0.) | q[1] 53 | BSgate(phi=params[0]) | (q[0], q[1]) 54 | BSgate() | (q[0], q[1]) 55 | state = eng.run('fock', cutoff_dim=10, eval=True) 56 | 57 | # Define the output as the probability of measuring |0,2> as opposed to |2,0> 58 | p0 = state.fock_prob([0, 2]) 59 | p1 = state.fock_prob([2, 0]) 60 | normalization = p0 + p1 + 1e-10 61 | output = p1 / normalization 62 | return output 63 | 64 | # Apply the single circuit to every input in the batch 65 | circuit_output = [single_input_circuit(x) for x in X] 66 | 67 | return circuit_output 68 | 69 | 70 | # Define a loss function that takes the outputs of the variational circuit 71 | # and compares them to the targets 72 | def myloss(circuit_output, targets): 73 | # We use the square loss function provided by MLT 74 | return square_loss(outputs=circuit_output, targets=targets) 75 | 76 | 77 | # Define how to translate the outputs of the circuit into model predictions 78 | def outputs_to_predictions(circuit_output): 79 | return round(circuit_output) 80 | 81 | 82 | # Generate some data 83 | X_train = np.array([[0.2, 0.4], [0.6, 0.8], [0.4, 0.2], [0.8, 0.6]]) 84 | Y_train = np.array([1., 1., 0., 0.]) 85 | X_test = np.array([[0.25, 0.5], [0.5, 0.25]]) 86 | Y_test = np.array([1., 0.]) 87 | X_pred = np.array([[0.4, 0.5], [0.5, 0.4]]) 88 | 89 | # Set the hyperparameters of the model and the training algorithm 90 | hyperparams = {'circuit': circuit, 91 | 'init_circuit_params': my_init_params, 92 | 'task': 'supervised', 93 | 'loss': myloss, 94 | 'optimizer': 'SGD', 95 | 'init_learning_rate': 0.5 96 | } 97 | 98 | # Create the learner 99 | learner = CircuitLearner(hyperparams=hyperparams) 100 | 101 | # Train the learner 102 | learner.train_circuit(X=X_train, Y=Y_train, steps=steps) 103 | 104 | # Evaluate the score of a test set 105 | test_score = learner.score_circuit(X=X_test, Y=Y_test, outputs_to_predictions=outputs_to_predictions) 106 | # The score_circuit() function returns a dictionary of different metrics. 107 | print("\nPossible scores to print: {}".format(list(test_score.keys()))) 108 | # We select the accuracy and loss. 109 | print("Accuracy on test set: {}".format(test_score['accuracy'])) 110 | print("Loss on test set: {}".format(test_score['loss'])) 111 | 112 | outcomes = learner.run_circuit(X=X_pred, outputs_to_predictions=outputs_to_predictions) 113 | # The run_circuit() function returns a dictionary of different outcomes. 114 | print("\nPossible outcomes to print: {}".format(list(outcomes.keys()))) 115 | # We select the predictions 116 | print("Predictions for new inputs: {}".format(outcomes['predictions'])) 117 | 118 | 119 | 120 | 121 | -------------------------------------------------------------------------------- /examples/numerical/unsupervised_advanced_num.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # Copyright 2018 Xanadu Quantum Technologies Inc. 4 | 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """ 18 | .. currentmodule:: qmlt.examples.numerical 19 | 20 | .. code-author:: Maria Schuld 21 | 22 | We revisit the example of a simple unsupervised learning task with the numerical circuit learner and 23 | introduce layered circuit architectures. 24 | 25 | This time the circuit learns a quantum state where Fock 26 | states with zero photons in the first mode have a high measurement probablity. 27 | 28 | """ 29 | 30 | import strawberryfields as sf 31 | from strawberryfields.ops import * 32 | import numpy as np 33 | from qmlt.numerical import CircuitLearner 34 | from qmlt.numerical.helpers import make_param 35 | from qmlt.numerical.regularizers import l2 36 | from qmlt.helpers import sample_from_distribution 37 | 38 | 39 | # Number of layers 40 | depth = 5 41 | steps = 500 42 | 43 | # This time we use a dynamic way to create parameters for each layer 44 | my_params = [] 45 | 46 | for i in range(depth): 47 | my_params.append(make_param(name='phi_' + str(i), stdev=0.2, regularize=False)) 48 | my_params.append(make_param(name='theta_' + str(i), stdev=0.2, regularize=False)) 49 | my_params.append(make_param(name='a_'+str(i), stdev=0.2, regularize=True, monitor=True)) 50 | my_params.append(make_param(name='rtheta_'+str(i), stdev=0.2, regularize=False, monitor=True)) 51 | my_params.append(make_param(name='r_'+str(i), stdev=0.2, regularize=True, monitor=True)) 52 | my_params.append(make_param(name='kappa_'+str(i), stdev=0.2, regularize=True, monitor=True)) 53 | 54 | 55 | def circuit(params): 56 | 57 | # Reshape to access parameter of a layer easier 58 | params = np.reshape(params, (depth, 6)) 59 | 60 | # We define the architecture of a single layer. 61 | def layer(i): 62 | BSgate(params[i, 0], params[i, 1]) | (q[0], q[1]) 63 | Dgate(params[i, 2]) | q[0] 64 | Rgate(params[i, 3]) | q[0] 65 | Sgate(params[i, 4]) | q[0] 66 | Kgate(params[i, 5]) | q[0] 67 | 68 | eng, q = sf.Engine(2) 69 | 70 | with eng: 71 | # Build the circuit of 'depth' layers 72 | for d in range(depth): 73 | layer(d) 74 | 75 | state = eng.run('fock', cutoff_dim=7) 76 | circuit_output = state.all_fock_probs() 77 | 78 | return circuit_output 79 | 80 | 81 | def myloss(circuit_output, X): 82 | circuit_output = np.array(circuit_output) 83 | probs = [circuit_output[x[0], x[1]] for x in X] 84 | prob_total = sum(np.reshape(probs, -1)) 85 | return -prob_total 86 | 87 | 88 | def myregularizer(regularized_params): 89 | return l2(regularized_params) 90 | 91 | 92 | X_train = np.array([[0, 1], 93 | [0, 2], 94 | [0, 3], 95 | [0, 4]]) 96 | 97 | hyperparams = {'circuit': circuit, 98 | 'init_circuit_params': my_params, 99 | 'task': 'unsupervised', 100 | 'optimizer': 'Nelder-Mead', 101 | 'init_learning_rate': 0.1, 102 | 'loss': myloss, 103 | 'regularizer': myregularizer, 104 | 'regularization_strength': 0.1, 105 | 'log_every': 100 106 | } 107 | 108 | learner = CircuitLearner(hyperparams=hyperparams) 109 | 110 | learner.train_circuit(X=X_train, steps=steps) 111 | 112 | outcomes = learner.run_circuit() 113 | final_distribution = outcomes['outputs'] 114 | 115 | for i in range(10): 116 | sample = sample_from_distribution(distribution=final_distribution) 117 | print("Fock state sample {}:{} \n".format(i, sample)) 118 | 119 | # Note: the learner really generalises. Sometimes (albeit rarely) it will 120 | # sample Fock state |0, 5> which it has never seen during training 121 | -------------------------------------------------------------------------------- /examples/numerical/unsupervised_num.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # Copyright 2018 Xanadu Quantum Technologies Inc. 4 | 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """ 18 | .. currentmodule:: qmlt.examples.numerical 19 | 20 | .. code-author:: Maria Schuld 21 | 22 | Example of a simple unsupervised learning task with the numerical circuit learner. 23 | 24 | This example fails to learn the structure of the data, namely to have zero photons in the first mode, 25 | irrespective of the second mode. 26 | 27 | """ 28 | 29 | import strawberryfields as sf 30 | from strawberryfields.ops import * 31 | import numpy as np 32 | from qmlt.numerical import CircuitLearner 33 | from qmlt.numerical.helpers import make_param 34 | from qmlt.numerical.regularizers import l2 35 | from qmlt.helpers import sample_from_distribution 36 | 37 | 38 | # Create some parameters. Mark some of them to be regularized. 39 | my_params = [ 40 | make_param(name='phi', stdev=0.2, regularize=False), 41 | make_param(name='theta', stdev=0.2, regularize=False), 42 | make_param(name='a', stdev=0.2, regularize=True), 43 | make_param(name='rtheta', stdev=0.2, regularize=False), 44 | make_param(name='r', stdev=0.2, regularize=True), 45 | make_param(name='kappa', stdev=0.2, regularize=True) 46 | ] 47 | 48 | 49 | # Define the variational circuit and its output 50 | def circuit(params): 51 | 52 | eng, q = sf.Engine(2) 53 | 54 | with eng: 55 | BSgate(params[0], params[1]) | (q[0], q[1]) 56 | Dgate(params[2]) | q[0] 57 | Rgate(params[3]) | q[0] 58 | Sgate(params[4]) | q[0] 59 | Kgate(params[5]) | q[0] 60 | 61 | state = eng.run('fock', cutoff_dim=7) 62 | circuit_output = state.all_fock_probs() 63 | 64 | return circuit_output 65 | 66 | 67 | # Define a loss function that maximises the probabilities of the states we want to learn 68 | def myloss(circuit_output, X): 69 | probs = [circuit_output[x[0], x[1]] for x in X] 70 | prob_total = sum(np.reshape(probs, -1)) 71 | return -prob_total 72 | 73 | 74 | def myregularizer(regularized_params): 75 | return l2(regularized_params) 76 | 77 | 78 | # Generate some training data. 79 | # The goal is to learn that the first mode contains no photons. 80 | X_train = np.array([[0, 1], 81 | [0, 2], 82 | [0, 3], 83 | [0, 4]]) 84 | 85 | # Set the hyperparameters of the model and the training algorithm 86 | hyperparams = {'circuit': circuit, 87 | 'init_circuit_params': my_params, 88 | 'task': 'unsupervised', 89 | 'optimizer': 'Nelder-Mead', 90 | 'loss': myloss, 91 | 'regularizer': myregularizer, 92 | 'regularization_strength': 0.1, 93 | 'print_log': True, 94 | 'log_every': 100 95 | } 96 | 97 | # Create the learner 98 | learner = CircuitLearner(hyperparams=hyperparams) 99 | 100 | # Train the learner 101 | learner.train_circuit(X=X_train, steps=500) 102 | 103 | # Get the final distribution, which is the circuit output 104 | outcomes = learner.run_circuit() 105 | final_distribution = outcomes['outputs'] 106 | 107 | 108 | # Use a helper function to sample fock states from this state. 109 | # They should show a similar distribution to the training data 110 | for i in range(10): 111 | sample = sample_from_distribution(distribution=final_distribution) 112 | print("Fock state sample {}:{}".format(i, sample)) 113 | 114 | 115 | 116 | -------------------------------------------------------------------------------- /examples/tf/optimization_advanced_tf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # Copyright 2018 Xanadu Quantum Technologies Inc. 4 | 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """ 18 | .. currentmodule:: qmlt.examples.tf 19 | 20 | .. code-author:: Maria Schuld 21 | 22 | We revisit the example of a simple optimization task with the tensorflow circuit learner and 23 | introduce regularisation, custom logging and monitoring, 24 | and look at the final parameters. 25 | 26 | 27 | """ 28 | 29 | import strawberryfields as sf 30 | from strawberryfields.ops import Dgate 31 | import tensorflow as tf 32 | from qmlt.tf.helpers import make_param 33 | from qmlt.tf import CircuitLearner 34 | 35 | 36 | def circuit(): 37 | 38 | # This time we want to keep the parameter small via regularization and visualize its evolution in tensorboard 39 | params = [make_param(name='alpha', constant=0.1, regularize=True, monitor=True)] 40 | eng, q = sf.Engine(1) 41 | 42 | with eng: 43 | Dgate(params[0]) | q[0] 44 | 45 | state = eng.run('tf', cutoff_dim=7, eval=False) 46 | 47 | circuit_output = state.fock_prob([1]) 48 | 49 | # The identity() function allows us to give this tensor a name 50 | # which we can refer to below 51 | circuit_output = tf.identity(circuit_output, name="prob") 52 | trace = tf.identity(state.trace(), name='trace') 53 | 54 | return circuit_output 55 | 56 | 57 | def myloss(circuit_output): 58 | return -circuit_output 59 | 60 | 61 | # We have to define a regularizer function that penalises large parameters that we marked to be regularized 62 | def myregularizer(regularized_params): 63 | # The function is imported from tensorflow and simply computes the squared Euclidean length of the 64 | # vector of all parameters 65 | return tf.nn.l2_loss(regularized_params) 66 | 67 | 68 | # We add the regularizer function to the model 69 | # The strength of regularizer is regulated by the 70 | # hyperparameter 'regularization_strength'. 71 | hyperparams = {'circuit': circuit, 72 | 'task': 'optimization', 73 | 'loss': myloss, 74 | 'regularizer': myregularizer, 75 | 'regularization_strength': 0.5, 76 | 'optimizer': 'SGD', 77 | 'init_learning_rate': 0.1 78 | } 79 | 80 | learner = CircuitLearner(hyperparams=hyperparams) 81 | 82 | # Define the tensors we want displayed in the training log that gets printed, 83 | # and a name to display it. 84 | log = {'Prob': 'prob', 85 | 'Trace': 'trace'} 86 | 87 | learner.train_circuit(steps=50, tensors_to_log=log) 88 | 89 | # Print out the final parameters 90 | final_params = learner.get_circuit_parameters() 91 | # final_params is a dictionary 92 | for name, value in final_params.items(): 93 | print("Parameter {} has the final value {}.".format(name, value)) 94 | 95 | # To monitor the training, install tensorboard, navigate with a terminal to the directory that contains 96 | # the newly created folder "logAUTO" and run "tensorboard --logdir=logAUTO". This should return a link 97 | # which can be opened in a browser. 98 | 99 | # You can track the changes in the variable alpha. Tensorboard gets live updated if you rerun this script. 100 | # Play around with the 'regularization_strength' and see how a large value forces alpha to zero. 101 | -------------------------------------------------------------------------------- /examples/tf/optimization_tf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # Copyright 2018 Xanadu Quantum Technologies Inc. 4 | 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """ 18 | .. currentmodule:: qmlt.examples.tf 19 | 20 | .. code-author:: Maria Schuld 21 | 22 | Example of a simple optimization task with the tensorflow circuit learner. 23 | 24 | """ 25 | 26 | import strawberryfields as sf 27 | from strawberryfields.ops import Dgate 28 | import tensorflow as tf 29 | from qmlt.tf import CircuitLearner 30 | from qmlt.tf.helpers import make_param 31 | 32 | 33 | # Define the variational circuit and its output 34 | def circuit(): 35 | 36 | # Create a parameter with an initial value of 0.1 37 | params = [make_param(name='alpha', constant=0.1)] 38 | 39 | eng, q = sf.Engine(1) 40 | 41 | with eng: 42 | Dgate(params[0]) | q[0] 43 | 44 | state = eng.run('tf', cutoff_dim=7, eval=False) 45 | 46 | # As the output we take the probability of measuring one photon in the mode 47 | prob = state.fock_prob([1]) 48 | circuit_output = tf.identity(prob, name="prob") 49 | return circuit_output 50 | 51 | 52 | # Define a loss function on the outputs of circuit(). 53 | # We use the negative probability of measuring |1> 54 | # so that minimization increases the probability. 55 | def myloss(circuit_output): 56 | return -circuit_output 57 | 58 | 59 | # Set the hyperparameters of the model and the training algorithm 60 | hyperparams = {'circuit': circuit, 61 | 'task': 'optimization', 62 | 'optimizer': 'SGD', 63 | 'init_learning_rate': 0.1, 64 | 'loss': myloss 65 | } 66 | 67 | # Create the learner 68 | learner = CircuitLearner(hyperparams=hyperparams) 69 | 70 | # Train the learner 71 | learner.train_circuit(steps=50) 72 | 73 | -------------------------------------------------------------------------------- /examples/tf/supervised_advanced_tf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # Copyright 2018 Xanadu Quantum Technologies Inc. 4 | 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """ 18 | .. currentmodule:: qmlt.examples.tf 19 | 20 | .. code-author:: Maria Schuld 21 | 22 | We revisit the example of a simple supervised learning task with the tensorflow circuit learner 23 | and introduce adaptive learning rate, printing, warm start and batch mode. 24 | 25 | """ 26 | 27 | import strawberryfields as sf 28 | from strawberryfields.ops import Dgate, BSgate 29 | import tensorflow as tf 30 | 31 | from qmlt.tf.helpers import make_param 32 | from qmlt.tf import CircuitLearner 33 | 34 | 35 | steps = 200 36 | batch_size = 2 37 | 38 | 39 | def circuit(X): 40 | 41 | params = [make_param(name='phi', constant=2., monitor=True)] 42 | 43 | eng, q = sf.Engine(2) 44 | 45 | with eng: 46 | Dgate(X[:, 0], 0.) | q[0] 47 | Dgate(X[:, 1], 0.) | q[1] 48 | BSgate(phi=params[0]) | (q[0], q[1]) 49 | BSgate() | (q[0], q[1]) 50 | 51 | num_inputs = X.get_shape().as_list()[0] 52 | state = eng.run('tf', cutoff_dim=10, eval=False, batch_size=num_inputs) 53 | 54 | p0 = state.fock_prob([0, 2]) 55 | p1 = state.fock_prob([2, 0]) 56 | normalization = p0 + p1 + 1e-10 57 | circuit_output = p1 / normalization 58 | 59 | return circuit_output 60 | 61 | 62 | def myloss(circuit_output, targets): 63 | return tf.losses.mean_squared_error(labels=circuit_output, predictions=targets) 64 | 65 | 66 | def outputs_to_predictions(outpt): 67 | return tf.round(outpt) 68 | 69 | 70 | X_train = [[0.2, 0.4], [0.6, 0.8], [0.4, 0.2], [0.8, 0.6]] 71 | Y_train = [1, 1, 0, 0] 72 | X_test = [[0.25, 0.5], [0.5, 0.25]] 73 | Y_test = [1, 0] 74 | X_pred = [[0.4, 0.5], [0.5, 0.4]] 75 | 76 | 77 | # There are some changes here: 78 | # We decay the learning rate by a factor 1/(1-decay*step) in each step. 79 | # We train_circuit with batches of 2 training inputs (instead of the full batch). 80 | # We also print out the results every 10th step. 81 | # Finally, you can set 'warm start': True to continue previosu training. 82 | # (MAKE SURE YOU RUN THE SAME SCRIPT ONCE WITH A COLD START, 83 | # ELSE YOU GET ERRORS WHEN LOADING THE MODEL!). 84 | # This loads the final parameters from the previous training. You can see 85 | # that the global step starts where it ended the last time you ran the script. 86 | hyperparams = {'circuit': circuit, 87 | 'task': 'supervised', 88 | 'loss': myloss, 89 | 'optimizer': 'SGD', 90 | 'init_learning_rate': 0.5, 91 | 'decay': 0.01, 92 | 'print_log': True, 93 | 'log_every': 10, 94 | 'warm_start': False 95 | } 96 | 97 | learner = CircuitLearner(hyperparams=hyperparams) 98 | 99 | learner.train_circuit(X=X_train, Y=Y_train, steps=steps, batch_size=batch_size) 100 | 101 | test_score = learner.score_circuit(X=X_test, Y=Y_test, 102 | outputs_to_predictions=outputs_to_predictions) 103 | # The score_circuit() function returns a dictionary of different metrics. 104 | print("\nPossible scores to print: {}".format(list(test_score.keys()))) 105 | # We select the accuracy and loss. 106 | print("Accuracy on test set: ", test_score['accuracy']) 107 | print("Loss on test set: ", test_score['loss']) 108 | 109 | outcomes = learner.run_circuit(X=X_pred, 110 | outputs_to_predictions=outputs_to_predictions) 111 | # The run_circuit() function returns a dictionary of different outcomes. 112 | print("\nPossible outcomes to print: {}".format(list(outcomes.keys()))) 113 | # We select the predictions 114 | print("Predictions for new inputs: {}".format(outcomes['predictions'])) 115 | -------------------------------------------------------------------------------- /examples/tf/supervised_tf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # Copyright 2018 Xanadu Quantum Technologies Inc. 4 | 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """ 18 | .. currentmodule:: qmlt.examples.tf 19 | 20 | .. code-author:: Maria Schuld 21 | 22 | Example of a simple supervised learning task with the tensorflow circuit learner. 23 | 24 | """ 25 | 26 | import strawberryfields as sf 27 | from strawberryfields.ops import Dgate, BSgate 28 | import tensorflow as tf 29 | from qmlt.tf.helpers import make_param 30 | from qmlt.tf import CircuitLearner 31 | 32 | 33 | steps = 100 34 | 35 | 36 | # Define the variational circuit and its output. 37 | def circuit(X): 38 | # Create a parameter with an initial value of 2. 39 | params = [make_param(name='phi', constant=2.)] 40 | 41 | eng, q = sf.Engine(2) 42 | 43 | with eng: 44 | # Note that we are feeding 1-d tensors into gates, not scalars! 45 | Dgate(X[:, 0], 0.) | q[0] 46 | Dgate(X[:, 1], 0.) | q[1] 47 | BSgate(phi=params[0]) | (q[0], q[1]) 48 | BSgate() | (q[0], q[1]) 49 | 50 | # We have to tell the engine how big the batches (first dim of X) are 51 | # which we feed into gates 52 | num_inputs = X.get_shape().as_list()[0] 53 | state = eng.run('tf', cutoff_dim=10, eval=False, batch_size=num_inputs) 54 | 55 | # Define the output as the probability of measuring |0,2> as opposed to |2,0> 56 | p0 = state.fock_prob([0, 2]) 57 | p1 = state.fock_prob([2, 0]) 58 | normalization = p0 + p1 + 1e-10 59 | circuit_output = p1 / normalization 60 | 61 | return circuit_output 62 | 63 | 64 | # Define a loss function that takes the outputs of the variational circuit 65 | # and compares them to the targets 66 | def myloss(circuit_output, targets): 67 | # Use tensorflow's predefined loss 68 | return tf.losses.mean_squared_error(labels=circuit_output, predictions=targets) 69 | 70 | 71 | # Define how to translate the outputs of the circuit into model predictions 72 | def outputs_to_predictions(circuit_output): 73 | return tf.round(circuit_output) 74 | 75 | 76 | # Generate some data 77 | X_train = [[0.2, 0.4], [0.6, 0.8], [0.4, 0.2], [0.8, 0.6]] 78 | Y_train = [1, 1, 0, 0] 79 | X_test = [[0.25, 0.5], [0.5, 0.25]] 80 | Y_test = [1, 0] 81 | X_pred = [[0.4, 0.5], [0.5, 0.4]] 82 | 83 | 84 | # Set the hyperparameters of the model and the training algorithm 85 | # Due to the workings of tensorflow, we have to define the batch size for every 86 | # mode of operation. The 'train_circuit' batch_size indicates the number of 87 | # samples used in every training step. 88 | # The 'eval' and 'infer' "batch_sizes" are the number of data points we plan 89 | # to feed into the score() and run_circuit() methods. 90 | hyperparams = {'circuit': circuit, 91 | 'task': 'supervised', 92 | 'loss': myloss, 93 | 'optimizer': 'SGD', 94 | 'init_learning_rate': 0.5, 95 | 'print_log': True} 96 | 97 | # Create a learner 98 | learner = CircuitLearner(hyperparams=hyperparams) 99 | 100 | # Train the learner 101 | learner.train_circuit(X=X_train, Y=Y_train, steps=steps) 102 | 103 | # Get the accuracy and loss for the test data 104 | test_score = learner.score_circuit(X=X_test, Y=Y_test, 105 | outputs_to_predictions=outputs_to_predictions) 106 | # The score_circuit() function returns a dictionary of different metrics. 107 | print("\nPossible scores to print: {}".format(list(test_score.keys()))) 108 | # We select the accuracy and loss. 109 | print("Accuracy on test set: ", test_score['accuracy']) 110 | print("Loss on test set: ", test_score['loss']) 111 | 112 | outcomes = learner.run_circuit(X=X_pred, outputs_to_predictions=outputs_to_predictions) 113 | 114 | # The run_circuit() function returns a dictionary of different outcomes. 115 | print("\nPossible outcomes to print: {}".format(list(outcomes.keys()))) 116 | # We select the predictions 117 | print("Predictions for new inputs: {}".format(outcomes['predictions'])) 118 | -------------------------------------------------------------------------------- /examples/tf/unsupervised_advanced_tf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # Copyright 2018 Xanadu Quantum Technologies Inc. 4 | 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """ 18 | .. currentmodule:: qmlt.examples.tf 19 | 20 | .. code-author:: Maria Schuld 21 | 22 | We revisit the example of a simple unsupervised learning task with the tf circuit learner and 23 | introduce layered circuit architectures. 24 | 25 | This time the circuit learns a quantum state where Fock 26 | states with zero photons in the first mode have a high measurement probablity. 27 | 28 | """ 29 | 30 | import strawberryfields as sf 31 | from strawberryfields.ops import * 32 | import numpy as np 33 | import tensorflow as tf 34 | from qmlt.tf import CircuitLearner 35 | from qmlt.tf.helpers import make_param 36 | from qmlt.helpers import sample_from_distribution 37 | 38 | 39 | # Number of layers 40 | depth = 5 41 | steps = 500 42 | 43 | 44 | def circuit(): 45 | 46 | # Create parameters for 'depth' number of layers. 47 | # Mark some of them to be regularized and some to be monitored. 48 | phi = make_param(name='phi', stdev=0.2, shape=[depth], regularize=False) 49 | theta = make_param(name='theta', stdev=0.2, shape=[depth], regularize=False) 50 | a = make_param(name='a', stdev=0.2, shape=[depth], regularize=True, monitor=True) 51 | rtheta = make_param(name='rtheta', stdev=0.2, shape=[depth], regularize=False, monitor=True) 52 | r = make_param(name='r', stdev=0.2, shape=[depth], regularize=True, monitor=True) 53 | kappa = make_param(name='kappa', stdev=0.2, shape=[depth], regularize=True, monitor=True) 54 | 55 | # Define a single layer of gates 56 | def layer(l): 57 | BSgate(phi[l], theta[l]) | (q[0], q[1]) 58 | Dgate(a[l]) | q[0] 59 | Rgate(rtheta[l]) | q[0] 60 | Sgate(r[l]) | q[0] 61 | Kgate(kappa[l]) | q[0] 62 | 63 | eng, q = sf.Engine(2) 64 | 65 | with eng: 66 | # Make depth layers 67 | for d in range(depth): 68 | layer(d) 69 | 70 | state = eng.run('tf', cutoff_dim=7, eval=False) 71 | circuit_output = state.all_fock_probs() 72 | 73 | return circuit_output 74 | 75 | 76 | def myloss(circuit_output, X): 77 | probs = tf.gather_nd(params=circuit_output, indices=X) 78 | prob_total = tf.reduce_sum(probs, axis=0) 79 | return -prob_total 80 | 81 | 82 | def myregularizer(regularized_params): 83 | return tf.nn.l2_loss(regularized_params) 84 | 85 | 86 | X_train = np.array([[0, 1], 87 | [0, 2], 88 | [0, 3], 89 | [0, 4]]) 90 | 91 | hyperparams = {'circuit': circuit, 92 | 'task': 'unsupervised', 93 | 'optimizer': 'SGD', 94 | 'init_learning_rate': 0.1, 95 | 'loss': myloss, 96 | 'regularizer': myregularizer, 97 | 'regularization_strength': 0.1 98 | } 99 | 100 | learner = CircuitLearner(hyperparams=hyperparams) 101 | 102 | learner.train_circuit(X=X_train, steps=steps) 103 | 104 | outcomes = learner.run_circuit() 105 | final_distribution = outcomes['outputs'] 106 | 107 | # Use a helper function to sample fock states from this state. 108 | # They should show a similar distribution to the training data 109 | for i in range(10): 110 | sample = sample_from_distribution(distribution=final_distribution) 111 | print("Fock state sample {}:{} \n".format(i, sample)) 112 | 113 | # Note: the learner really generalises. Sometimes (albeit rarely) it will 114 | # sample Fock state |0, 5> which it has never seen during training 115 | -------------------------------------------------------------------------------- /examples/tf/unsupervised_tf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # Copyright 2018 Xanadu Quantum Technologies Inc. 4 | 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """ 18 | .. currentmodule:: qmlt.examples.tf 19 | 20 | .. code-author:: Maria Schuld 21 | 22 | Example of a simple unsupervised learning task with the tf circuit learner. 23 | 24 | """ 25 | 26 | import strawberryfields as sf 27 | from strawberryfields.ops import * 28 | import numpy as np 29 | import tensorflow as tf 30 | from qmlt.tf import CircuitLearner 31 | from qmlt.tf.helpers import make_param 32 | from qmlt.helpers import sample_from_distribution 33 | 34 | 35 | steps = 100 36 | 37 | 38 | def circuit(): 39 | 40 | phi = make_param(name='phi', stdev=0.2, regularize=False) 41 | theta = make_param(name='theta', stdev=0.2, regularize=False) 42 | a = make_param(name='a', stdev=0.2, regularize=True, monitor=True) 43 | rtheta = make_param(name='rtheta', stdev=0.2, regularize=False, monitor=True) 44 | r = make_param(name='r', stdev=0.2, regularize=True, monitor=True) 45 | kappa = make_param(name='kappa', stdev=0.2, regularize=True, monitor=True) 46 | 47 | eng, q = sf.Engine(2) 48 | 49 | with eng: 50 | BSgate(phi, theta) | (q[0], q[1]) 51 | Dgate(a) | q[0] 52 | Rgate(rtheta) | q[0] 53 | Sgate(r) | q[0] 54 | Kgate(kappa) | q[0] 55 | 56 | state = eng.run('tf', cutoff_dim=7, eval=False) 57 | circuit_output = state.all_fock_probs() 58 | 59 | return circuit_output 60 | 61 | 62 | def myloss(circuit_output, X): 63 | probs = tf.gather_nd(params=circuit_output, indices=X) 64 | prob_total = tf.reduce_sum(probs, axis=0) 65 | return -prob_total 66 | 67 | 68 | def myregularizer(regularized_params): 69 | return tf.nn.l2_loss(regularized_params) 70 | 71 | 72 | X_train = np.array([[0, 1], 73 | [0, 2], 74 | [0, 3], 75 | [0, 4]]) 76 | 77 | hyperparams = {'circuit': circuit, 78 | 'task': 'unsupervised', 79 | 'optimizer': 'SGD', 80 | 'init_learning_rate': 0.1, 81 | 'loss': myloss, 82 | 'regularizer': myregularizer, 83 | 'regularization_strength': 0.1 84 | } 85 | 86 | learner = CircuitLearner(hyperparams=hyperparams) 87 | 88 | learner.train_circuit(X=X_train, steps=steps) 89 | 90 | outcomes = learner.run_circuit() 91 | final_distribution = outcomes['outputs'] 92 | 93 | # Use a helper function to sample fock states from this state. 94 | # They should show a similar distribution to the training data 95 | for i in range(10): 96 | sample = sample_from_distribution(distribution=final_distribution) 97 | print("Fock state sample {}:{} \n".format(i, sample)) 98 | 99 | # Print out the final circuit parameters 100 | learner.get_circuit_parameters(only_print=True) 101 | 102 | -------------------------------------------------------------------------------- /qmlt/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018 Xanadu Quantum Technologies Inc. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | """qmlt module""" 15 | from __future__ import unicode_literals 16 | from ._version import __version__ 17 | 18 | 19 | def version(): 20 | """ 21 | Get version number of the QMLT. 22 | 23 | Returns: 24 | str: The package version number 25 | """ 26 | return __version__ 27 | -------------------------------------------------------------------------------- /qmlt/_version.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018 Xanadu Quantum Technologies Inc.the set 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Version information. 16 | Version number (major.minor.patch[-label]) 17 | """ 18 | 19 | __version__ = '0.7.1' 20 | -------------------------------------------------------------------------------- /qmlt/helpers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # Copyright 2018 Xanadu Quantum Technologies Inc. 4 | 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """ 18 | Helpers 19 | ======================================================== 20 | 21 | **Module name:** :mod:`qmlt.helpers` 22 | 23 | .. currentmodule:: qmlt.helpers 24 | 25 | .. codeauthor:: Maria Schuld 26 | 27 | Collection of helpers to set up an experiment with either the numerical or tf 28 | circuit learner. 29 | 30 | Summary 31 | ------- 32 | 33 | .. autosummary:: 34 | sample_from_distribution 35 | 36 | Code details 37 | ------------ 38 | """ 39 | 40 | 41 | import numpy as np 42 | 43 | 44 | def sample_from_distribution(distribution): 45 | r""" 46 | Sample a Fock state from a nested probability distribution of Fock states. 47 | 48 | Args: 49 | distribution (ndarray): Nested array containing probabilities of Fock state. 50 | Fock state :math:`|i,j,k \rangle` is retrieved by ``distribution([i,j,k])``. 51 | Can be the result of :func:`state.all_fock_probs`. 52 | 53 | Return: List of photon numbers representing a Fock state. 54 | """ 55 | 56 | distribution = np.array(distribution) 57 | cutoff = distribution.shape[0] 58 | num_modes = len(distribution.shape) 59 | 60 | probs_flat = np.reshape(distribution, (-1)) 61 | indices_flat = np.arange(len(probs_flat)) 62 | indices = np.reshape(indices_flat, [cutoff] * num_modes) 63 | sample_index = np.random.choice(indices_flat, p=probs_flat / sum(probs_flat)) 64 | fock_state = np.asarray(np.where(indices == sample_index)).flatten() 65 | 66 | return fock_state 67 | -------------------------------------------------------------------------------- /qmlt/numerical/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # Copyright 2018 Xanadu Quantum Technologies Inc. 4 | 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """ 18 | Numerical Quantum Circuit Learner 19 | ======================================================== 20 | 21 | **Module name:** :mod:`qmlt.numerical` 22 | 23 | .. currentmodule:: qmlt.numerical 24 | 25 | .. codeauthor:: Maria Schuld 26 | 27 | This module contains a class to train models for machine learning and optimization based on variational quantum circuits. 28 | The optimization is executed by scipy's numerical optimisation library. The user defines a function that computes 29 | the outputs of the variational circuit, as well as the training objective, and specifies the model and training 30 | hyperparameters. 31 | 32 | There are three basic functionalities. The circuit can be trained, run with the current parameters, and scored. 33 | 34 | The numerical learner module has been designed for the training of continuous-variable circuits written in StrawberryFields or 35 | BlackBird (using any backend), but is in principle able to train any user-provided model coded in python. 36 | 37 | .. note:: 38 | Numerical differentiation is not robust, which means that some models fail to be trained. For example, the approximations 39 | of gradients for gradient-based methods are not precise enough to find the steepest descent in plateaus of the 40 | optimization landscape. This can sometimes be rectified by choosing good hyperparameters, but ultimately poses a limit 41 | to training quantum circuits with numerical methods. 42 | 43 | 44 | CircuitLearner class 45 | --------------------- 46 | 47 | .. currentmodule:: qmlt.numerical.CircuitLearner 48 | 49 | .. autosummary:: 50 | train_circuit 51 | run_circuit 52 | score_circuit 53 | get_circuit_parameters 54 | 55 | 56 | Helper methods 57 | -------------- 58 | 59 | .. currentmodule:: qmlt.numerical 60 | 61 | .. autosummary:: 62 | check 63 | check_X 64 | check_Y 65 | check_steps 66 | check_batch_size 67 | check_logs 68 | 69 | Code details 70 | ------------ 71 | """ 72 | 73 | from .learner import (CircuitLearner, 74 | _check as check, 75 | _check_X as check_X, 76 | _check_Y as check_Y, 77 | _check_steps as check_steps, 78 | _check_batch_size as check_batch_size, 79 | _check_logs as check_logs) 80 | 81 | __all__ = ['CircuitLearner', 'check', 'check_X', 'check_Y', 'check_steps', 'check_batch_size', 'check_logs'] 82 | -------------------------------------------------------------------------------- /qmlt/numerical/helpers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # Copyright 2018 Xanadu Quantum Technologies Inc. 4 | 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """ 18 | Helpers 19 | ======================================================== 20 | 21 | **Module name:** :mod:`qmlt.numerical.helpers` 22 | 23 | .. currentmodule:: qmlt.numerical.helpers 24 | 25 | .. codeauthor:: Maria Schuld 26 | 27 | Collection of helpers to set up an experiment with the numerical circuit learner. 28 | 29 | Summary 30 | ------- 31 | 32 | .. autosummary:: 33 | make_param 34 | 35 | Code details 36 | ------------ 37 | """ 38 | # pylint: disable=too-many-arguments 39 | import numpy as np 40 | 41 | 42 | def make_param(name=None, stdev=None, mean=0., interval=None, constant=None, 43 | regularize=False, monitor=False, seed=None): 44 | r"""Return a circuit parameter. 45 | 46 | Args: 47 | name (str): name of the variable 48 | stdev (float): If not None, initialise from normal distribution. 49 | mean (float): If stdev is not None, use this mean for normal 50 | distribution. 51 | interval (list of length 2): If stdev is None and interval is not None, 52 | initialise from random value sampled 53 | uniformly from this interval. 54 | constant (float): If stdev and interval are both None and constant 55 | is not None, use this as an initial value. 56 | If constant is also None, use 0 as an initial value (not recommended!). 57 | regularize (boolean): If true, regularize this parameter. 58 | monitor (boolean): If true, monitor this variable for plotting. 59 | 60 | Return: 61 | Dictionary: Dictionary representing a circuit parameter. 62 | """ 63 | 64 | if seed is not None: 65 | np.random.seed(seed) 66 | 67 | if stdev is not None: 68 | var = {'name': name, 69 | 'val': np.random.normal(loc=mean, scale=stdev), 70 | 'regul': regularize, 71 | 'monitor': monitor} 72 | 73 | elif interval is not None: 74 | var = {'name': name, 75 | 'val': interval[0]+np.random.random()*(interval[1]-interval[0]), 76 | 'regul': regularize, 77 | 'monitor': monitor} 78 | 79 | elif constant is not None: 80 | var = {'name': name, 81 | 'val': constant, 82 | 'regul': regularize, 83 | 'monitor': monitor} 84 | 85 | else: 86 | var = {'name': name, 87 | 'val': 0.1*np.random.random(), 88 | 'regul': regularize, 89 | 'monitor': monitor} 90 | return var 91 | -------------------------------------------------------------------------------- /qmlt/numerical/losses.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # Copyright 2018 Xanadu Quantum Technologies Inc. 4 | 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """ 18 | Losses 19 | ======================================================== 20 | 21 | **Module name:** :mod:`qmlt.numerical.losses` 22 | 23 | .. currentmodule:: qmlt.numerical.losses 24 | 25 | .. codeauthor:: Maria Schuld 26 | 27 | A collection of loss functions for numpy. 28 | 29 | Summary 30 | ------- 31 | 32 | .. autosummary:: 33 | trace_distance 34 | expectation 35 | square_loss 36 | _softmax 37 | cross_entropy_with_softmax 38 | 39 | Code details 40 | ------------ 41 | """ 42 | 43 | import numpy as np 44 | 45 | 46 | def trace_distance(rho, sigma): 47 | r"""Trace distance :math:`\frac{1}{2}\tr \{ \sqrt{ (\rho - \sigma)^2} \}` between quantum states :math:`\rho` and :math:`\sigma`. 48 | 49 | Args: 50 | rho (ndarray or list): 2-dimensional square matrix representing the state :math:`\rho`. 51 | sigma (ndarray or list): 2-dimensional square matrix of the same dimensions and dtype as rho, 52 | representing the state :math:`\sigma` 53 | 54 | Returns: 55 | float: Scalar trace distance. 56 | 57 | """ 58 | 59 | rho = np.array(rho) 60 | sigma = np.array(sigma) 61 | 62 | if rho.shape != sigma.shape: 63 | raise ValueError("Cannot compute the trace distance if inputs have" 64 | " different shapes {} and {}".format(rho.shape, sigma.shape)) 65 | if rho.ndim != 2: 66 | raise ValueError("Trace distance loss expects 2-d arrays representing density matrices.") 67 | 68 | diffs = rho - sigma 69 | eigvals = np.linalg.eigvals(diffs) 70 | return 0.5 * sum(np.absolute(eigvals)) 71 | 72 | 73 | def expectation(rho, operator): 74 | r""" Expectation value :math:`\tr\{ \rho O\}` of operator :math:`O` with respect to the quantum state :math:`\rho`. 75 | 76 | 77 | Args: 78 | rho (ndarray or list): 2-dimensional array representing the state :math:`\rho`. 79 | operator (ndarray or list): 2-dimensional array of the same dimensions and dtype as rho, 80 | representing the operator :math:`O` 81 | 82 | Returns: 83 | float: Scalar expectation value. 84 | 85 | """ 86 | 87 | rho = np.array(rho) 88 | operator = np.array(operator) 89 | 90 | if rho.shape != operator.shape: 91 | raise ValueError("Cannot compute expectation value if rho and operator have" 92 | " different shapes {} and {}".format(rho.shape, operator.shape)) 93 | if rho.ndim != 2: 94 | raise ValueError("Expectation loss expects a 2-d array representing a density matrix.") 95 | 96 | exp = np.trace(rho@operator) 97 | 98 | if np.imag(exp) > 1e-5: 99 | raise ValueError("Expectation value has a non-negligible imaginary contribution." 100 | "Something went wrong.") 101 | 102 | return exp 103 | 104 | 105 | def square_loss(outputs, targets): 106 | r"""Mean squared loss :math:`0.5 \sum\limits_{m=1}^M |y^m - t^m|^2` between outputs :math:`y^m` and 107 | targets :math:`t^m` for :math:`m = 1,...,M`. 108 | 109 | Args: 110 | outputs (ndarray or list): array of dimension M x 1 containing the 1-dimensional outputs. 111 | targets (ndarray or list): array of the same dimension and type as outputs, containing the targets. 112 | 113 | Returns: 114 | float: Scalar mean squared loss. 115 | 116 | """ 117 | 118 | outputs = np.array(outputs) 119 | targets = np.array(targets) 120 | 121 | if outputs.shape != targets.shape: 122 | raise ValueError("Cannot compute squared loss if outputs and targets have" 123 | " different shapes {} and {}".format(outputs.shape, targets.shape)) 124 | 125 | if outputs.ndim > 2: 126 | raise ValueError("Mean squared loss expects 1-d outputs, dimension of current outputs" 127 | " is {}.".format(outputs.ndim - 1)) 128 | 129 | diff = outputs - targets 130 | res = 0.5*sum(np.dot(d, d) for d in diff) 131 | return res 132 | 133 | 134 | def _softmax(logits): 135 | r"""Softmax function, turns a vector of real values into a vector of probabilities. 136 | 137 | Args: 138 | logits (ndarray 1-d): Real 1-d vector of model outputs 139 | 140 | Returns: 141 | ndarray: Vector of probabilities 142 | 143 | """ 144 | exps = np.exp(logits - np.max(logits)) 145 | return exps / np.sum(exps) 146 | 147 | 148 | def cross_entropy_with_softmax(outputs, targets): 149 | r""" 150 | Cross-entropy loss that measures the probability error in discrete classification tasks (with mutually exclusive classes). 151 | Useful for one-hot-encoded vectors. 152 | 153 | Args: 154 | outputs (ndarray): Real 2-dim array representing a batch of model outputs. Also called logits. 155 | targets (ndarray): Real 2-dim array representing a batch of target outputs. 156 | 157 | Return: 158 | float: Scalar loss. 159 | """ 160 | probs = [_softmax(outp) for outp in outputs] 161 | terms = np.array([y*np.log(p) for p, y in zip(probs, targets)]) 162 | loss = (-1)*np.sum(terms) 163 | return loss 164 | -------------------------------------------------------------------------------- /qmlt/numerical/regularizers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # Copyright 2018 Xanadu Quantum Technologies Inc. 4 | 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """ 18 | Regularizers 19 | ======================================================== 20 | 21 | **Module name:** :mod:`qmlt.numerical.regularizers` 22 | 23 | .. currentmodule:: qmlt.numerical.regularizers 24 | 25 | .. codeauthor:: Maria Schuld 26 | 27 | A collection of regularizers to facilitate experiments with the numerical circuit learner. 28 | 29 | Summary 30 | ------- 31 | 32 | .. autosummary:: 33 | l2 34 | l1 35 | 36 | 37 | Code details 38 | ------------ 39 | 40 | """ 41 | 42 | import numpy as np 43 | 44 | 45 | def l2(circuit_params): 46 | r"""L2 regulariser :math:`0.5 \sum_{i=1}^N w_i^2` for a vector :math:`w = (w_1,...,w_N)` of circuit parameters. 47 | 48 | Args: 49 | circuit_params (ndarray): 1-d array containing the values of the circuit parameters to regularize. 50 | 51 | Returns: 52 | float: Scalar l2 loss. 53 | 54 | """ 55 | circuit_params = np.array(circuit_params) 56 | 57 | if circuit_params.ndim > 1: 58 | raise ValueError("Regulariser expects a 1-dimensional array, got {} dimensions".format(circuit_params.ndim)) 59 | 60 | return 0.5*np.dot(circuit_params, circuit_params) 61 | 62 | 63 | def l1(circuit_params): 64 | r"""L1 regulariser :math:`\sum_{i=1}^N |w_i|` for a vector :math:`w = (w_1,...,w_N)` of circuit parameters. 65 | 66 | Args: 67 | circuit_params (ndarray): 1-d array containing the values of the circuit parameters to regularize. 68 | 69 | Returns: 70 | float: Scalar l1 loss. 71 | 72 | """ 73 | 74 | circuit_params = np.array(circuit_params) 75 | 76 | if circuit_params.ndim > 1: 77 | raise ValueError("Regulariser expects a 1-dimensional array, got {} dimensions".format(circuit_params.ndim)) 78 | 79 | return np.sum(np.absolute(circuit_params)) 80 | -------------------------------------------------------------------------------- /qmlt/tf/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # Copyright 2018 Xanadu Quantum Technologies Inc. 4 | 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """ 18 | TF Quantum Circuit Learner 19 | ======================================================== 20 | 21 | **Module name:** :mod:`qmlt.tf` 22 | 23 | .. currentmodule:: qmlt.tf 24 | 25 | .. codeauthor:: Maria Schuld 26 | 27 | This module contains a class to train models for machine learning and optimization based on variational quantum circuits. 28 | The class extends TensorFlow's ``tf.estimator`` class, and adapts it to unsupervised learning and optimization tasks. It 29 | hides the complexity of defining input functions, hooks and configurations. 30 | 31 | The user defines a function that computes the outputs of the variational circuit, as well as the training objective, 32 | and specifies the model and training hyperparameters. 33 | 34 | There are three basic functionalities. The circuit can be trained, run with the current parameters, and scored. 35 | 36 | The TensorFlow learner module has been designed for the training of continuous-variable circuits written in StrawberryFields or 37 | BlackBird using the 'tf' backend only, but is in principle able to train any user-provided model coded in tensorflow. 38 | 39 | .. note:: 40 | 41 | Contrary to the :mod:`numerical learner `, the TensorFlow learner doesn't contain built-in plotting functions. 42 | The recommended method of visualizing the learner parameters is by using `TensorBoard `_. 43 | 44 | CircuitLearner class 45 | --------------------- 46 | 47 | .. currentmodule:: qmlt.tf.CircuitLearner 48 | 49 | .. autosummary:: 50 | get_circuit_parameters 51 | 52 | 53 | Helper methods 54 | -------------- 55 | 56 | .. currentmodule:: qmlt.tf 57 | 58 | .. autosummary:: 59 | qcv_model_fn 60 | make_input_fn 61 | check 62 | check_X 63 | check_Y 64 | check_steps 65 | check_batch_size 66 | check_shuffle 67 | 68 | Code details 69 | ------------ 70 | """ 71 | 72 | from .learner import (CircuitLearner, 73 | _qcv_model_fn as qcv_model_fn, 74 | _check as check, 75 | _check_X as check_X, 76 | _check_Y as check_Y, 77 | _check_steps as check_steps, 78 | _check_batch_size as check_batch_size, 79 | _check_shuffle as check_shuffle, 80 | _make_input_fn as make_input_fn) 81 | 82 | __all__ = ['CircuitLearner', 'qcv_model_fn', 'make_input_fn', 'check', 'check_X', 'check_Y', 'check_steps', 'check_batch_size', 'check_shuffle'] 83 | -------------------------------------------------------------------------------- /qmlt/tf/helpers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # Copyright 2018 Xanadu Quantum Technologies Inc. 4 | 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | # pylint: disable=too-many-arguments,not-context-manager,too-many-branches 17 | """ 18 | Helpers 19 | ======================================================== 20 | 21 | **Module name:** :mod:`qmlt.tf.helpers` 22 | 23 | .. currentmodule:: qmlt.tf.helpers 24 | 25 | .. codeauthor:: Maria Schuld 26 | 27 | Collection of helpers to set up an experiment with the tensorflow circuit learner. 28 | 29 | Summary 30 | ------- 31 | 32 | .. autosummary:: 33 | make_param 34 | 35 | Code details 36 | -------------- 37 | """ 38 | 39 | from random import choice 40 | from string import ascii_letters, digits 41 | import tensorflow as tf 42 | 43 | 44 | def make_param(name=None, stdev=None, mean=0., interval=None, constant=None, shape=(), 45 | regularize=False, monitor=False, seed=None): 46 | r"""Return a tensorflow variable. 47 | 48 | Args: 49 | name (str): name of the variable 50 | stdev (float): If not None, initialise from normal distribution. 51 | mean (float): If stdev is not None, use this mean for normal distribution. Defaults to 0. 52 | interval (list of length 2): If stdev is None and interval is not None, initialise from random value sampled 53 | uniformly from this interval. 54 | constant (float): If stdev and interval are both None and constant is not None, use this as an initial value. 55 | If constant is also None, use 0 as an initial value (not recommended!). 56 | shape (tuple or list): Shape of variable tensor. Useful for layered architectures. 57 | regularize (boolean): If true, mark this parameter for regularization. 58 | monitor (boolean): Whether to add this variable to tensorboard summary. 59 | seed (int): Use this seed to generate random numbers. 60 | """ 61 | 62 | if name is None: 63 | name = ''.join(choice(ascii_letters + digits) for _ in range(5)) 64 | 65 | if stdev is not None: 66 | if regularize: 67 | with tf.variable_scope("regularized"): 68 | var = tf.get_variable(name, 69 | initializer=tf.random_normal(shape=shape, stddev=stdev, mean=mean, seed=seed), 70 | dtype=tf.float32) 71 | else: 72 | var = tf.get_variable(name, 73 | initializer=tf.random_normal(shape=shape, stddev=stdev, mean=mean, seed=seed), 74 | dtype=tf.float32) 75 | elif interval is not None: 76 | if regularize: 77 | with tf.variable_scope("regularized"): 78 | var = tf.get_variable(name, 79 | initializer=tf.random_uniform(shape=(), minval=interval[0], maxval=interval[1], 80 | seed=seed), 81 | dtype=tf.float32) 82 | else: 83 | var = tf.get_variable(name, 84 | initializer=tf.random_uniform(shape=(), minval=interval[0], maxval=interval[1], 85 | seed=seed), 86 | dtype=tf.float32) 87 | 88 | elif constant is not None: 89 | if regularize: 90 | with tf.variable_scope("regularized"): 91 | var = tf.get_variable(name, 92 | shape=shape, 93 | initializer=tf.constant_initializer(value=constant), 94 | dtype=tf.float32) 95 | else: 96 | var = tf.get_variable(name, 97 | shape=shape, 98 | initializer=tf.constant_initializer(value=constant), 99 | dtype=tf.float32) 100 | else: 101 | if regularize: 102 | with tf.variable_scope("regularized"): 103 | var = tf.get_variable(name, 104 | shape=shape, 105 | initializer=tf.constant_initializer(value=0.), 106 | dtype=tf.float32) 107 | 108 | else: 109 | var = tf.get_variable(name, 110 | shape=shape, 111 | initializer=tf.constant_initializer(value=0.), 112 | dtype=tf.float32) 113 | 114 | if monitor: 115 | if shape == (): 116 | tf.summary.scalar(name=name, tensor=var) 117 | else: 118 | var_flat = tf.reshape(var, [-1]) 119 | var_list = tf.unstack(var_flat, axis=0) 120 | for idx, v in enumerate(var_list): 121 | tf.summary.scalar(name=name+'_'+str(idx), tensor=v) 122 | 123 | return var 124 | -------------------------------------------------------------------------------- /qmlt/tf/losses.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # Copyright 2018 Xanadu Quantum Technologies Inc. 4 | 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """ 18 | Losses 19 | ======================================================== 20 | 21 | **Module name:** :mod:`qmlt.tf.losses` 22 | 23 | .. currentmodule:: qmlt.tf.losses 24 | 25 | .. codeauthor:: Maria Schuld 26 | 27 | A collection of loss functions for tensorflow that are specific to quantum machine learning and optimization. 28 | 29 | 30 | Summary 31 | ------- 32 | 33 | .. autosummary:: 34 | trace_distance 35 | expectation 36 | 37 | Code details 38 | ------------ 39 | """ 40 | 41 | 42 | import tensorflow as tf 43 | 44 | 45 | def trace_distance(rho, sigma): 46 | r""" Trace distance :math:`\frac{1}{2}\tr \{ \sqrt{ (\rho - \sigma})^2 \}` between quantum states :math:`\rho` and :math:`\sigma`. 47 | 48 | The inputs and outputs are tensors of dtype float, and all computations support automatic differentiation. 49 | 50 | Args: 51 | rho (tf.Tensor): 2-dimensional Hermitian matrix representing state :math:`\rho`. 52 | sigma (tf.Tensor): 2-dimensional Hermitian matrix of the same dimensions and dtype as rho, 53 | representing state :math:`\sigma`. 54 | 55 | Returns: 56 | tf.Tensor: Returns the scalar trace distance. 57 | """ 58 | 59 | if rho.shape != sigma.shape: 60 | raise ValueError("Cannot compute the trace distance if inputs have" 61 | " different shapes {} and {}".format(rho.shape, sigma.shape)) 62 | 63 | diff = rho - sigma 64 | eig = tf.self_adjoint_eigvals(diff) 65 | abs_eig = tf.abs(eig) 66 | return 0.5*tf.real(tf.reduce_sum(abs_eig)) 67 | 68 | 69 | def expectation(rho, operator): 70 | r""" Expectation value :math:`\tr\{ \rho O\}` of operator :math:`O` with respect to the quantum state :math:`\rho`. 71 | 72 | The inputs and outputs are tensors of dtype float, and all computations support automatic differentiation. 73 | 74 | 75 | Args: 76 | rho (tf.Tensor) : 2-dimensional Hermitian tensor representing state :math:`\rho`. 77 | operator (tf.Tensor): 2-dimensional Hermitian tensor of the same dimensions and dtype as rho. 78 | 79 | Returns: 80 | tf.Tensor: Returns the scalar expectation value. 81 | 82 | """ 83 | if rho.shape != operator.shape: 84 | raise ValueError("Cannot compute expectation value if rho and operator have" 85 | " different shapes {} and {}".format(rho.shape, operator.shape)) 86 | if len(rho.shape) != 2: 87 | raise ValueError("Expectation loss expects a 2-d array representing a density matrix.") 88 | 89 | exp = tf.real(tf.trace(tf.matmul(rho, operator))) 90 | return exp 91 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | matplotlib==2.1.2 2 | networkx==2.1 3 | numpy==1.14.0 4 | scikit-learn==0.19.1 5 | scipy==1.0.0 6 | StrawberryFields==0.7.3 7 | tensorflow==1.6.0 8 | tensorflow-tensorboard==0.1.8 9 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018 Xanadu Quantum Technologies Inc. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | #!/usr/bin/env python3 16 | import sys 17 | import os 18 | from setuptools import setup 19 | # from sphinx.setup_command import BuildDoc 20 | 21 | with open("qmlt/_version.py") as f: 22 | version = f.readlines()[-1].split()[-1].strip("\"'") 23 | 24 | # cmdclass = {'build_docs': BuildDoc} 25 | 26 | # add any major python requirements 27 | requirements = [ 28 | "scikit-learn>=0.19", 29 | "matplotlib>=2.0", 30 | "strawberryfields>=0.7.3" 31 | ] 32 | 33 | info = { 34 | 'name': 'qmlt', 35 | 'version': version, 36 | 'maintainer': 'Xanadu Inc.', 37 | 'maintainer_email': 'maria@xanadu.ai', 38 | 'url': 'http://xanadu.ai', 39 | 'license': 'LICENSE', 40 | # put submodules here 41 | 'packages': [ 42 | 'qmlt', 43 | 'qmlt.numerical', 44 | 'qmlt.tf' 45 | ], 46 | 'include_package_data': True, 47 | 'description': 'Machine learning and optimization of quantum optical circuits', 48 | 'long_description': open('README.rst').read(), 49 | 'provides': ["qmlt"], 50 | 'install_requires': requirements, 51 | 'command_options': { 52 | 'build_sphinx': { 53 | 'version': ('setup.py', version), 54 | 'release': ('setup.py', version)}} 55 | } 56 | 57 | classifiers = [ 58 | "Development Status :: 3 - Alpha", 59 | "Environment :: Console", 60 | "Intended Audience :: Science/Research", 61 | "License :: OSI Approved :: Apache Software License", 62 | "Natural Language :: English", 63 | "Operating System :: POSIX", 64 | "Operating System :: MacOS :: MacOS X", 65 | "Operating System :: POSIX :: Linux", 66 | "Operating System :: Microsoft :: Windows", 67 | "Programming Language :: Python", 68 | 'Programming Language :: Python :: 3', 69 | 'Programming Language :: Python :: 3.5', 70 | 'Programming Language :: Python :: 3.6', 71 | 'Programming Language :: Python :: 3 :: Only', 72 | "Topic :: Scientific/Engineering :: Physics" 73 | ] 74 | 75 | setup(classifiers=classifiers, **(info)) 76 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # Copyright 2018 Xanadu Quantum Technologies Inc. 4 | 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | -------------------------------------------------------------------------------- /tests/test_helpers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # Copyright 2018 Xanadu Quantum Technologies Inc. 4 | 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """ 18 | Unit tests for qmlt helpers 19 | ============================ 20 | 21 | .. codeauthor:: Maria Schuld 22 | 23 | """ 24 | 25 | import unittest 26 | import tensorflow as tf 27 | import numpy as np 28 | from qmlt.helpers import sample_from_distribution 29 | from qmlt.numerical.helpers import make_param as make_param_num 30 | from qmlt.tf.helpers import make_param as make_param_tf 31 | 32 | 33 | class BaseHelpersTest(unittest.TestCase): 34 | """ 35 | Baseclass for helper tests. 36 | """ 37 | 38 | def setUp(self): 39 | self.seed = 1 40 | 41 | def assertAlmostEqual(self, one, two, msg=None, delta=1e-6): 42 | """ 43 | Assert that ``one`` almost equal to ``two``. Default threshold is 1e-6. 44 | """ 45 | if one == two: 46 | return 47 | if np.abs(one - two) <= delta: 48 | return 49 | standardMsg = 'The values differ more than threshold delta = {}'.format(delta) 50 | msg = self._formatMessage(msg, standardMsg) 51 | raise self.failureException(msg) 52 | 53 | def assertAlmostEqualArray(self, one_arr, two_arr, msg=None, delta=1e-6): 54 | """ 55 | Assert that the elements in 1-d array ``one`` are almost equal to those in 1-d array ``two``. 56 | Default threshold is 1e-6. 57 | """ 58 | if np.allclose(one_arr, two_arr, atol=delta): 59 | return 60 | standardMsg = 'The values differ more than threshold delta = {}'.format(delta) 61 | msg = self._formatMessage(msg, standardMsg) 62 | raise self.failureException(msg) 63 | 64 | def assertDictHasKey(self, dict, key, msg=None): 65 | """ 66 | Assert that dict has the key. 67 | """ 68 | if key in dict: 69 | return 70 | standardMsg = 'The key {} is not in the dictionary'.format(key) 71 | msg = self._formatMessage(msg, standardMsg) 72 | raise self.failureException(msg) 73 | 74 | def assertEquals(self, one, two, msg=None): 75 | """ 76 | Assert that one == two. Compares lists, tuples and strings. 77 | """ 78 | if one == two: 79 | return 80 | standardMsg = 'The strings {} and {} are not equal'.format(one, two) 81 | msg = self._formatMessage(msg, standardMsg) 82 | raise self.failureException(msg) 83 | 84 | 85 | class TestMakeParamsNum(BaseHelpersTest): 86 | """ 87 | Tests that the numeric make_params helper makes valid parameters. 88 | """ 89 | 90 | def setUp(self): 91 | super().setUp() 92 | self.inp = 0.5 93 | self.interval = [-1, 1] 94 | 95 | def test_num_has_all_fields(self): 96 | p = make_param_num(constant=self.inp) 97 | self.assertDictHasKey(p, 'name') 98 | self.assertDictHasKey(p, 'val') 99 | self.assertDictHasKey(p, 'regul') 100 | self.assertDictHasKey(p, 'monitor') 101 | 102 | def test_num_make_constant_param(self): 103 | p = make_param_num(constant=self.inp) 104 | self.assertAlmostEqual(p['val'], self.inp) 105 | 106 | def test_num_make_normal_param(self): 107 | p = make_param_num(stdev=self.inp, seed=self.seed) 108 | self.assertAlmostEqual(p['val'], 0.812172681831, delta=0.0001) 109 | 110 | def test_num_make_interval_param(self): 111 | p = make_param_num(interval=self.interval, seed=self.seed) 112 | self.assertAlmostEqual(p['val'], -0.16595599059, delta=0.0001) 113 | 114 | def test_num_make_blank_param(self): 115 | p = make_param_num(seed=self.seed) 116 | self.assertAlmostEqual(p['val'], 0.0417022004702, delta=0.0001) 117 | 118 | 119 | class TestMakeParamsTf(BaseHelpersTest): 120 | """ 121 | Tests that the tensorflow make_params helper makes valid parameters. 122 | """ 123 | 124 | def setUp(self): 125 | super().setUp() 126 | self.inp = 0.5 127 | self.interval = [-1, 1] 128 | self.shape = (1, 2) 129 | self.sess = tf.Session() 130 | 131 | def test_tf_make_constant_param(self): 132 | p = make_param_tf(constant=self.inp) 133 | self.sess.run(tf.global_variables_initializer()) 134 | p_res = self.sess.run(p) 135 | self.assertAlmostEqual(p_res, self.inp) 136 | 137 | def test_tf_make_normal_param(self): 138 | p = make_param_tf(stdev=self.inp, seed=self.seed) 139 | self.sess.run(tf.global_variables_initializer()) 140 | p_res = self.sess.run(p) 141 | self.assertAlmostEqual(p_res, -0.4056591, delta=0.0001) 142 | 143 | def test_tf_make_interval_param(self): 144 | p = make_param_tf(interval=self.interval, seed=self.seed) 145 | self.sess.run(tf.global_variables_initializer()) 146 | p_res = self.sess.run(p) 147 | self.assertAlmostEqual(p_res, -0.5219252, delta=0.0001) 148 | 149 | def test_tf_regul_param_name(self): 150 | p = make_param_tf(name='param', regularize=True) 151 | self.assertEquals(p.name, 'regularized/param:0') 152 | 153 | def test_tf_regul_constant_param_name(self): 154 | p = make_param_tf(name='param1', constant=self.inp, regularize=True) 155 | self.assertEquals(p.name, 'regularized/param1:0') 156 | 157 | def test_tf_regul_normal_param_name(self): 158 | p = make_param_tf(name='param2', stdev=self.inp, regularize=True) 159 | self.assertEquals(p.name, 'regularized/param2:0') 160 | 161 | def test_tf_regul_interval_param_name(self): 162 | p = make_param_tf(name='param3', interval=self.interval, regularize=True) 163 | self.assertEquals(p.name, 'regularized/param3:0') 164 | 165 | def test_tf_constant_monitored_param(self): 166 | p = make_param_tf(constant=self.inp, monitor=True) 167 | self.sess.run(tf.global_variables_initializer()) 168 | p_res = self.sess.run(p) 169 | self.assertAlmostEqual(p_res, self.inp) 170 | 171 | def test_tf_check_shape_deep_monitored_params(self): 172 | p = make_param_tf(constant=self.inp, shape=self.shape, monitor=True) 173 | self.sess.run(tf.global_variables_initializer()) 174 | self.assertEqual(p.shape, self.shape) 175 | 176 | def test_tf_check_shape_deep_params(self): 177 | p = make_param_tf(shape=self.shape) 178 | self.sess.run(tf.global_variables_initializer()) 179 | self.assertEqual(p.shape, self.shape) 180 | 181 | class TestSampling(BaseHelpersTest): 182 | """ 183 | Tests that the sampling helper returns a sample from a distribution. 184 | """ 185 | 186 | def setUp(self): 187 | super().setUp() 188 | self.distribution = np.array([[0., 1.], [0., 0.]]) 189 | 190 | def test_samplefromdistr_returns_sample(self): 191 | desired_result = np.array([0, 1]) 192 | self.assertAlmostEqualArray(sample_from_distribution(self.distribution), desired_result) 193 | 194 | 195 | if __name__ == "__main__": 196 | 197 | print('Testing helpers of the QMLT app.') 198 | 199 | # run the tests in this file 200 | suite = unittest.TestSuite() 201 | for t in [TestMakeParamsNum, TestMakeParamsTf, TestSampling]: 202 | ttt = unittest.TestLoader().loadTestsFromTestCase(t) 203 | suite.addTests(ttt) 204 | 205 | unittest.TextTestRunner().run(suite) 206 | 207 | -------------------------------------------------------------------------------- /tests/test_losses.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # Copyright 2018 Xanadu Quantum Technologies Inc. 4 | 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """ 18 | Unit tests for qmlt losses and regularization 19 | ======================================================== 20 | 21 | .. codeauthor:: Maria Schuld 22 | 23 | """ 24 | 25 | import unittest 26 | import tensorflow as tf 27 | import numpy as np 28 | 29 | 30 | from qmlt.numerical.losses import (square_loss as _square_loss, 31 | expectation as _expectation, 32 | trace_distance as _trace_distance, 33 | cross_entropy_with_softmax as _cross_ent) 34 | 35 | from qmlt.numerical.regularizers import l2 as _l2_regul 36 | from qmlt.numerical.regularizers import l1 as _l1_regul 37 | 38 | from qmlt.tf.losses import (expectation as _tf_expectation, 39 | trace_distance as _tf_trace_distance) 40 | 41 | 42 | class BaseCostHelpersTest(unittest.TestCase): 43 | """ 44 | Baseclass for loss tests. 45 | Creates some random inputs. 46 | """ 47 | 48 | def setUp(self, seed, shape): 49 | if not seed is None: 50 | np.random.seed(seed) 51 | self.input1_arr = np.random.random(shape) 52 | self.input2_arr = np.random.random(shape) 53 | self.input1_batch_arr = np.array([np.random.random(shape) for i in range(3)]) 54 | self.input2_batch_arr = np.array([np.random.random(shape) for i in range(3)]) 55 | self.input1_batch_list = [np.random.random(shape) for i in range(3)] 56 | self.input2_batch_list = [np.random.random(shape) for i in range(3)] 57 | 58 | def assertIsScalar(self, z, msg=None): 59 | """ Check if z is a scalar. """ 60 | if np.isscalar(z): 61 | return 62 | standardMsg = '{} is not a scalar.'.format(z) 63 | msg = self._formatMessage(msg, standardMsg) 64 | raise self.failureException(msg) 65 | 66 | def assertIsTfScalar(self, z, msg=None): 67 | """ Check if z is a scalar. """ 68 | if z.get_shape() == (): 69 | return 70 | standardMsg = '{} is not a scalar Tensor.'.format(z) 71 | msg = self._formatMessage(msg, standardMsg) 72 | raise self.failureException(msg) 73 | 74 | 75 | class TestRegularizer(BaseCostHelpersTest): 76 | """ 77 | Tests for regularizers that take a 1-d list, or array of scalars. 78 | """ 79 | 80 | def setUp(self): 81 | super().setUp(seed=1, shape=()) 82 | 83 | def test_l2regul_returns_scalar(self): 84 | self.assertIsScalar(_l2_regul(self.input1_batch_list)) 85 | self.assertIsScalar(_l2_regul(self.input1_batch_arr)) 86 | 87 | def test_l2regul_return_value(self): 88 | inpt = [1., 2., -3.] 89 | self.assertAlmostEqual(_l2_regul(inpt), 7.) 90 | 91 | def test_l1regul_returns_scalar(self): 92 | self.assertIsScalar(_l1_regul(self.input1_batch_list)) 93 | self.assertIsScalar(_l1_regul(self.input1_batch_arr)) 94 | 95 | def test_l1regul_return_value(self): 96 | inpt = [1., 2., -3.] 97 | self.assertAlmostEqual(_l1_regul(inpt), 6.) 98 | 99 | def test_l2regul_throws_exception(self): 100 | twodarr = np.array([[1., 0.], [0., 1.]]) 101 | with self.assertRaises(ValueError): 102 | _l2_regul(twodarr) 103 | 104 | def test_l1regul_throws_exception(self): 105 | twodarr = np.array([[1., 0.], [0., 1.]]) 106 | with self.assertRaises(ValueError): 107 | _l1_regul(twodarr) 108 | 109 | 110 | class TestLosses(BaseCostHelpersTest): 111 | """ 112 | Tests for functions that compute the similarity of 1-d outputs and targets in a batch. 113 | """ 114 | 115 | def setUp(self): 116 | super().setUp(seed=1, shape=(2,)) 117 | 118 | def test_meansquare_returns_scalar(self): 119 | self.assertIsScalar(_square_loss(self.input1_batch_list, self.input2_batch_list)) 120 | self.assertIsScalar(_square_loss(self.input1_batch_arr, self.input2_batch_arr)) 121 | 122 | def test_meansquare_throws_exception(self): 123 | threedarr = np.array([[[0., 1.], [1., 2.]], [[0., 1.], [1., 2.]]]) 124 | twodarr = np.array([[1., 0.], [0., 1.]]) 125 | with self.assertRaises(ValueError): 126 | _square_loss(threedarr, twodarr) 127 | with self.assertRaises(ValueError): 128 | _square_loss(threedarr, threedarr) 129 | 130 | def test_crossent_returns_scalar(self): 131 | self.assertIsScalar(_cross_ent(self.input1_batch_arr, self.input2_batch_arr)) 132 | 133 | 134 | class TestQuantumStateMeasures(BaseCostHelpersTest): 135 | """ 136 | Tests for functions that compute distance or expectations with respect to 2-d density matrices. 137 | """ 138 | 139 | def setUp(self): 140 | super().setUp(seed=1, shape=(2, 2)) 141 | 142 | def test_expectation_returns_scalar(self): 143 | self.assertIsScalar(_expectation(self.input1_arr, self.input2_arr)) 144 | 145 | def test_tf_expectation_returns_scalar(self): 146 | input1_arr = tf.convert_to_tensor(self.input1_arr) 147 | input2_arr = tf.convert_to_tensor(self.input2_arr) 148 | self.assertIsTfScalar(_tf_expectation(input1_arr, input2_arr)) 149 | 150 | def test_tracedist_returns_scalar(self): 151 | self.assertIsScalar(_trace_distance(self.input1_arr, self.input2_arr)) 152 | 153 | def test_tf_tracedist_returns_scalar(self): 154 | input1_arr = tf.convert_to_tensor(self.input1_arr) 155 | input2_arr = tf.convert_to_tensor(self.input2_arr) 156 | self.assertIsTfScalar(_tf_trace_distance(input1_arr, input2_arr)) 157 | 158 | def test_tracedist_for_same_inputs_is_zero(self): 159 | self.assertAlmostEqual(_trace_distance(self.input1_arr, self.input1_arr), 0.) 160 | 161 | def test_tf_tracedist_for_same_inputs_is_zero(self): 162 | input1_arr = tf.convert_to_tensor(self.input1_arr) 163 | with tf.Session() as sess: 164 | res = sess.run(_tf_trace_distance(input1_arr, input1_arr)) 165 | self.assertAlmostEqual(res, 0.) 166 | 167 | def test_tracedist_is_nonnegative(self): 168 | self.assertGreaterEqual(_trace_distance(self.input1_arr, self.input2_arr), 0.) 169 | 170 | def test_tf_tracedist_is_nonnegative(self): 171 | input1_arr = tf.convert_to_tensor(self.input1_arr) 172 | input2_arr = tf.convert_to_tensor(self.input2_arr) 173 | with tf.Session() as sess: 174 | res = sess.run(_tf_trace_distance(input1_arr, input2_arr)) 175 | self.assertGreaterEqual(res, 0.) 176 | 177 | def test_tf_tracedist_throws_exception(self): 178 | onedtens = tf.convert_to_tensor([0., 1.]) 179 | twodtens = tf.convert_to_tensor([[1., 0.], [0., 1.]]) 180 | with self.assertRaises(ValueError): 181 | _tf_trace_distance(onedtens, twodtens) 182 | 183 | def test_expectation_returns_eigenvalue(self): 184 | mat = np.zeros((4, 4)) 185 | mat[0, 0] = 1 186 | diag_input1 = mat 187 | diag_input2 = np.diag([4., 3., 2., 1.]) 188 | self.assertAlmostEqual(_expectation(diag_input1, diag_input2), 4.) 189 | 190 | def test_tf_expectation_returns_eigenvalue(self): 191 | mat = np.zeros((4, 4)) 192 | mat[0, 0] = 1 193 | diag_input1 = tf.convert_to_tensor(np.array(mat)) 194 | diag_input2 = tf.convert_to_tensor(np.array(np.diag([4., 3., 2., 1.]))) 195 | with tf.Session() as sess: 196 | res = sess.run(_tf_expectation(diag_input1, diag_input2)) 197 | self.assertAlmostEqual(res, 4.) 198 | 199 | def test_tf_expectation_throws_exception(self): 200 | onedtens = tf.convert_to_tensor([0., 1.]) 201 | twodtens = tf.convert_to_tensor([[1., 0.], [0., 1.]]) 202 | with self.assertRaises(ValueError): 203 | _tf_expectation(onedtens, twodtens) 204 | with self.assertRaises(ValueError): 205 | _tf_expectation(onedtens, onedtens) 206 | 207 | def test_expectation_throws_exception(self): 208 | onedarr = np.array([0., 1.]) 209 | twodarr = np.array([[1., 0.], [0., 1.]]) 210 | with self.assertRaises(ValueError): 211 | _expectation(onedarr, twodarr) 212 | with self.assertRaises(ValueError): 213 | _expectation(onedarr, onedarr) 214 | 215 | def test_tracedist_throws_exception(self): 216 | onedarr = np.array([0., 1.]) 217 | twodarr = np.array([[1., 0.], [0., 1.]]) 218 | with self.assertRaises(ValueError): 219 | _trace_distance(onedarr, twodarr) 220 | with self.assertRaises(ValueError): 221 | _trace_distance(onedarr, onedarr) 222 | 223 | 224 | if __name__ == "__main__": 225 | 226 | print('Testing losses of the QMLT app.') 227 | 228 | # run the tests in this file 229 | suite = unittest.TestSuite() 230 | for t in [TestRegularizer, TestLosses, TestQuantumStateMeasures]: 231 | ttt = unittest.TestLoader().loadTestsFromTestCase(t) 232 | suite.addTests(ttt) 233 | 234 | unittest.TextTestRunner().run(suite) 235 | 236 | -------------------------------------------------------------------------------- /tests/test_plots.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # Copyright 2018 Xanadu Quantum Technologies Inc. 4 | 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """ 18 | Unit tests for qmlt plots 19 | ======================================================== 20 | 21 | .. codeauthor:: Josh Izaac 22 | 23 | """ 24 | import sys 25 | import os 26 | import unittest 27 | import importlib 28 | 29 | import numpy as np 30 | 31 | import matplotlib as mpl 32 | if os.environ.get('DISPLAY', '') == '': 33 | print('no display found. Using non-interactive Agg backend') 34 | mpl.use('Agg') 35 | import matplotlib.pyplot as plt 36 | 37 | import tensorflow as tf 38 | 39 | from qmlt.numerical import plot 40 | 41 | 42 | class TestSquarish(unittest.TestCase): 43 | 44 | def test_1_plot(self): 45 | res = plot._squareish(1) 46 | self.assertEqual(res, (1, 1)) 47 | 48 | def test_2_plots(self): 49 | res = plot._squareish(2) 50 | self.assertEqual(res, (2, 1)) 51 | 52 | def test_3_plots(self): 53 | res = plot._squareish(3) 54 | self.assertEqual(res, (3, 1)) 55 | 56 | def test_4_plots(self): 57 | res = plot._squareish(4) 58 | self.assertEqual(res, (2, 2)) 59 | 60 | def test_5_plots(self): 61 | res = plot._squareish(5) 62 | self.assertEqual(res, (3, 2)) 63 | 64 | def test_6_plots(self): 65 | res = plot._squareish(6) 66 | self.assertEqual(res, (3, 2)) 67 | 68 | def test_7_plots(self): 69 | res = plot._squareish(7) 70 | self.assertEqual(res, (3, 3)) 71 | 72 | def test_13_plots(self): 73 | res = plot._squareish(13) 74 | self.assertEqual(res, (3, 5)) 75 | 76 | 77 | class TestPlot(unittest.TestCase): 78 | 79 | def test_no_axes(self): 80 | fig, ax = plt.subplots(1, 1) 81 | x = np.arange(0, 1, 0.1) 82 | y = np.sin(x) 83 | res = plot._plot(x, y) 84 | x_plot, y_plot = res.lines[0].get_xydata().T 85 | self.assertTrue(np.all(x == x_plot)) 86 | self.assertTrue(np.all(y == y_plot)) 87 | 88 | 89 | def test_axes(self): 90 | fig, ax = plt.subplots(1, 1) 91 | x = np.arange(0, 1, 0.1) 92 | y = np.sin(x) 93 | res = plot._plot(x, y, ax) 94 | x_plot, y_plot = ax.lines[0].get_xydata().T 95 | self.assertTrue(np.all(x == x_plot)) 96 | self.assertTrue(np.all(y == y_plot)) 97 | 98 | def test_xlabel(self): 99 | fig, ax = plt.subplots(1, 1) 100 | x = np.arange(0, 1, 0.1) 101 | y = np.sin(x) 102 | res = plot._plot(x, y, ax, xlabel='Test') 103 | x_label = res.xaxis.get_label().get_text() 104 | self.assertEqual('Test', x_label) 105 | 106 | def test_title(self): 107 | fig, ax = plt.subplots(1, 1) 108 | x = np.arange(0, 1, 0.1) 109 | y = np.sin(x) 110 | res = plot._plot(x, y, ax, ylabel='Test') 111 | y_label = res.get_title() 112 | self.assertEqual('Test', y_label) 113 | 114 | 115 | class TestMatplotlibImport(unittest.TestCase): 116 | 117 | def test_import_error(self): 118 | with self.assertRaisesRegex(ImportError, 'To use the plotting'): 119 | del sys.modules['matplotlib'] 120 | del sys.modules['matplotlib.pyplot'] 121 | importlib.reload(plot) 122 | 123 | if __name__ == "__main__": 124 | # run the tests in this file 125 | suite = unittest.TestSuite() 126 | for t in [TestSquarish, TestPlot, TestMatplotlibImport]: 127 | ttt = unittest.TestLoader().loadTestsFromTestCase(t) 128 | suite.addTests(ttt) 129 | 130 | unittest.TextTestRunner().run(suite) 131 | 132 | --------------------------------------------------------------------------------