Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds Fourier coefficient calculation module #1160

Merged
merged 129 commits into from
May 27, 2021
Merged
Show file tree
Hide file tree
Changes from 65 commits
Commits
Show all changes
129 commits
Select commit Hold shift + click to select a range
0111e13
backup
mariaschuld Nov 3, 2020
97d4242
Merge branch 'master' into fourier_spectrum
Dec 11, 2020
028f178
Merge in main branch.
Mar 10, 2021
25dd3a4
Add fourier module.
Mar 17, 2021
6c51f4e
Move format_nvec to utils.
Mar 17, 2021
11e6d96
Try adding module to docs.
Mar 18, 2021
24755d1
Merge branch 'master' into fourier_spectrum
Mar 18, 2021
8429c33
Fix some documentation and get it to render in TOC.
Mar 18, 2021
fa61e00
Unroll gates into Pauli rotations to compute spectra.
Mar 18, 2021
6ef1316
Merge branch 'master' into fourier_spectrum
Mar 24, 2021
266bc59
Add Fourier module to init after merge.
Mar 24, 2021
5fed522
Allow is_input flag to persist after operations on the array.
Mar 24, 2021
883d76f
Fix collection of parameters after unrolling gates.
Mar 24, 2021
2e26621
Start adding tests for spectra calculation.
Mar 24, 2021
4cb28d8
Merge branch 'master' into fourier_spectrum
mariaschuld Mar 29, 2021
0852c23
Add custom decomposition for CRot.
Mar 30, 2021
2c1e79b
First crack at low pass filter.
Mar 31, 2021
4fef3e4
Finish anti-aliasing functions.
Mar 31, 2021
88d8e26
Merge branch 'master' into fourier_spectrum
glassnotes Mar 31, 2021
7498e33
Add threshold frequency.
Mar 31, 2021
cb01c5c
Small changes to formatting.
Mar 31, 2021
efa3109
Merge branch 'fourier_spectrum' of https://github.com/PennyLaneAI/pen…
Mar 31, 2021
ec47232
Fix init file.
Mar 31, 2021
8355dc8
Black tensor file.
Mar 31, 2021
4086e50
Add more tests for coefficients.
Apr 1, 2021
f1fef40
Add more tests for coefficients.
Apr 1, 2021
7a4b8f0
Fix incorrect result in test.
Apr 1, 2021
e18b925
Add simple test for anti-aliasing results.
Apr 1, 2021
205735c
Remove spectra function from test file. Add simple test for coefficie…
Apr 1, 2021
0dcdcd0
Spectrum qnode transform (#1184)
mariaschuld Apr 1, 2021
0a0f57f
Remove custom decompositions.
Apr 1, 2021
42fbf93
Remove is_input.
Apr 1, 2021
bc1cb7a
Remove last remnant of is_input.
Apr 1, 2021
bc802d5
Re-add forgotten import.
Apr 1, 2021
5d3ad54
Lint and black.
Apr 1, 2021
2dbe1a8
Tweak docs.
Apr 1, 2021
5045ec1
Run black.
Apr 1, 2021
e0adf8b
Extended module documentation. Remove default anti-aliasing.
Apr 5, 2021
2be1267
Remove visualization modules from current PR.
Apr 8, 2021
1ba1fce
Remove remaining components of visualization.
Apr 8, 2021
3b4da13
Remove utility functions for visualizations.
Apr 8, 2021
c911693
Merge branch 'master' into fourier_spectrum
Apr 8, 2021
d054cc2
Fix aliasing test.
Apr 8, 2021
e674b0a
Update aliasing docstring.
Apr 8, 2021
80e58de
Improve documentation in both functions and rst file.
Apr 8, 2021
19714e7
Merge branch 'master' into fourier_spectrum
glassnotes Apr 9, 2021
4e4ed8a
Fix headings in docs.
Apr 9, 2021
9f63db8
Merge branch 'master' into fourier_spectrum
mariaschuld Apr 13, 2021
62e6a01
Adds Fourier coefficient visualization tools to fourier module (#1198)
glassnotes Apr 14, 2021
a24d251
Merge branch 'master' into fourier_spectrum
glassnotes Apr 14, 2021
e370809
Remove spectrum function from Fourier module (#1217)
mariaschuld Apr 15, 2021
54bc263
Merge branch 'master' into fourier_spectrum
Apr 20, 2021
67cd38a
Merge branch 'master' into fourier_spectrum
glassnotes May 18, 2021
b332221
Merge branch 'master' into fourier_spectrum
co9olguy May 19, 2021
3de4307
Update doc/code/qml_fourier.rst
mariaschuld May 20, 2021
dc5fa7a
Update doc/code/qml_fourier.rst
mariaschuld May 20, 2021
a53613b
Merge branch 'master' into fourier_spectrum
mariaschuld May 20, 2021
c9b223f
Apply suggestions from code review
glassnotes May 20, 2021
191fcd8
Apply suggestions from code review
glassnotes May 20, 2021
4af9f2e
Move partial import. Change sum to series.
May 20, 2021
00b07f4
Rename fourier_coefficients to coefficients.
May 20, 2021
7f7088e
Replace | with \vert.
May 20, 2021
cec1acb
Specify 1D function inputs.
May 20, 2021
182d3ac
Fix observables in docstrings. Add details to coefficients docstring.
May 20, 2021
3913c6f
Move major docstring to __init__.py
May 20, 2021
421a885
Merge branch 'master' into fourier_spectrum
glassnotes May 20, 2021
ae20b03
Shorten names of all plotting functions.
May 20, 2021
d597b0d
Update plotting names in test. Run black.
May 20, 2021
9d78989
Remove graphic and docstring details on 2D plotting function.
May 20, 2021
b6ac07a
Improvements to main visualization docstring.
May 20, 2021
e2be80c
Add proper docstrings and graphics to all visualization functions.
May 20, 2021
94cc3b1
Remove function visualization methods.
May 20, 2021
e96cb3d
Add aliasing example to coefficients docstring.
May 20, 2021
37639fa
Move matplotlib import warning to visualization module.
May 20, 2021
e5dc33c
Remove unnecessary import.
May 20, 2021
f85202b
Merge branch 'master' into fourier_spectrum
glassnotes May 20, 2021
0f0696c
Merge branch 'master' into fourier_spectrum
glassnotes May 21, 2021
26bb397
Remove is_input remnant of spectrum function.
May 21, 2021
4dd6e85
increase coverage and move functions to top of module docstring
mariaschuld May 25, 2021
7fbeea1
Merge branch 'master' into fourier_spectrum
mariaschuld May 25, 2021
a8ac502
solve codefactor issues and black
mariaschuld May 25, 2021
da9e607
Merge branch 'fourier_spectrum' of github.com:PennyLaneAI/pennylane i…
mariaschuld May 25, 2021
e1695b6
change CHANGELOG
mariaschuld May 25, 2021
978953d
black again
mariaschuld May 25, 2021
58e7b23
didn't know we also black tests now
mariaschuld May 25, 2021
f86f5cc
fix formatting of docstrings
mariaschuld May 25, 2021
88005e3
fix issues, tests are now running (2 still failing)
mariaschuld May 25, 2021
2e8c512
fix header levers sphinx
mariaschuld May 25, 2021
00a5666
add matplotlib to requirements
mariaschuld May 25, 2021
904ab07
move module docstring to docs rst file
mariaschuld May 25, 2021
63d5409
Add valid/invalid radial axes to tests.
May 25, 2021
fbfd0fe
fix last test
mariaschuld May 25, 2021
0a5770b
polished docstrings
mariaschuld May 25, 2021
9bc5b06
Add checks for non-polar axes passed to radial_box.
May 25, 2021
dbd2482
Run black.
May 25, 2021
e0ff851
Update .github/CHANGELOG.md
glassnotes May 25, 2021
b79b380
Make links clickable in the docs.
May 25, 2021
d81800e
Merge branch 'fourier_spectrum' of https://github.com/PennyLaneAI/pen…
May 25, 2021
c858c56
add tests to improve coverage
mariaschuld May 25, 2021
a5debd2
black
mariaschuld May 26, 2021
ab4cfa5
rename utils test file
mariaschuld May 26, 2021
31d3522
delete unused imports
mariaschuld May 26, 2021
d8e1229
one more test and some polishing
mariaschuld May 26, 2021
c5a0d3b
Apply suggestions from code review
glassnotes May 26, 2021
ef1fb36
Fix module docstring so that function links render.
May 26, 2021
8261ca3
Remove notes from module docs and move to coefficients.
May 26, 2021
ffc0589
Update matplotlib import error messages.
May 26, 2021
4305e98
Add interface tests for TF/torch.
May 26, 2021
b5b70d9
turn warning into exception and fix image link(hopefully)
mariaschuld May 26, 2021
1e7de22
fix merge confilcts
mariaschuld May 26, 2021
2a6ef9e
Update .github/CHANGELOG.md
mariaschuld May 26, 2021
4455864
back to using automodapi
mariaschuld May 26, 2021
267745d
Merge branch 'fourier_spectrum' of github.com:PennyLaneAI/pennylane i…
mariaschuld May 26, 2021
ebf4acf
Add test for JAX interface.
May 26, 2021
d52471f
Merge branch 'fourier_spectrum' of https://github.com/PennyLaneAI/pen…
May 26, 2021
13f0ada
fix sphinx
mariaschuld May 26, 2021
db1a6db
add link to changelog
mariaschuld May 26, 2021
30b606f
Merge branch 'fourier_spectrum' of github.com:PennyLaneAI/pennylane i…
mariaschuld May 26, 2021
9c8626d
Fix docstring for radial box.
May 26, 2021
a2b1a79
Apply suggestions from code review
glassnotes May 26, 2021
d87a34f
Merge branch 'master' into fourier_spectrum
josh146 May 27, 2021
9d0bfc4
import visualization modules
mariaschuld May 27, 2021
5025f3f
Merge branch 'fourier_spectrum' of github.com:PennyLaneAI/pennylane i…
mariaschuld May 27, 2021
a18a032
fix sphinx links and autosummary issues, change docstrings to refer t…
mariaschuld May 27, 2021
821974d
small fix
mariaschuld May 27, 2021
c416bbf
Merge branch 'master' into fourier_spectrum
mariaschuld May 27, 2021
0e70dd6
undo jax config change in test
mariaschuld May 27, 2021
901bae0
Merge branch 'fourier_spectrum' of github.com:PennyLaneAI/pennylane i…
mariaschuld May 27, 2021
ff897cd
use config correctly
mariaschuld May 27, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added doc/_static/fourier_vis_2D_func.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added doc/_static/fourier_vis_bar_plot.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added doc/_static/fourier_vis_bar_plot_2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added doc/_static/fourier_vis_panel.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added doc/_static/fourier_vis_radial_box.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added doc/_static/fourier_vis_violin.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
9 changes: 9 additions & 0 deletions doc/code/qml_fourier.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
qml.fourier
===========

This module contains tools for computing Fourier series representations of
quantum circuits.

.. automodapi:: pennylane.fourier
:include-all-objects:
:no-inheritance-diagram:
mariaschuld marked this conversation as resolved.
Show resolved Hide resolved
1 change: 1 addition & 0 deletions doc/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,7 @@ PennyLane is **free** and **open source**, released under the Apache License, Ve
code/qml_interfaces
code/qml_operation
code/qml_devices
code/qml_fourier
code/qml_grouping
code/qml_math
code/qml_qaoa
Expand Down
2 changes: 1 addition & 1 deletion pennylane/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
from .collections import QNodeCollection, apply, dot, map, sum
from .queuing import QueuingContext
import pennylane.grouping # pylint:disable=wrong-import-order

import pennylane.fourier # pylint:disable=wrong-import-order

# Look for an existing configuration file
default_config = Configuration("config.toml")
Expand Down
350 changes: 350 additions & 0 deletions pennylane/fourier/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,350 @@
# Copyright 2018-2021 Xanadu Quantum Technologies Inc.

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

# http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

r"""Fourier series of quantum circuits
----------------------------------

Consider a quantum circuit that depends on a parameter vector :math:`x` with
length :math:`N`. The circuit involves application of some unitary operations
:math:`U(x)`, and then measurement of an observable :math:`\hat{O}`.
Analytically, the expectation value is

.. math::

\langle \hat{O} \rangle = \langle 0 \vert U^\dagger (x) \hat{O} U(x) \vert 0\rangle = \langle
\psi(x) \vert \hat{O} \vert \psi (x)\rangle.

This output is simply a function :math:`f(x) = \langle \psi(x) \vert \hat{O} \vert \psi
(x)\rangle`. Notably, it is a periodic function of the parameters, and
it can thus be expressed as a multidimensional Fourier series:

.. math::

f(x) = \sum \limits_{n_1\in \Omega_1} \dots \sum \limits_{n_N \in \Omega_N}
c_{n_1,\dots, n_N} e^{-i x_1 n_1} \dots e^{-i x_N n_N},

where :math:`n_i` are integer-valued frequencies, :math:`\Omega_i` are the set
of available values for the integer frequencies, and the
:math:`c_{n_1,\ldots,n_N}` are Fourier coefficients.

As a simple example, consider ``simple_circuit`` below, which is a function of a
single parameter.

.. code::

import pennylane as qml
from pennylane import numpy as np

dev = qml.device('default.qubit', wires=2)

@qml.qnode(dev)
def simple_circuit(x):
qml.RX(x[0], wires=0)
qml.RY(x[0], wires=1)
qml.CNOT(wires=[1, 0])
return qml.expval(qml.PauliZ(0))

We can mathematically evaluate the expectation value of this function to be
:math:`\langle Z \rangle = 0.5 + 0.5 \cos(2x)`. Thus, the Fourier coefficients
of this function are :math:`c_0 = 0.5`, :math:`c_1 = c^*_{-1} = 0`, and \
:math:`c_2 = c^*_{-2} = 0.25`.

The PennyLane ``fourier`` module enables calculation of
the values of the Fourier coefficients :math:`c_{n_1,\dots, n_N}`.
Knowledge of the coefficients, and thereby the spectrum of frequencies
where the coefficients are non-zero, is important
for the study of the expressivity of quantum circuits, as described in `Schuld,
Sweke and Meyer (2020) <https://arxiv.org/abs/2008.08605>`__ and `Vidal and
Theis, 2019 <https://arxiv.org/abs/1901.11434>`__ -- the more coefficients
available to a quantum model, the larger the class of functions that model can
represent, potentially leading to greater utility for quantum machine learning
applications.

Calculating the Fourier coefficients
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The Fourier coefficients can be numerically calculated with the
:func:`~.pennylane.fourier.coefficients` function:

.. code::

>>> from pennylane.fourier import coefficients
>>> coeffs = coefficients(simple_circuit, len(x), 2)
>>> print(np.round(coeffs, decimals=4))
[0.5 +0.j 0. -0.j 0.25+0.j 0.25+0.j 0. -0.j]

The inputs to the :func:`~.pennylane.fourier.coefficients` function are

- A QNode containing the variational circuit for which to compute the Fourier coefficients,
- the length of the input vector, and
- the maximum frequency for which to calculate the coefficients (also known as
the *degree*).

.. note::

For a quantum function of multiple inputs, it may be necessary to use a
wrapper function to ensure the Fourier coefficients are calculated with
respect to the correct input values (using, e.g., ``functools.partial``).

Internally, the coefficients are computed using numpy's `discrete Fourier
transform <https://numpy.org/doc/stable/reference/generated/numpy.fft.fftn.html>`__
function. The order of the coefficients in the output thus follows the standard
output ordering, i.e., :math:`[c_0, c_1, c_2, c_{-2}, c_{-1}]`, and similarly
for multiple dimensions.

.. note::

If a frequency lower than the true maximum frequency is used to calculate the
coefficients, it is possible that `aliasing
<https://en.wikipedia.org/wiki/Aliasing>`__ will be present in the
output. The coefficient calculator also contains a simple anti-aliasing
filter that will cut off frequencies higher than a given threshold. This can
be configured by setting the ``lowpass_filter`` option to ``True``, and optionally
specifying the ``frequency_threshold`` argument (if none is specified, 2 times
the specified degree will be used as the threshold).


Fourier coefficient visualization
---------------------------------

A key application of the Fourier module is to analyze the *expressivity* of
classes of quantum circuit families. The set of frequencies in the Fourier representation
of a quantum circuit can be used to characterize the function
class that a parametrized circuit gives rise to. For example, if an eembedding
leads to a Fourier representation with few and low-order frequencies,
a quantum circuit using this embedding can only express rather simple periodic functions.

The Fourier module contains a number of methods to visualize the coefficients of the Fourier series
representation of a single circuit, as well as distributions over Fourier coefficients for a parametrized circuit family.

.. note::

The visualization functions are structured to accept ``matplotlib`` axes as
arguments so that additional configuration (such as adding titles, saving,
etc.) can be done outside the functions. Many of the plots, however, require
a specific number of subplots. The examples below demonstrate how the subplots
should be created for each function.

Visualizing a single set of coefficients
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

While all the functions available for visualizing multiple sets of Fourier coefficients
can be used for a single set, the primary tool for this purpose is the
``coefficients_bar_plot`` function.

.. code::

import matplotlib.pyplot as plt
import pennylane as qml
from pennylane.fourier import *

dev = qml.device('default.qubit', wires=2)

@qml.qnode(dev)
def simple_circuit(x):
qml.RY(x[0], wires=0)
qml.CNOT(wires=[1, 0])
qml.RX(x[0], wires=0)
return qml.expval(qml.PauliZ(0))

>>> coeffs = coefficients(simple_circuit, 1, 2)
>>> coeffs
[0.5 +0.j 0. +0.j 0.25+0.j 0.25+0.j 0. +0.j]
>>> fig, ax = plt.subplots(2, 1, sharex=True, sharey=True) # Set up the axes
>>> coefficients_bar_plot(coeffs, 1, ax)
>>> plt.suptitle("Simple circuit bar plot")

.. image:: ../_static/fourier_vis_bar_plot.png
:align: center
:width: 500px
:target: javascript:void(0);

|

In the bar plots, real coefficients are shown in the top panel, and complex in
the bottom. The labels along the x-axis represent the coefficient frequencies
(for large plots, it is sometimes convenient to remove these by passing
``show_freqs=False`` to the plotting function).

Below is a more complex example that demonstrates some of the additional
customization options available:

.. code::

from functools import partial

weights = np.array([[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]])

@qml.qnode(dev)
def circuit_with_weights(w, x):
qml.RX(x[0], wires=0)
qml.RY(x[1], wires=1)
qml.CNOT(wires=[1, 0])

qml.Rot(*w[0], wires=0)
qml.Rot(*w[1], wires=1)
qml.CNOT(wires=[1, 0])

qml.RX(x[0], wires=0)
qml.RY(x[1], wires=1)
qml.CNOT(wires=[1, 0])

return qml.expval(qml.PauliZ(0))

coeffs = coefficients(partial(circuit_with_weights, weights), 2, 2)

# Number of inputs is now two; pass custom colours as well
fig, ax = plt.subplots(2, 1, sharex=True, sharey=True, figsize=(15, 4))
coefficients_bar_plot(coeffs, 2, ax, colour_dict={"real" : "red", "imag" : "blue"});
plt.suptitle("Circuit with weights bar plot", fontsize=14)


.. image:: ../_static/fourier_vis_bar_plot_2.png
:align: center
:Width: 100%
:target: javascript:void(0);

|

Two convenience functions are also provided to visualize 1- and 2-dimensional
landscapes given a set of Fourier coefficients:
:func:`~.pennylane.fourier.reconstruct_function_1D_plot` and
:func:`~.pennylane.fourier.reconstruct_function_2D_plot`. For example,
``circuit_with_weights`` has two input parameters ``x[0]`` and ``x[1]``, and so
we can plot its output:

.. code::

reconstruct_function_2D_plot(coeffs)
plt.title("Expectation value for circuit with weights", fontsize=14)

.. image:: ../_static/fourier_vis_2D_func.png
:align: center
:width: 400px
:target: javascript:void(0);


Visualizing multiple sets of coefficients
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^


Suppose we do not want to visualize the Fourier coefficients for a fixed
``weights`` argument in ``circuit_with_weights``, but the distribution over sets
of Fourier coefficients when the weights are randomly sampled. For each
``weights`` sample we get a different set of coefficients:

.. code::

coeffs = []

for _ in range(100):
weights = np.random.normal(0, 1, size=(2, 3))
c = coefficients(partial(circuit_with_weights, weights), 2, degree=2)
coeffs.append(np.round(c, decimals=8))

coeffs = np.array(coeffs)


One option to plot the distribution is :func:`~.pennylane.fourier.coefficients_violin_plot`:

.. code::

fig, ax = plt.subplots(2, 1, sharey=True, figsize=(15, 4))
coefficients_violin_plot(coeffs, 2, ax, show_freqs=True);
plt.suptitle("Distribution of coefficients for circuit with weights", fontsize=16)

.. image:: ../_static/fourier_vis_violin.png
:width: 100%
:target: javascript:void(0);

|

A similar option is the :func:`~.pennylane.fourier.coefficients_box_plot`, which
produces a plot of the same format but using a box plot.

A different view can obtained using the
:func:`~.pennylane.fourier.coefficients_radial_box_plot` function. This "rolls up"
the coefficients onto a polar grid. Let us use it to visualize the same set of
coefficients as above:

.. code::

# The subplot axes must be *polar* for the radial plots
fig, ax = plt.subplots(
1, 2, sharex=True, sharey=True,
subplot_kw=dict(polar=True),
figsize=(15, 8)
)
coefficients_radial_box_plot(coeffs, 2, ax, show_freqs=True, show_fliers=False)
plt.suptitle("Distribution of coefficients for circuit with weights", fontsize=16)
plt.tight_layout()


.. image:: ../_static/fourier_vis_radial_box.png
:align: center
:width: 700px
:target: javascript:void(0);

|

The left plot displays the real part, and the right the imaginary
part of the distribution over a parametrized quantum circuit's
Fourier coefficients. The labels on the "spokes" of the wheels represent the particular
frequencies; we see that this matches the coefficients we found earlier. Note
how the coefficient :math:`c_0` appears in the top middle of each plot; the
negative frequencies extend counterclockwise from that point, and the positive
frequencies increase in the clockwise direction. Such plots allow for a more
compact representation of a large number of frequencies than the linear violin
and box plots discussed above. For a large number of frequencies, however, it is
recommended to disable the frequency labelling by setting ``show_freqs=False``,
and hiding box plot fliers as was done above.

Finally, for the special case of 1- or 2-dimensional functions, we can use the
:func:`~.pennylane.fourier.coefficients_panel_plot` to plot the distributions of the
sampled sets of Fourier coefficients on the complex plane.

.. code::

# Need a grid large enough to hold all coefficients up to frequency 2
fig, ax = plt.subplots(5, 5, figsize=(12, 10), sharex=True, sharey=True)
coefficients_panel_plot(coeffs, 2, ax)
plt.suptitle(
"Fourier coefficients of circuit with weights in the complex plane",
fontsize=16
)
plt.tight_layout()

.. image:: ../_static/fourier_vis_panel.png
:align: center
:width: 700px
:target: javascript:void(0);

"""

from .coefficients import coefficients

try:
import matplotlib.pyplot as plt
except ModuleNotFoundError:
print("Module matplotlib is required for visualization in the Fourier module.")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it'd be nice if visualization was decoupled from calculation of Fourier coefficients (I can think of a few uses for knowing the coefficients but not wanting to visualize)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isn't it already decoupled? fourier_coefficients is imported above the try-except.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On a different note, this should be a warning rather than a print statement.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it's not decoupled if you get a warning msg about matplotlib even if you are not planning to do visualization

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we can import matplotlib within the __init__.py of the visualization submodule, rather than at the top-level module

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, I see

else:
from .visualization import (
coefficients_violin_plot,
coefficients_bar_plot,
coefficients_box_plot,
coefficients_panel_plot,
coefficients_radial_box_plot,
reconstruct_function_1D_plot,
reconstruct_function_2D_plot,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

recommend shorter name (e.g., using coeffs instead of coefficients), and considering an alternate name for the reconstruct_... functions (why "re"construct?)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure thing, maybe we can also switch the order to plot_coeffs_violin, plot_coeffs_bar.

)
Loading