Coder Social home page Coder Social logo

quandela / perceval Goto Github PK

View Code? Open in Web Editor NEW
139.0 5.0 63.0 15.17 MB

An open source framework for programming photonic quantum computers

Home Page: https://perceval.quandela.net

License: Other

Python 100.00%
quantum-computing physics-simulation quantum

perceval's People

Contributors

apoppn avatar aubaert avatar benoit-f-q avatar burlemarxiste avatar ericbrts avatar fzanichelli001 avatar gdgliniasty avatar giacomofrn avatar jmaterne avatar jsenellart avatar juliencalisto avatar king-p3nguin avatar lilas avatar lukamusic avatar mario-valdivia avatar marionquandela avatar mbassiouny33 avatar melvinmathe avatar nanoy42 avatar nicolasheurtel avatar pemeriau avatar qu-shaman avatar quandevla avatar raksharuia avatar samuelquandela avatar sebmalherbe avatar thibaudvdrl avatar vaap96 avatar vmscw avatar yvalibouse avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

perceval's Issues

pcvl.Processor seems to return NoneType on Boson Sampling nb

To Reproduce
Steps to reproduce the behavior:

  1. Go to Boson Sampling Demo
  2. Run all cells up to cell [12]
source = pcvl.Source(brightness=0.90, purity=0.9)
QPU = pcvl.Processor({1:source,2:source, 3:source }, Linear_Circuit_60)
  1. See error
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Input In [32], in <cell line: 2>()
      1 source = pcvl.Source(brightness=0.90, purity=0.9)
----> 2 QPU = pcvl.Processor({1:source,2:source, 3:source }, Linear_Circuit_60)

File ~/.pip/target/perceval/components/processor.py:48, in Processor.__init__(self, sources, circuit, post_select_fn)
     46 self._post_select = post_select_fn
     47 self._inputs_map = None
---> 48 for k in range(circuit.m):
     49     if k in sources:
     50         distribution = sources[k].probability_distribution()

AttributeError: 'NoneType' object has no attribute 'm'

image

Desktop (please complete the following information):

$ cat /etc/os-release 
PRETTY_NAME="Debian GNU/Linux 10 (buster)"
NAME="Debian GNU/Linux"
VERSION_ID="10"
VERSION="10 (buster)"
VERSION_CODENAME=buster
ID=debian
HOME_URL="https://www.debian.org/"
SUPPORT_URL="https://www.debian.org/support"
BUG_REPORT_URL="https://bugs.debian.org/"
$ cat /proc/cpuinfo 
processor       : 0
vendor_id       : GenuineIntel
cpu family      : 6
model           : 85
model name      : Intel(R) Xeon(R) Gold 6226R CPU @ 2.90GHz
stepping        : 7
microcode       : 0x1
cpu MHz         : 2893.202
cache size      : 16384 KB
physical id     : 0
siblings        : 1
core id         : 0
cpu cores       : 1
apicid          : 0
initial apicid  : 0
fpu             : yes
fpu_exception   : yes
cpuid level     : 13
wp              : yes
flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon rep_good nopl xtopology cpuid tsc_known_freq pni pclmulqdq vmx ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch cpuid_fault invpcid_single ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm mpx avx512f avx512dq rdseed adx smap clflushopt clwb avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves arat umip pku ospke avx512_vnni md_clear arch_capabilities
vmx flags       : vnmi preemption_timer posted_intr invvpid ept_x_only ept_ad ept_1gb flexpriority apicv tsc_offset vtpr mtf vapic ept vpid unrestricted_guest vapic_reg vid pml
$ python3 --version
Python 3.9.9
$ python3 
Python 3.9.9 (main, Dec 21 2021, 10:35:05) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import perceval
>>> print(perceval.__version__)
0.4.1

Incorrect simulation results on arm64 architecture (Apple M1) within Conda env

Describe the bug
On Mac M1 installation within a Conda environment appears to succeed, but gives incorrect simulation results.

