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

BtoF #522

Open
wants to merge 64 commits into
base: develop
Choose a base branch
from
Open

BtoF #522

Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
64 commits
Select commit Hold shift + click to select a range
52dc84e
progress
ziofil Oct 30, 2024
54dece0
Merge branch 'develop' into BtoF
ziofil Oct 30, 2024
b2cb63e
save progress
ziofil Oct 31, 2024
3af12af
fixed call
ziofil Nov 1, 2024
d2ac182
refactored _call_all
ziofil Nov 1, 2024
7036e40
save progress
ziofil Nov 5, 2024
dfd5527
Merge branch 'develop' into BtoF
ziofil Nov 5, 2024
2b760b7
save progress
ziofil Nov 6, 2024
76fd3a2
make format
ziofil Nov 8, 2024
66d4d4d
refactored decompose
ziofil Nov 8, 2024
4ce96c6
sync
ziofil Nov 12, 2024
8c61e3b
finished polyexp ansatz
ziofil Nov 12, 2024
ebcb558
progress
ziofil Nov 13, 2024
7ccb75d
new wires
ziofil Nov 14, 2024
bdaa1f0
skip progressbar if needed (#516)
ziofil Nov 12, 2024
d0d47ac
updates
ziofil Nov 14, 2024
d4f9761
better format
ziofil Nov 14, 2024
f7b4600
replace old wires
ziofil Nov 14, 2024
774e089
fix codefactor issues
ziofil Nov 14, 2024
0e4c8e6
fixes wires tests
ziofil Nov 14, 2024
b71adda
default wires for components
ziofil Nov 15, 2024
dc7f155
fix set issue
ziofil Nov 15, 2024
a71aafa
fix attribute name
ziofil Nov 15, 2024
1561de2
update representation and tests
ziofil Nov 15, 2024
2547163
fixed permutation
ziofil Nov 15, 2024
b31d604
updated gitignore
ziofil Nov 15, 2024
28e7a5e
sync
ziofil Nov 18, 2024
2458998
sync
ziofil Nov 19, 2024
b84fd2e
fix order and remove print
ziofil Nov 19, 2024
1665237
sync
ziofil Nov 19, 2024
487bfd0
fixed serialization
ziofil Nov 19, 2024
25d09d9
only sets
ziofil Nov 20, 2024
e32b82c
fix doctest
ziofil Nov 21, 2024
8c336d3
codefactor
ziofil Nov 25, 2024
46584b8
imports
ziofil Nov 25, 2024
a553cda
imports
ziofil Nov 25, 2024
1894c46
pylint
ziofil Nov 25, 2024
ead2001
pylint
ziofil Nov 25, 2024
f4b446e
fixed import
ziofil Nov 25, 2024
d05f87f
remove unused code
ziofil Nov 25, 2024
6871e4b
removed commented code
ziofil Nov 25, 2024
cdc57e7
removed unused code
ziofil Nov 25, 2024
45c3bfa
fix wires
ziofil Nov 26, 2024
2524b68
add test
ziofil Nov 26, 2024
c83aea8
removed import
ziofil Nov 26, 2024
87d22b6
iterable -> sequence
ziofil Nov 26, 2024
7014180
test Number wires
ziofil Nov 26, 2024
fa20331
fix attribute name
ziofil Nov 27, 2024
8ceb2ae
fix attr name
ziofil Nov 27, 2024
991b80b
fixed wires
ziofil Nov 27, 2024
e1ba15a
better pylintrc
ziofil Nov 27, 2024
e218e4e
convolution added to numpy backend (#517)
ziofil Nov 27, 2024
144958f
better pylintrc
ziofil Nov 27, 2024
6f8a34e
more tests
ziofil Nov 27, 2024
ed25e82
pylint kwuygfkuqygrejhf
ziofil Nov 27, 2024
b9be5e5
Sequence -> Collection
ziofil Nov 27, 2024
ef39521
removed pylint disable
ziofil Nov 28, 2024
290cf62
move plot and rename class
ziofil Nov 28, 2024
839cf99
sync
ziofil Nov 29, 2024
374c39c
sync
ziofil Dec 2, 2024
8dc9962
Adding a bunch of gates from the lab (#520)
arsalan-motamedi Dec 9, 2024
bff3d17
fix the ipython_display side effect (#531)
timmysilv Dec 9, 2024
e9be0d7
Python 3.12 version bump (#528)
apchytr Dec 10, 2024
e9b70ac
Unitary/Channel from fock (#530)
arsalan-motamedi Dec 12, 2024
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
3 changes: 3 additions & 0 deletions .github/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@
* Fix the TensorFlow issue with the expected number of gradients in `custom_gradient`.
[(#506)](https://github.com/XanaduAI/MrMustard/pull/506)

* Use the default repr when in interactive IPython.
[(#531)](https://github.com/XanaduAI/MrMustard/pull/531)

### Documentation

### Tests
Expand Down
18 changes: 12 additions & 6 deletions .github/workflows/tests_numpy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,15 @@ jobs:
runs-on: ubuntu-latest
permissions:
id-token: write # This is required for requesting the JWT for S3 access
strategy:
matrix:
python-version: ['3.9', '3.12']
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
group: ${{ github.workflow }}-${{ matrix.python-version }}-${{ github.ref }}
cancel-in-progress: true
env:
HYPOTHESIS_PROFILE: ci
UPLOAD_TIMINGS: ${{ github.event_name == 'push' && matrix.python-version == '3.12' && 'true' || 'false' }}

steps:
- name: Checkout repo
Expand All @@ -23,7 +27,7 @@ jobs:
- name: Setup python
uses: actions/setup-python@v4
with:
python-version: '3.11'
python-version: ${{ matrix.python-version }}

- name: Setup Julia
uses: julia-actions/setup-julia@v1
Expand All @@ -47,18 +51,20 @@ jobs:
- name: Run tests
run: |
set -o pipefail
python -m pytest tests --backend=numpy -p no:warnings --tb=native ${{ github.event_name == 'push' && '--durations=0 -vv ' || '' }}| tee durations.txt
python -m pytest tests --backend=numpy -p no:warnings --tb=native ${{ env.UPLOAD_TIMINGS == 'true' && '--durations=0 -vv ' || '' }}| tee durations.txt
set +o pipefail

- name: configure aws credentials
if: github.event_name == 'push'
if: env.UPLOAD_TIMINGS == 'true'
uses: aws-actions/configure-aws-credentials@v3
with:
role-to-assume: ${{ secrets.AWS_OIDC_ROLE_ARN }}
aws-region: ${{ vars.AWS_DEFAULT_REGION }}

- name: Copy durations to s3
if: github.event_name == 'push'
if: env.UPLOAD_TIMINGS == 'true'
env:
REF_NAME: ${{ github.ref_name }}
run: |
grep ' call ' durations.txt | awk '{print $3,$1}' > ${{ steps.record_file.outputs.filename }}
aws s3 cp ./${{ steps.record_file.outputs.filename }} s3://${{ secrets.AWS_TIMINGS_BUCKET }}/numpy_tests/${{ github.ref_name }}/
aws s3 cp ./${{ steps.record_file.outputs.filename }} s3://${{ secrets.AWS_TIMINGS_BUCKET }}/numpy_tests/$REF_NAME/
18 changes: 12 additions & 6 deletions .github/workflows/tests_tensorflow.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,15 @@ jobs:
runs-on: ubuntu-latest
permissions:
id-token: write # This is required for requesting the JWT for S3 access
strategy:
matrix:
python-version: ['3.9', '3.12']
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
group: ${{ github.workflow }}-${{ matrix.python-version }}-${{ github.ref }}
cancel-in-progress: true
env:
HYPOTHESIS_PROFILE: ci
UPLOAD_TIMINGS: ${{ github.event_name == 'push' && matrix.python-version == '3.12' && 'true' || 'false' }}

steps:
- name: Checkout repo
Expand All @@ -23,7 +27,7 @@ jobs:
- name: Setup python
uses: actions/setup-python@v4
with:
python-version: '3.11'
python-version: ${{ matrix.python-version }}

- name: Setup Julia
uses: julia-actions/setup-julia@v1
Expand All @@ -47,7 +51,7 @@ jobs:
- name: Run tests
run: |
set -o pipefail
python -m pytest tests --backend=tensorflow --cov=mrmustard --cov-report=term-missing --cov-report=xml -p no:warnings --tb=native ${{ github.event_name == 'push' && '--durations=0 -vv ' || '' }}| tee durations.txt
python -m pytest tests --backend=tensorflow --cov=mrmustard --cov-report=term-missing --cov-report=xml -p no:warnings --tb=native ${{ env.UPLOAD_TIMINGS == 'true' && '--durations=0 -vv ' || '' }}| tee durations.txt
set +o pipefail

- name: Upload coverage to Codecov
Expand All @@ -58,14 +62,16 @@ jobs:
fail_ci_if_error: true

- name: configure aws credentials
if: github.event_name == 'push'
if: env.UPLOAD_TIMINGS == 'true'
uses: aws-actions/configure-aws-credentials@v3
with:
role-to-assume: ${{ secrets.AWS_OIDC_ROLE_ARN }}
aws-region: ${{ vars.AWS_DEFAULT_REGION }}

- name: Copy durations to s3
if: github.event_name == 'push'
if: env.UPLOAD_TIMINGS == 'true'
env:
REF_NAME: ${{ github.ref_name }}
run: |
grep ' call ' durations.txt | awk '{print $3,$1}' > ${{ steps.record_file.outputs.filename }}
aws s3 cp ./${{ steps.record_file.outputs.filename }} s3://${{ secrets.AWS_TIMINGS_BUCKET }}/tf_tests/${{ github.ref_name }}/
aws s3 cp ./${{ steps.record_file.outputs.filename }} s3://${{ secrets.AWS_TIMINGS_BUCKET }}/tf_tests/$REF_NAME/
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,4 @@ coverage.xml
.coverage
/.serialize_cache/

.venv
.venv*
4 changes: 3 additions & 1 deletion .pylintrc
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,6 @@ ignored-classes=numpy,tensorflow,scipy,networkx,strawberryfields,thewalrus
# can either give multiple identifier separated by comma (,) or put this option
# multiple time (only on the command line, not in the configuration file where
# it should appear only once).
disable=fixme,no-member,line-too-long,invalid-name,too-many-lines,redefined-builtin,too-many-locals,duplicate-code,too-many-arguments,too-few-public-methods,no-else-return,isinstance-second-argument-not-valid-type,no-self-argument, arguments-differ, protected-access
disable=fixme,no-member,line-too-long,invalid-name,too-many-lines,redefined-builtin,too-many-locals,
duplicate-code,too-many-arguments,too-few-public-methods,no-else-return,isinstance-second-argument-not-valid-type,
no-self-argument, arguments-differ, protected-access, too-many-positional-arguments, possibly-used-before-assignment
7 changes: 4 additions & 3 deletions doc/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,9 @@
automodapi_toctreedirnm = "code/api"
automodsumm_inherited_members = True

mathjax_path = "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML"
mathjax_path = (
"https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML"
)

bibtex_bibfiles = ["references.bib"]

Expand Down Expand Up @@ -139,8 +141,7 @@
}
],
"extra_copyrights": [
"TensorFlow, the TensorFlow logo, and any related marks are trademarks "
"of Google Inc."
"TensorFlow, the TensorFlow logo, and any related marks are trademarks " "of Google Inc."
],
"google_analytics_tracking_id": "UA-116279123-2",
"prev_next_button_colour": "#b79226",
Expand Down
18 changes: 11 additions & 7 deletions mrmustard/lab_dev/circuit_components.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def _serialize(self) -> tuple[dict[str, Any], dict[str, ArrayLike]]:
if "name" in params: # assume abstract type, serialize the representation
ansatz_cls = type(self.ansatz)
serializable["name"] = self.name
serializable["wires"] = self.wires.sorted_args
serializable["wires"] = tuple(tuple(a) for a in self.wires.args)
serializable["ansatz_cls"] = f"{ansatz_cls.__module__}.{ansatz_cls.__qualname__}"
return serializable, self.ansatz.to_dict()

Expand Down Expand Up @@ -113,7 +113,9 @@ def _deserialize(cls, data: dict) -> CircuitComponent:
if "ansatz_cls" in data:
ansatz_cls, wires, name = map(data.pop, ["ansatz_cls", "wires", "name"])
ansatz = locate(ansatz_cls).from_dict(data)
return cls._from_attributes(Representation(ansatz, Wires(*map(set, wires))), name=name)
return cls._from_attributes(
Representation(ansatz, Wires(*tuple(set(m) for m in wires))), name=name
)

return cls(**data)

Expand Down Expand Up @@ -222,7 +224,7 @@ def from_bargmann(
modes_out_ket: Sequence[int] = (),
modes_in_ket: Sequence[int] = (),
name: str | None = None,
) -> CircuitComponent:
) -> CircuitComponent: # pylint:disable=too-many-positional-arguments
r"""
Initializes a ``CircuitComponent`` object from its Bargmann (A,b,c) parametrization.

Expand Down Expand Up @@ -251,7 +253,7 @@ def from_quadrature(
triple: tuple,
phi: float = 0.0,
name: str | None = None,
) -> CircuitComponent:
) -> CircuitComponent: # pylint:disable=too-many-positional-arguments
r"""
Returns a circuit component from the given triple (A,b,c) that parametrizes the
quadrature wavefunction of this component in the form :math:`c * exp(1/2 x^T A x + b^T x)`.
Expand Down Expand Up @@ -501,7 +503,6 @@ def to_fock(self, shape: int | Sequence[int] | None = None) -> CircuitComponent:
>>> d_fock = d.to_fock(shape=3)

>>> assert d_fock.name == d.name
>>> assert d_fock.wires == d.wires
>>> assert isinstance(d_fock.ansatz, ArrayAnsatz)

Args:
Expand Down Expand Up @@ -698,9 +699,9 @@ def __rshift__(self, other: CircuitComponent | numbers.Number) -> CircuitCompone
if only_ket or only_bra or both_sides:
ret = self @ other
elif self_needs_bra or self_needs_ket:
ret = (self.adjoint @ self) @ other
ret = self.adjoint @ (self @ other)
elif other_needs_bra or other_needs_ket:
ret = self @ (other @ other.adjoint)
ret = (self @ other.adjoint) @ other
else:
msg = f"``>>`` not supported between {self} and {other} because it's not clear "
msg += "whether or where to add bra wires. Use ``@`` instead and specify all the components."
Expand All @@ -724,6 +725,9 @@ def __truediv__(self, other: Scalar) -> CircuitComponent:
return self._from_attributes(Representation(self.ansatz / other, self.wires), self.name)

def _ipython_display_(self):
if mmwidgets.IN_INTERACTIVE_SHELL:
print(self)
return
# both reps might return None
rep_fn = mmwidgets.fock if isinstance(self.ansatz, ArrayAnsatz) else mmwidgets.bargmann
rep_widget = rep_fn(self.ansatz)
Expand Down
9 changes: 4 additions & 5 deletions mrmustard/lab_dev/circuit_components_utils/b_to_ps.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@

from ..transformations.base import Map
from ...physics.ansatz import PolyExpAnsatz
from ...physics.representations import RepEnum
from ...physics.wires import ReprEnum
from ..utils import make_parameter

__all__ = ["BtoPS"]
Expand Down Expand Up @@ -53,10 +53,9 @@ def __init__(
fn=triples.displacement_map_s_parametrized_Abc, s=self.s, n_modes=len(modes)
),
).representation
for i in self.wires.input.indices:
self.representation._idx_reps[i] = (RepEnum.BARGMANN, None)
for i in self.wires.output.indices:
self.representation._idx_reps[i] = (RepEnum.PHASESPACE, float(self.s.value))
for w in self.representation.wires.output.wires:
w.repr = ReprEnum.CHARACTERISTIC
w.repr_params = float(self.s.value)

def inverse(self):
ret = BtoPS(self.modes, self.s)
Expand Down
12 changes: 7 additions & 5 deletions mrmustard/lab_dev/circuit_components_utils/b_to_q.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@

from ..transformations.base import Operation
from ...physics.ansatz import PolyExpAnsatz
from ...physics.representations import RepEnum
from ...physics.wires import ReprEnum
from ..utils import make_parameter

__all__ = ["BtoQ"]
Expand Down Expand Up @@ -53,10 +53,12 @@ def __init__(
fn=triples.bargmann_to_quadrature_Abc, n_modes=len(modes), phi=self.phi
),
).representation
for i in self.wires.input.indices:
self.representation._idx_reps[i] = (RepEnum.BARGMANN, None)
for i in self.wires.output.indices:
self.representation._idx_reps[i] = (RepEnum.QUADRATURE, float(self.phi.value))
for w in self.representation.wires.input.wires:
w.repr = ReprEnum.BARGMANN
w.repr_params = None
for w in self.representation.wires.output.wires:
w.repr = ReprEnum.QUADRATURE
w.repr_params = float(self.phi.value)

def inverse(self):
ret = BtoQ(self.modes, self.phi)
Expand Down
3 changes: 2 additions & 1 deletion mrmustard/lab_dev/circuit_components_utils/trace_out.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
from ..circuit_components import CircuitComponent
from ...physics.ansatz import PolyExpAnsatz
from ...physics.representations import Representation
from ...physics.wires import Wires

__all__ = ["TraceOut"]

Expand Down Expand Up @@ -65,7 +66,7 @@ def __init__(
super().__init__(
Representation(
PolyExpAnsatz.from_function(fn=triples.identity_Abc, n_modes=len(modes)),
[(), modes, (), modes],
Wires(set(), set(modes), set(), set(modes)),
),
name="Tr",
)
Expand Down
2 changes: 1 addition & 1 deletion mrmustard/lab_dev/circuits.py
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@ def serialize(self, filestem: str = None):
@classmethod
def deserialize(cls, data: dict) -> Circuit:
r"""Deserialize a Circuit."""
comps, path = map(data.pop, ("components", "path"))
comps, path = data.pop("components"), data.pop("path")

for k, v in data.items():
kwarg, i = k.split(":")
Expand Down
2 changes: 2 additions & 0 deletions mrmustard/lab_dev/states/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,10 @@
from .ket import Ket
from .dm import DM

from .bargmann_eigenstate import BargmannEigenstate
from .coherent import Coherent
from .displaced_squeezed import DisplacedSqueezed
from .gstate import GKet, GDM
from .number import Number
from .quadrature_eigenstate import QuadratureEigenstate
from .squeezed_vacuum import SqueezedVacuum
Expand Down
67 changes: 67 additions & 0 deletions mrmustard/lab_dev/states/bargmann_eigenstate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# Copyright 2024 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.

"""
The class representing a Bargmann eigenstate.
"""

from __future__ import annotations

from typing import Sequence

from mrmustard.physics.ansatz import PolyExpAnsatz
from mrmustard.physics import triples
from .ket import Ket
from ..utils import make_parameter

__all__ = ["BargmannEigenstate"]


class BargmannEigenstate(Ket):
r"""
The `N`-mode Bargmann eigenstate.

.. code-block ::

>>> from mrmustard.lab_dev import BargmannEigenstate

>>> state = BargmannEigenstate([1, 2], [0.1, 0.5j])
>>> assert state.modes == [1, 2]

Args:
modes: A list of modes.
alpha: The displacement of the state (i.e., the eigen-value).

.. details::
Its ``(A,b,c)`` triple is given by
.. math::
A = 0 , b = alpha, c = 1.
"""

short_name = "Be"

def __init__(
self,
modes: Sequence[int],
alpha: float | Sequence[float] = 0.0,
alpha_trainable: bool = False,
alpha_bounds: tuple[float | None, float | None] = (None, None),
):
super().__init__(name="BargmannEigenstate")

self._add_parameter(make_parameter(alpha_trainable, alpha, "alpha", alpha_bounds))
self._representation = self.from_ansatz(
modes=modes,
ansatz=PolyExpAnsatz.from_function(fn=triples.bargmann_eigenstate_Abc, x=self.alpha),
).representation
Loading