To Reproduce
Steps to reproduce the behavior:

  1. Set-up Conda env (I'm using the Apple M1 Conda version):
  • conda create -n perceval python=3.9
  • conda activate perceval
  • pip install --upgrade pip
  • pip install perceval-quandela
  1. At this point everything seems fine, and opening a Python terminal allows to import the library. Now try to run simple circuit which just adds a phase.
  • Open python terminal. Then:
import numpy as np
import perceval as pcvl
import perceval.lib.phys as phys

bs = phys.BS(theta=0, phi_a=0, phi_b=np.pi/2, phi_d=np.pi)
C = phys.Circuit(4, name='phase')
C.add((2,3), bs)
pcvl.pdisplay(C)  # looks good
print(C.compute_unitary())  # also looks good (diagonal with -1 in last entry)
simulator_backend = pcvl.BackendFactory().get_backend("Naive")
simu = simulator_backend(C.compute_unitary())
state = pcvl.BasicState([1,1,1,1])
print(simu.probampli(state, pcvl.BasicState([1,1,1,1])))

Expected behavior
This gives result 0j, however this circuit should just add a phase on that input, so should be -1 for the amplitude.
Also it is interesting that if one does the above circuit with only two rails this works fine.
Moreover, this seems to be specific to the arm installation. On my other device (old MacBook Pro with native i386 chip) I had not seen any of these issues, when I did the installation in the exact same way.

Desktop:

  • OS: macOS (12.4)
  • CPU Arch: Apple M1
  • Python Version: 3.9
  • Perceval Version: 0.4.2

Other notes:
I tried to install it in a few different ways, including from source, using either a Rosetta terminal (with Conda configured to x86), or using virtualenv, but found similar, or other issues. Moreover I tried to use a x86 Ubuntu Docker image, and using virtualenv I was still unable to install it.
The emulated installation on x86 did not even allow to import perceval which gave error zsh: illegal hardware instruction python and crashes the terminal.

I thought this could be due to pip vs Conda installation binaries using inconsistent architecture builds, but I also tried to install all dependencies using Conda directly (and either pip installing perceval, or trying to build from source), but alas similar issues.

power operator is losing annotations

Describe the bug
When using power operator on BasicState - annotations got lost

To Reproduce

>>> s = pcvl.BasicState("|{P:H}>")
>>> print(s)
|{P:H}>
>>>print(s**2)
|{P:H},{P:H}>
>>>print(s*s)
|1,1>

Expected behavior
s**2 should be equal to s*s

Beautify display of circuits

Describe the Feature Request
Renderer of processor produces non aesthetic circuits, where components are not nicely aligned as a human would do. See the attached pictures. The reason is coming from automatic placement of the components that do not take into account global symmetry/semantic of the circuit

To Reproduce
Steps to reproduce the behavior:
In a notebook, or editor with support of matplotlib renderer:

import perceval as pcvl
import numpy as np
import random
bs = pcvl.Circuit.generic_interferometer(4,
                                         lambda idx : pcvl.BS(theta=pcvl.P("theta_%d"%idx))//(0, pcvl.PS(phi=np.pi*2*random.random())),
                                         shape="rectangle",
                                         depth = 2*4,
                                         phase_shifter_fun_gen=lambda idx: pcvl.PS(phi=np.pi*2*random.random()))
pcvl.pdisplay(bs)

Expected behavior
In such interferemoter, we expect some alignement of the beamsplitters that cannot naturally be achieved because of the intermediate phaseshifters

image

When defining a circuit, we should have a way to give horizontal grid position (x_grid in the code below)

Circuit(3).add(0, pcvl.BS(), x_grid=1).add(0, pcvl.PS(1), x_grid=2).add(2, pcvl.PS(1), x_grid=2)
  1. the x_grid would be an incremental index not mapping to a specific position but with the following semantic:
    • components with identical x_grid should be vertically aligned
    • component A with x_grid higher than component B x_grid has to be located on its right
    • component with no x_grid are flexible (as currently)
  2. this additional parameter will be used to beautify circuits generated by generic_interferometer and core_catalog objects and will be available in the add method of ACircuit class and child but also in the add method of AProcessor and child.

Additional context

In notebook, a svg renderer is used (perceval/rendering/canvas/svg_canvas.py), in editor, matplotlib renderer is used (perceval/rendering/canvas/mplot_canvas.py)

Enable selection of simple precision

Currently Perceval uses float64 as a default for storing parameters. For simulation with increasing number of modes/photons, this induces a natural 2x slowdown for numerical precision beyond any QPU native precision.

A nice feature would be to enable a mode in Perceval allowing to switch in simple precision - this could be done with global parameter containing type to use, but will also require exqalibur to accept both simple and double precision calls.

Error in the Permutation component

Describe the bug
The matrix of the permutation might not be computed correctly.

To Reproduce
Steps to reproduce the behavior:

circuit =  phys.PERM([2, 0, 1])
simulator_backend = pcvl.BackendFactory().get_backend("Naive")
s_circuit = simulator_backend(circuit)
ca = pcvl.CircuitAnalyser(s_circuit, input_states=[pcvl.AnnotatedBasicState("|1,0,0>")], 
                          output_states = [pcvl.AnnotatedBasicState("|0,0,1>"),
                                           pcvl.AnnotatedBasicState("|0,1,0>"), 
                                           pcvl.AnnotatedBasicState("|1,0,0>")])

Perceval_error_2

As you can see the photon is redirected in the second path while it should be in the third. I looked at the code, in my opinion there is a missing piece here:

super().__init__(n, U=u)

The unitary u is missing a transposition. Reasoning in physical terms, right now that function correctly describes the permutation only if you reverse the timeline, i.e., you invert the input and output states.

The 2-path transposition phys.PERM([1, 0]) , as well as the transposition shown in the Documentation, produce symmetric matrixes, hence this mistake is not evident.

  • Perceval Version: 0.4.2

Make all objects pickable (using pickle)

Prerequisite
I have not seen it requested either in github or in the forum.

Is your feature request related to a problem? Please describe.
When someone wants to take advantage of the python multiprocessing library, BasicState are not pickable. This is a bit frustrating, since using multiprocessing is sometimes very useful in order to have much faster result. In my project, the BasicState was hidden inside the Processor which held an attribute when called with with_input method. Thus it is a bit painful to debug.

Describe the solution you'd like
Be able to pickle the states by calling pickle.dump(pcvl.BasicState([0,1])) or any other Perceval objects.

Describe alternatives you've considered
A simple and effective method would be to implement __getstate__ and __setstate__ as described in the documentation.

inconsistency in version numbering post 0.7.3

Hi

when I run python .\setup.py install from 0.9 branch it finishes with:

Using /home//anaconda3/lib/python3.10/site-packages/mpmath-1.2.1-py3.10.egg
Finished processing dependencies for perceval-quandela==0.7.3.post53

but isn't it supposed to be 0.9.0?

Also in the documentation , the HTML title in the head tag of the doc says 0.7.3, which is misleading and may lead users to believe they are not browsing the correct up-to-date documentation.

This implies a constant hand-written 0.7.3 is still lurking from the old release and was never updated.

A quick search gives:
https://github.com/search?q=repo%3AQuandela%2FPerceval%200.7.3&type=code

I am not familiar with the mechanism, so I did not do a PR but I am assuming the doc gets its version number from docs/source/conf.py ? so I guess you want to update that file, the rst file too 🤷‍♂️ ?

Thanks

Heralds out of their box

Describe the bug

Perceval has a renderer at the Circuit or the Processor level allowing to generate svg or png through matplotlib library. At the processor level, it is possible to add heralds on some modes - as a result, these modes are not anymore available and the heralds are showing inside the circuit.
However, the rendering of the circuit does not take these heralds into account which makes sometime the herald appears as overlapping with the circuit box.

To Reproduce
within Pycharm or any editor supporting in-app matplot display, or within a Jupyter notebook

import Perceval as pcvl
from perceval.components.core_catalog import PostProcessedCnotItem
pcvl.pdisplay(PostProcessedCnotItem().build(), recursive=True)

image

or

circuit = pcvl.Circuit(3).add(0, pcvl.BS()).add(1, pcvl.BS(1))
processor = pcvl.Processor('SLOS', circuit)
processor.add_herald(0,0)
pcvl.pdisplay(processor, recursive=True)

image

Expected behavior
The herald on the first mode should be displayed inside the circuit bounding box

Additional context
In notebook, a svg renderer is used (perceval/rendering/canvas/svg_canvas.py), in editor, matplotlib renderer is used (perceval/rendering/canvas/mplot_canvas.py)

Support adding barrier to `perceval.Circuit`

In qiskit, barrier will separate the circuit into two distinct areas for visual purposes. (Also, it will prevent combining gates through barriers while using transpiler) To break components into separate groups, I use

circ.add(0, comp.PERM(list(range(circ.m))))

so that it works like a barrier, but it would be nice if I can add barriers to circuit not as a component.

Rendering: incorrect size of circuit box

When a processor contains nested circuits (created with the merge=False argument passed to add), the blue box enclosing each subblock is of the wrong size.

The reason is that the drawing of elements stops at one level of recursion, whereas the get_size call goes to the full depth.

This is a circuit from a tutorial:

import perceval as pcvl
from perceval.components import core_catalog
from perceval.rendering import format

from perceval.components.unitary_components import PS, BS, PERM

pre_MZI = (pcvl.Circuit(4, name="Bell State Prep")
           .add(0, BS())
           .add(2, BS())
           .add(1, PERM([1, 0])))

upper_MZI = (pcvl.Circuit(2, name="upper MZI")
             .add(0, PS(phi=pcvl.P('phi_0')))
             .add(0, BS())
             .add(0, PS(phi=pcvl.P('phi_2')))
             .add(0, BS()))

lower_MZI = (pcvl.Circuit(2, name="lower MZI")
             .add(0, PS(phi=pcvl.P('phi_1')))
             .add(0, BS())
             .add(0, PS(phi=pcvl.P('phi_3')))
             .add(0, BS()))

chip = (pcvl.Circuit(4)
              .add(0, pre_MZI, merge=False)
              .add(0, upper_MZI, merge=False)
              .add(2, lower_MZI, merge=False))

processor = pcvl.Processor('SLOS', chip)
output_format = format.Format.MPLOT
extension = "pdf"

pcvl.pdisplay_to_file(processor, 'pdisplay_multiblocks.' + extension, output_format, recursive=True)

By changing some of the merge=False arguments to True, one can get circuits with various degrees of nesting. In all the following examples, the size of the blue circuit box is the same, and corresponds to the size of the fully flattened circuit.

Screenshot 2024-06-11 at 10 49 48 Screenshot 2024-06-11 at 10 50 27 Screenshot 2024-06-11 at 10 50 47

In ICircuitRenderer.render_circuit, the call to self.get_circuit_size(c, recursive=True) is the culprit since it will always return the same value, (9, 4), corresponding to the size of a completely flattened circuit.

Possible fixes:

  1. Add a recursion_level parameter to all functions recursively traversing circuits (flatten, get_size, get_circuit_size, render_circuit, pdisplay_processor, pdisplay_circuit...), and make sure they consistently traverse the circuit graph at the appropriate depth.
  2. Assume that one should never draw anything deeper than one level of recursion, and thus set recursive=False in the function call retrieving the size of a block. A similar change has to be done to the herald positioning code (it should flatten only one level deep to attach the heralds to the elements that are actually going to be drawn).
  3. Assume that setting recursive=True should always go to the full recursion depth, at the risk of getting large diagrams. Thus render_circuit should pass its recursive argument when calling itself.

Unit test modifies access permissions of critical system directory [macOS]

As part of the unit test checking persistent data saving and loading, the access permissions of the parent directory are changed.

os.chmod(parent_directory, 0o000)

On macOS, this changes the permissions of /Users/my_user/Library/Application Support/, which contains settings and data for all other installed applications.

Consequences:

  • The system settings directory becomes unreadable if the test aborts (happened on my system).
  • Even if the test runs successfully, the permissions are reset to 0o777, giving other users of the system the ability to erase or overwrite settings files.

In addition, 0o755 or 0o700 might be a more reasonable setting than 0o777 for the folder storing Perceval settings.

Suggested fix: something like pyfakefs if test coverage is essential, if not, excluding the test involving the parent directory?

pcvl.Circuit.decomposition seems to return NoneType on Boson Sampling nb

To Reproduce
Steps to reproduce the behavior:

  1. Go to Boson Sampling Demo
  2. Run all cells up to cell [5]
Linear_Circuit_60 = pcvl.Circuit.decomposition(Unitary_60, mzi,
                                               phase_shifter_fn=symb.PS,
                                               shape="triangle")
pcvl.pdisplay(Linear_Circuit_60)
  1. See error
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
Input In [5], in <cell line: 4>()
      1 Linear_Circuit_60 = pcvl.Circuit.decomposition(Unitary_60, mzi,
      2                                                phase_shifter_fn=symb.PS,
      3                                                shape="triangle")
----> 4 pcvl.pdisplay(Linear_Circuit_60)

File ~/.pip/target/perceval/utils/utils.py:63, in pdisplay(o, output_format, **opts)
     61         r = simple_complex(o, **opts_simple)[1]
     62     else:
---> 63         raise RuntimeError("pdisplay not defined for type %s" % type(o))
     64 else:
     65     r = o.pdisplay(output_format=output_format, **opts)

RuntimeError: pdisplay not defined for type <class 'NoneType'>

Expected behavior
A display of the circuit

Screenshots
image

Desktop (please complete the following information):

$ cat /etc/os-release 
PRETTY_NAME="Debian GNU/Linux 10 (buster)"
NAME="Debian GNU/Linux"
VERSION_ID="10"
VERSION="10 (buster)"
VERSION_CODENAME=buster
ID=debian
HOME_URL="https://www.debian.org/"
SUPPORT_URL="https://www.debian.org/support"
BUG_REPORT_URL="https://bugs.debian.org/"
$ cat /proc/cpuinfo 
processor       : 0
vendor_id       : GenuineIntel
cpu family      : 6
model           : 85
model name      : Intel(R) Xeon(R) Gold 6226R CPU @ 2.90GHz
stepping        : 7
microcode       : 0x1
cpu MHz         : 2893.202
cache size      : 16384 KB
physical id     : 0
siblings        : 1
core id         : 0
cpu cores       : 1
apicid          : 0
initial apicid  : 0
fpu             : yes
fpu_exception   : yes
cpuid level     : 13
wp              : yes
flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon rep_good nopl xtopology cpuid tsc_known_freq pni pclmulqdq vmx ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch cpuid_fault invpcid_single ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm mpx avx512f avx512dq rdseed adx smap clflushopt clwb avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves arat umip pku ospke avx512_vnni md_clear arch_capabilities
vmx flags       : vnmi preemption_timer posted_intr invvpid ept_x_only ept_ad ept_1gb flexpriority apicv tsc_offset vtpr mtf vapic ept vpid unrestricted_guest vapic_reg vid pml
$ python3 --version
Python 3.9.9
$ python3 
Python 3.9.9 (main, Dec 21 2021, 10:35:05) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import perceval
>>> print(perceval.__version__)
0.4.1

QASM to linear optics circuit converter

Taking QiskitConverter / MyQLMConverter as examples (located in package perceval.converter), write a converter taking a qasm file as input.

The QASMConverter will return a fully setup Perceval Processor. It needs to support a subset of gates that Perceval already supports (all 1-qubit gates, CX, CZ, CCX and CCZ), qubit naming.
An exception should be raised for other gates, for classical bits, and other feature that Perceval does not support.

Latex Renderer

To include Perceval circuits in latex paper, we only have the option to generate svg through svg renderer (perceval/rendering/canvas/svg_canvas.py) or png through mplot renderer (perceval/rendering/canvas/mplot_canvas.py). The renderer are automatically selected or can be specified with output_format=Format.TEXT|LATEX|HTML option. For circuit, LATEX format is not supported:

in perceval/rendering/circuit/renderer.py:

    if output_format == Format.LATEX:
        raise NotImplementedError("Latex format is not supported for circuit rendering")

Describe the solution you'd like
Having a LaTeX renderer would enable integration of higher quality circuits in scientific papers - we can integrate svg inside LaTeX using Inkscape, but it does not give the control of the generated graph for further LaTeX editing.
A solution could be to generate TikZ code that will then be fully editable within latex - for instance changing font size, adding formula, etc...

Error in the heralded CNOT in 0.9 version

Hello,
It appears that there is still a problem with the heralded CNOT gate (the one with 8 modes) corrected last week in the 0.9 version. While it computes the right probabilities, I found that the heralded gate is reproducing a control(-X) operation instead of a controlX. I found out while applying my quantum process tomography algorithm on this gate.

I might be wrong, but my algorithm works for the heralded CZ gate in 0.9 version and also for every other 1 qubit and non entangling 2qubit gates. Besides, the heralded CZ gate with H gate on both sides of the target qubit truly implements a controlX operation.

Thanks in advance,

Arman

Qiskit converter appears to fail for Qiskit circuit

Description:
I'm attempting to take a qiskit.QuantumCircuit object that is obtained from the QFT QED-C benchmark and use the perceval converter to take that and convert it into something that perceval understands, but the converter appears to be failing.

Steps to reproduce:

Clone QED-C repo:

git clone https://github.com/vprusso/QC-App-Oriented-Benchmarks.git
cd QC-App-Oriented-Benchmarks/

Create virtual env:
python -m venv venv

Activate virtual env:
source venv/bin/activate

Install minimal dependencies:

pip install qiskit
pip install perceval-quandela

(Attempt to) run QFT benchmark
In QC-App-Oriented-Benchmarks/quantum-fourier-transform/qiskit, replace the if __name__ == "__main__" block with:

    import perceval as pcvl
    from perceval.converters import QiskitConverter
    from perceval.components import catalog

    token_qcloud = '<TOKEN>'

    circuit = QuantumFourierTransform(2, 1)

    # Then convert the Quantum Circuit with Perceval QiskitConvertor
    qiskit_converter = QiskitConverter(catalog, backend_name="Naive")
    quantum_processor = qiskit_converter.convert(circuit)

The following error seems to arise:

Traceback (most recent call last):
  File "/Users/vincent.russo/Projects/resarch/unitary_fund/metriq-api/benchmark/benchmark/QC-App-Oriented-Benchmarks/quantum-fourier-transform/qiskit/qft_benchmark.py", line 397, in <module>
    quantum_processor = qiskit_converter.convert(circuit)
                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/vincent.russo/Projects/resarch/unitary_fund/metriq-api/benchmark/venv/lib/python3.11/site-packages/perceval/converters/qiskit_converter.py", line 89, in convert
    assert isinstance(instruction[0], qiskit.circuit.gate.Gate), "cannot convert (%s)" % instruction[0]
AssertionError: cannot convert (Instruction(name='inv_qft', num_qubits=2, num_clbits=0, params=[]))

Indeed, the circuit variable up above is a qiskit.QuantumCircuit object, so, in theory, I believe it should be being fed the right type of argument.

Is there any type of necessary transpilation that might need to take place? I also attempted to transpile the gates as:

    from qiskit import transpile

    basis_gates = ['u1', 'u2', 'u3', 'cx', 'u']

    qc = QuantumFourierTransform(2, 1)
    qc = transpile(qc, basis_gates=basis_gates)

However, this did not seem to work either.

Traceback (most recent call last):
  File "/Users/vincent.russo/Projects/resarch/unitary_fund/metriq-api/benchmark/benchmark/QC-App-Oriented-Benchmarks/quantum-fourier-transform/qiskit/qft_benchmark.py", line 395, in <module>
    quantum_processor = qiskit_converter.convert(qc)
                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/vincent.russo/Projects/resarch/unitary_fund/metriq-api/benchmark/venv/lib/python3.11/site-packages/perceval/converters/qiskit_converter.py", line 95, in convert
    p.add(instruction[1][0].index * 2, ins.copy())
  File "/Users/vincent.russo/Projects/resarch/unitary_fund/metriq-api/benchmark/venv/lib/python3.11/site-packages/perceval/components/abstract_processor.py", line 216, in add
    raise RuntimeError("Cannot add any component to a processor with a post-process function. You may remove the post-process function by calling clear_postprocess()")
RuntimeError: Cannot add any component to a processor with a post-process function. You may remove the post-process function by calling clear_postprocess()

I know that's a lot of output and content, and if there's anything further I can provide that might be helpful, please do let me know!

Example for a system of nonlinear differential equations

A system of differential equations resolution?

I'm deeply interested in your work on Perceval, particularly for solving a nonlinear differential equation as shown in Section 4.6.3 in your publication: https://perceval.quandela.net/docs/notebooks/Differential_equation_resolution.html

While your example on a single nonlinear differential equation is impressive, I'm curious about its extensible application to a system of nonlinear differential equations. Could you provide any guidance or resources on this?
For example:
dx/dt = x−3y+sin(x)
dy/dt = −x+y−2cos(y)

Thanks!

Pip installation error - cmake

I was excited to install and use it, but it failed at the pip install stage.

System

  • MacBook Pro (2021)
  • Apple M1 Pro
  • macOS 12.2.1 (Monterey)

Environment

  • conda 4.10.3
  • Python 3.9.7
  • pip-22.0.4

Error

pip install pip install perceval-quandela I got a message containing:

  Building wheel for quandelibc (setup.py) ... error
  error: subprocess-exited-with-error
  
  × python setup.py bdist_wheel did not run successfully.
  │ exit code: 1
  ╰─> [4 lines of output]
      running bdist_wheel
      running build
      running build_ext
      error: [Errno 2] No such file or directory: 'cmake'
      [end of output]

Questions

I assume that cmake is needed. Which version to use?

Time Delay (TD) element's functionality not implemented

In the Hong-Ou-Mandel simulation script, found here, there are two errors.

The first is the initialization of the AnnotatedBasicState has incorrect arguments, this can be fixed by transforming the keyword arguments into a list. I changed line 45 to:

st0 = pcvl.AnnotatedBasicState([1, 0], {0: {"time": 2e-9, "time_gen_fn":photon_length_fn}})

However, then there still appears an error when I run the script:

  File "...\test.py", line 52, in f
    return sim.prob(st0, qc.FockState([2, 0]))+sim.prob(st0, qc.FockState([0, 2]))
  File "...\env\lib\site-packages\perceval\backends\template.py", line 165, in prob
    self.compile(i_state)
  File "...\env\lib\site-packages\perceval\backends\stepper.py", line 96, in compile
    sv.apply_delta_t(r[0], float(c._dt))
AttributeError: 'StateVector' object has no attribute 'apply_delta_t'

The line that it fails on is:

sv.apply_delta_t(r[0], float(c._dt))

In the definition of StateVector and its parent classes there is no definition of the apply_delta_t method.

drawSvg 2.0 has a new api, causes import failure

Prerequisite
Please ensure that this bug has not been answered on the Perceval forum Done

Describe the bug
drawsvg (previously drawSvg) has changed its naming scheme from CamelCase to underscore based, in the 2.0 major release.

Installing drawsvg with version greater than 2.0 causes import perceval to fail, because of import drawSvg statements in several places.

To Reproduce
Steps to reproduce the behavior:

  1. On a clean system, python -m pip install perceval-quandela
  2. On the python console import perceval
  3. Error relating to import drawSvg pops up

Expected behavior
Import should occur with no errors.

Desktop (please complete the following information):

  • OS: Debian
  • CPU Arch: x86_64
  • Python Version: 3.10
  • Perceval Version: 0.7.3

Additional context
The temporary fix is to add drawsvg<2.0 in the requirements.txt. Long term, perceval should start using the latest version of drawsvg. As many of drawsvg function names have changed, this will require some work.

Definition of (perfect) complex input states

It is possible today in Perceval to work with complex input state by manually constructing it with pcvl.StateVector - for instance to work with Bell state: 1/sqrt(2)(|01>+|10>) in dual rail encoding, we would do something like that:

sv=pcvl.StateVector(pcvl.BasicState("|1,0,0,1>"))+pcvl.StateVector(pcvl.BasicState("|0,1,1,0>"))

This is used for instance in a simulation as follow:

processor=pcvl.Processor("SLOS", pcvl.Circuit(4).add(1, pcvl.BS()))
processor.with_input(sv)
pcvl.pdisplay(processor.probs()["results"])

A conversion from logical state |01> => |1,0,0,1> already exists through the concept of Processor port:

ls=pcvl.LogicalState([0,1])
print(ls.to_basic_state([pcvl.Port(pcvl.Encoding.DUAL_RAIL, "p1"), pcvl.Port(pcvl.Encoding.DUAL_RAIL, "p2")]))

We would like to have simpler generators of simple and complex states - for a given encoding:

These generators would be available in a StateGenerator class initialized with an encoding (Encoding.RAW (=logical state), Encoding.DUAL_RAIL, and Encoding.POLARIZATION) to be supported

Example code:

>>> generator=pcvl.StateGenerator(Encoding.DUAL_RAIL)
>>> print(generator.LogicalState([0,1]))
|1,0,0,1>
>>> print(generator.BellState("phi+"))
sqrt(2)/2*|1,0,1,0>+sqrt(2)/2*|0,1,0,1>
>>> print(generator.GHZState(3))
sqrt(2)/2*|1,0,1,0,1,0>+sqrt(2)/2*|0,1,0,1,0,1>
>>> graph=nx.path_graph(3)
>>> print(generator.GraphState(graph))
1/sqrt(8)*|1,0,1,0,1,0>+1/sqrt(8)*|0,1,1,0,1,0>+1/sqrt(8)*|1,0,0,1,1,0>+1/sqrt(8)*|1,0,1,0,0,1>+1/sqrt(8)*|0,1,0,1,0,1>-1/sqrt(8)*|1,0,0,1,0,1>-1/sqrt(8)*|0,1,0,1,1,0>+1/sqrt(8)*|0,1,1,0,0,1>

How to sample a StateVector input

Prerequisite
Please ensure this has not been requested on the Perceval forum

Is your feature request related to a problem? Please describe.
Is perceval package capable of sampling input state defined as a StateVector object? I want to sample an input state like $\frac{1}{\sqrt{2}} (|1,0&gt;+|0,1&gt;)$, so I type the code:

p = pcvl.Processor("Naive",circuit)
p.with_input(state_vector)

However, it reports:
NotImplementedError: Could not find signature for with_input: <StateVector>

It seems that I can only input a BasisState object for sampling tasks, and I don't know how to get probability amplitudes and make superposition of them (there is only sampler.probs() which is not correct for superposition).

Noise model for various gates

The Perceval framework had provided error models for the overall circuit by adding multiphoton component in the source laser beam.
But it would be better if there is a noise associated with various gates (beam splitter, phase shifters) which are being applied. Since practically the various photonics components are not 100% accurate, we may need to model the noise associated with each gate operation.

Also, the Perceval forum link shows Error 500 when trying to post queries in the forum.
https://perceval.quandela.net/forum/

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.