Giter Club home page Giter Club logo

quantum-viz.js's Introduction

quantum-viz.js

Licensed under the MIT License PR's Welcome Build Status npm version

screenshot of circuit generated by quantum-viz

quantum-viz.js (or qviz) is a configurable tool for rendering quantum circuits. With the increasing demand for quantum libraries and educational tools, quantum circuits provide an intuitive way to visualize and understand quantum algorithms. quantum-viz.js is a lightweight library that can be easily integrated into any project. It aims to be easily configurable while allowing complex user interactions, such as toggling between different measurement outcomes.

Getting Started

Installation

Include quantum-viz.js in your HTML page by using it directly from CDN:

<script src="https://unpkg.com/@microsoft/quantum-viz.js"></script>

or import it in into your TypeScript package:

npm i @microsoft/quantum-viz.js

Usage

  1. Create a Circuit JavaScript object (the Circuit schema is documented here):
const sampleCircuit = {
    qubits: [
        // ...
    ],
    operations: [
        // ...
    ],
};
  1. Draw it in a div:
const sampleDiv = document.getElementById('sample');
qviz.draw(sampleCircuit, sampleDiv, qviz.STYLES['Default']);

Refer to the example folder for an example on how to use quantum-viz.js. Notice that in order to open the contents of this folder in a browser you will need first to install from source (see below).

Python usage

To use this package with Python, use quantum-viz.

Running from source

Installing

To build and install this project from source, run the following commands from the root folder of this repository:

# Install dependencies
> npm install
# Build
> npm run build:prod

Running tests

To run tests for this project, run the following commands:

# Installs dependencies (run this step if you haven't)
> npm install
# Starts Jest tests
> npm run test

Contributing

Check out our contributing guidelines to find out how you can contribute to quantum-viz.js!

Feedback

If you have feedback about this library, please let us know by filing a new issue!

Reporting Security Issues

Security issues and bugs should be reported privately, via email, to the Microsoft Security Response Center (MSRC) at [email protected]. You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Further information, including the MSRC PGP key, can be found in the Security TechCenter.

Trademarks

This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow Microsoft's Trademark & Brand Guidelines. Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party's policies.

Code of Conduct

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

quantum-viz.js's People

Contributors

aaronthangnguyen avatar anpaz avatar dependabot[bot] avatar jond01 avatar microsoft-github-policy-service[bot] avatar theroughcode 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

Watchers

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

quantum-viz.js's Issues

ACTION REQUIRED: Microsoft needs this private repository to complete compliance info

There are open compliance tasks that need to be reviewed for your quantum-viz.js repo.

Action required: 4 compliance tasks

To bring this repository to the standard required for 2021, we require administrators of this and all Microsoft GitHub repositories to complete a small set of tasks within the next 60 days. This is critical work to ensure the compliance and security of your microsoft GitHub organization.

Please take a few minutes to complete the tasks at: https://repos.opensource.microsoft.com/orgs/microsoft/repos/quantum-viz.js/compliance

  • The GitHub AE (GitHub inside Microsoft) migration survey has not been completed for this private repository
  • No Service Tree mapping has been set for this repo. If this team does not use Service Tree, they can also opt-out of providing Service Tree data in the Compliance tab.
  • No repository maintainers are set. The Open Source Maintainers are the decision-makers and actionable owners of the repository, irrespective of administrator permission grants on GitHub.
  • Classification of the repository as production/non-production is missing in the Compliance tab.

You can close this work item once you have completed the compliance tasks, or it will automatically close within a day of taking action.

If you no longer need this repository, it might be quickest to delete the repo, too.

GitHub inside Microsoft program information

More information about GitHub inside Microsoft and the new GitHub AE product can be found at https://aka.ms/gim or by contacting [email protected]

FYI: current admins at Microsoft include @matthiastroyer, @george-moussa, @guenp, @msoeken, @guanghaolow, @jgukelberger, @cesarzc, @cgranade, @jenshnielsen, @johnazariah, @vadym-kl, @rmshaffer, @apaetz

Closing a parent operation leaves the children closed with a minus (-) sign

Describe the bug
When there is a nested circuit - an operation within an operation, and both are open, closing the top operation keeps the inner one semi-open.
After reopening the top operation, the inner one is with a minus sign (-) - as an open operation, but it is actually closed.

To Reproduce
Steps to reproduce the behavior:

  1. Open the example in the repository, also here:
    https://observablehq.com/@anpaz/quantum?ui=classic
    Specifically, focus on the last example (Grover search).
  2. Click on the plus (+) of the first "GroverIteration (Oracle)" operation.
  3. Keep the previous operation open and close the topmost "GroverSearch" operation.
  4. Open the top operation. The previously opened operation is closed but presented with a minus (-).

Expected behavior
I would expect one of the two:

  1. Closing with children reset: closing a parent (or a grandparent) closes all its children and indirect grand-children. Reopening the parent appropriately presents the children closed with a (+) sign.
  2. Closing with memory: when closing and reopening a parent operation, the previous state of its children is kept intact. In the above example, "GroverIteration (Oracle)" should be visually open at step 4.

Screenshots

  1. image
  2. image
  3. image
  4. image

Edit:
This issue is connected to #17.

Enable `forceConsistentCasingInFileNames` in `tsconfig.json`

Is your feature request related to a problem? Please describe.
Microsoft Edge Tools recommend this setting to reduce issues when working with different OSes.

Describe the solution you'd like

// tsconfig.json
{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "lib": [
            "DOM",
            "ES2019",
        ],
        "declaration": true,
        "strict": true,
        "outDir": "lib",
        "forceConsistentCasingInFileNames": true
    },
    "include": [
        "src/**/*"
    ]
}

Describe alternatives you've considered
No change.

Additional context
Screen Shot 2022-05-19 at 12 42 51 PM

Post-selected measurement gates and state preparation gates

Is your feature request related to a problem? Please describe.
In some areas of quantum computing it is common to use post-selected measurement gates to explain
why a circuit works when all measurement outcomes are zero and then proceed to explaining a circuit
for a general case. I would like to be able to visualize such circuits with quantum-viz.js.

Describe the solution you'd like
I would like post-selected Pauli measurement gates to be available as basic gates.

Describe alternatives you've considered
Ability for a user to add custom one, two and multiple-qubit gates with custom drawing of the gates.

Additional context
Below are examples of the gates that would be nice to have
image

Empty parent gates should be removed

Describe the bug
When the last operation is removed from a group, the group collapses and can't be removed/fixed

To Reproduce
Steps to reproduce the behavior:

  1. Drag gate H outside
  2. Drag gate RX outside
  3. Gate Foo is still visible

Expected behavior
Should remove the group all together if there are no more gates left.

Screenshots
Screen Shot 2022-07-07 at 7 17 25 PM

No support for dragging gate inside of classically-controlled group

Describe the bug
No support for dragging gate inside of classically-controlled group

To Reproduce
Steps to reproduce the behavior:

  1. Drag Measure into classically-controlled group
  2. Try to drag Measure out of group
  3. Nothing happens

Expected behavior
Should be able to drag Measure gate in / out of classically-controlled group

Screenshots
Screen Shot 2022-07-07 at 6 25 09 PM

Add consumer-facing tests

It would be nice to have consumer-facing tests that tests the compiled code in a sample TypeScript project or JS code. This could be an end-to-end test that imports qviz and includes some tests to make sure all components of package are exported as expected.

Jupyter widget fails on Python 3.9

Describe the bug

With Python 3.9, I get an error when trying to open the qviz widget on a Jupyter Notebook in the dev environment.

To Reproduce

I followed the steps in the CONTRIBUTING.md, namely install the dev environment using poetry:

pip install poetry nox nox-poetry
poetry install

Then, installed Jupyter Notebook with:

 pip install notebook

During installation I see the versions of traitlets an ipython replaced, since the latest version of notebook for Python 3.9 requires a newer, incompatible, version:

 nbclient, ipykernel, argon2-cffi, nbconvert, notebook
  Attempting uninstall: traitlets
    Found existing installation: traitlets 4.3.3
    Uninstalling traitlets-4.3.3:
      Successfully uninstalled traitlets-4.3.3
  Attempting uninstall: ipython
    Found existing installation: ipython 7.16.1
    Uninstalling ipython-7.16.1:
      Successfully uninstalled ipython-7.16.1
ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
quantum-viz 0.0.0 requires ipython<8.0.0, but you have ipython 8.3.0 which is incompatible.

After installing, I tried opening any of the notebooks in quantum-viz/examples, I get this error:

---------------------------------------------------------------------------
VarnameRetrievingError                    Traceback (most recent call last)
Input In [3], in <cell line: 1>()
----> 1 Viewer(bell)

File C:\Repos\quantum-viz.js\quantum-viz\quantum_viz\widget.py:59, in Viewer.__init__(self, circuit, width, height)
     48 """
     49 Create Viewer instance.
     50 
   (...)
     56 :type height: int, optional
     57 """
     58 try:
---> 59     self.name = varname()
     60 except ImproperUseError:
     61     self.name = "_"

Expected behavior
The widget should work fine with Python 3.9

Screenshots
image

Additional context
Add any other context about the problem here. e.g.

  • OS: windows
  • Python: 3.9
  • ipython = 8.3.0

trace magic keyword and jupyter horizontal scrolling

I'm troubleshooting an issue observed with %trace keyword and my jupyter installation with the Q# kernel, namely -- I can't seem to get horizontal scrolling to work appropriately.

image
image


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

Widget fails to render in jupyter notebook

Describe the bug
Widget not rendering in jupyter notebook

To Reproduce
Steps to reproduce the behaviour:

  1. Create new virtual environment
  2. Install jupyter notebook (pip install jupyter)
  3. Install quantum-viz (pip install quantum-viz)
  4. Re-activate venv (to ensure correct jupyter executable selected)
  5. Run jupyter notebook
  6. (In browser) create new notebook
  7. Copy and paste example code from here
  8. Execute cell

Expected behavior
An in-notebook visualisation of the quantum-viz.js widget.

Screenshots
Screenshot 2022-06-21 at 21 01 58

Additional context
Add any other context about the problem here. e.g.

  • OS: Mac OSX 12.4 (running on M1 Apple silicon)
  • Python version: 3.10.0
  • pip list:
Package              Version
-------------------- -----------
appnope              0.1.3
argon2-cffi          21.3.0
argon2-cffi-bindings 21.2.0
asttokens            2.0.5
attrs                21.4.0
backcall             0.2.0
beautifulsoup4       4.11.1
bleach               5.0.0
cffi                 1.15.0
click                8.1.3
debugpy              1.6.0
decorator            5.1.1
defusedxml           0.7.1
entrypoints          0.4
executing            0.8.3
fastjsonschema       2.15.3
ipykernel            6.15.0
ipython              7.28.0
ipython-genutils     0.2.0
ipywidgets           7.7.0
jedi                 0.18.1
Jinja2               3.1.2
jsonschema           4.6.0
jupyter              1.0.0
jupyter-client       7.3.4
jupyter-console      6.4.3
jupyter-core         4.10.0
jupyterlab-pygments  0.2.2
jupyterlab-widgets   1.1.0
MarkupSafe           2.1.1
matplotlib-inline    0.1.3
mistune              0.8.4
nbclient             0.6.4
nbconvert            6.5.0
nbformat             5.4.0
nest-asyncio         1.5.5
notebook             6.4.11
packaging            21.3
pandocfilters        1.5.0
parso                0.8.3
pexpect              4.8.0
pickleshare          0.7.5
pip                  22.0.4
prometheus-client    0.14.1
prompt-toolkit       3.0.29
psutil               5.9.1
ptyprocess           0.7.0
pure-eval            0.2.2
pycparser            2.21
Pygments             2.12.0
pyparsing            3.0.9
pyrsistent           0.18.1
python-dateutil      2.8.2
pyzmq                23.2.0
qtconsole            5.3.1
QtPy                 2.1.0
quantum-viz          1.0.4
Send2Trash           1.8.0
setuptools           62.3.2
six                  1.16.0
soupsieve            2.3.2.post1
stack-data           0.3.0
terminado            0.15.0
tinycss2             1.1.1
tornado              6.1
traitlets            5.3.0
varname              0.8.3
wcwidth              0.2.5
webencodings         0.5.1
wheel                0.37.1
widgetsnbextension   3.6.0

Need to automate release

Currently the process to release new packages versions are:

  1. Verify GitHub actions run successfully in main
  2. Verify package version numbers match new release number:
  3. Create a new tag (using v[version-number] convention)
  4. Build and validate all components
  5. Create a new GitHub Release
  6. Manually publish to pypi.org and npm
    • For Python: cd quantum-viz; poetry build; twine upload dist/*
    • For Typescript: npm login; npm publish --access public
  7. Update version numbers to reflect next version.

This should all be automated by some GitHub action.

Top level gates should be expanded by default

If the circuit has only one top-level gate, this gate should be expanded by default. This is a common scenario for Q# generated operations.

For example, if a circuit has:
image

It should automatically expand to:
image

Sample circuit is incorrectly rendered

The sample circuit is incorrectly rendered such that the operation Foo is already expanded on first render. Furthermore, hovering over the group shows a + icon instead of -.

We should investigate this behaviour and fix it.

image

`canvas` causes error at installation

Describe the bug
A dependency in devDependencies causes error at installation

To Reproduce
Steps to reproduce the behavior:

  1. Run npm install
  2. See error

Expected behavior
Command should run without any errors

Causes

Screenshots
Screen Shot 2022-05-17 at 6 25 42 PM

Additional context

  • OS: MacBook Pro M1 Max, Surface Book 2

Expand / collapse of composed gates not persist when dragging any gate

Describe the bug
The collapse/expanded state of a group is lost once the circuit is rendered again after modifying.

To Reproduce
Steps to reproduce the behavior:

  1. Collapse gate Foo
  2. Drag any gate
  3. Gate Foo is expanded

Expected behavior
Gate Foo should remain collapsed

Screenshots
2022-07-07 19 27 11

State visualization

Is your feature request related to a problem? Please describe.
Currently, qviz shows only the operations of a quantum program. One key feature is the ability to group operations and expand them to make the program easier to understand.
Another tool that could greatly help developers to visualize a quantum program would be the ability to easily compare the state of the quantum system before and after each operation; this would greatly help in visualizing the effect of each operation.

Describe the solution you'd like
This is a very rough draft of what I have in mind:
image

Namely, you can select any gate and show the before/after state of the system.

How we represent state is very important: we need to come up with a scalable way to represent a state for many qubits (it's easy when it's 2 but becomes complicated when it's 10+). Ideally, is something that should quickly tell users what's the value we get with the highest probability when measured, and how is the phase affected. In the mock, the top basis state vectors are shown with their size proportional to their probability. It also shows the phase of these top basis state vectors and a histogram with all the probabilities.

Rename Sqore to QuantumViz

We want to rename the project from its original name of "Sqore" to "QuantumViz" or "qviz".
This involves renaming function names, documentation, etc.

Invisible gate for idles/no-ops

Is your feature request related to a problem? Please describe.
I would like to draw a circuit that has distinct timesteps at which certain operations are applied. Currently, if there is no operation on a qubit at a certain timestep, the next operation for that qubit is graphed immediately after the last operation.

For example:
Here is a circuit I drew using quantum-viz. The intended circuit was:

  • Hadamard(0) at timestep 0
  • Hadamard(1) at timestep 1
  • ControlledX(0, 1) at timestep 2
  • Measurement(0) at timestep 3

The drawn circuit more appropriately describes:

  • Hadamard(0) at timestep 0
  • Hadamard(1) at timestep 0
  • ControlledX(0, 1) at timestep 1
  • Measurement(0) at timestep 2

image

Describe the solution you'd like
I would like to be able to use an "invisible gate" (an idle/no-op) that simply leaves a blank line where an operation would go. This would be like the identity operators used below, except that it would not be visible. Of course, the line indicating the qubit would still be there - ideally, it would look exactly like the line for qubit 1 below the measurement in the image above.

Describe alternatives you've considered
Here is the same circuit as above with idles (identity operators) where I would like spaces:
image

Though this fix is okay for small circuits, it clutters the visual and makes circuits difficult to read. It would be very nice if I could replace these idles with an "invisible" gate.

OpenQASM support

Is your feature request related to a problem? Please describe.
It would be great if we could visualize an OpenQASM circuit using q-viz.

Describe the solution you'd like
Ideally this would all work using just javascript. We would have a javascript method that takes OpenQASM as a string, and parse it into a Sqore that can then be visualized. For example:

const teleport = `
    // quantum teleportation example
    OPENQASM 2.0;
    include "qelib1.inc";
    qreg q[3];
    creg c0[1];
    creg c1[1];
    creg c2[1];
    // optional post-rotation for state tomography
    gate post q { }
    u3(0.3,0.2,0.1) q[0];
    h q[1];
    cx q[1],q[2];
    barrier q;
    cx q[0],q[1];
    h q[0];
    measure q[0] -> c0[0];
    measure q[1] -> c1[0];
    if(c0==1) z q[2];
    if(c1==1) x q[2];
    post q[2];
    measure q[2] -> c2[0];
`;
const circuit = parse(teleport);
qviz.draw(circuit, sampleDiv, qviz.STYLES['Default']);

For OpenQASM 3.0, we might need to do something similar to what we do with Q#, i.e. run a trace of the program and generate the json from the corresponding gates.

displayArgs for measurements

Describe the bug
Display arguments are not displayed for measurements.

To Reproduce
Steps to reproduce the behavior:

  1. Use the following circuit:
    'qubits': [ {'id': 0, 'numChildren': 1}, {'id': 1, 'numChildren': 1} ], 'operations': [{ 'gate': 'MZZ', 'displayArgs': 'arg', 'isMeasurement': 'True', 'isControlled': 'True', 'controls': [{'qId': 0}], 'targets': [{'qId': 1}] }]
  2. Display the circuit:
    widget = Viewer(circuit) widget._ipython_display_()
  3. See error (I believe this error persists for CNOTs as well).

Expected behavior
I expected to see the requested arguments displayed for the operation.

Screenshots
In this image, I input displayArgs = "arg" for each operation.
MicrosoftTeams-image (1)

Additional context

  • OS: windows

Improve API

Our current API for the package looks like this:

const sampleCircuit = {
    qubits: [
        // ...
    ],
    operations: [
        // ...
    ],
};
const sampleDiv = document.getElementById('sample');
qviz.draw(sampleCircuit, sampleDiv, qviz.STYLES['Default']);

A few things that would make for a good interface are:

  1. Easy to use
  2. Customizable (i.e. style, interactivity, custom augmentations)
  3. Easy to read

A good example of an interface that we can draw inspiration from is d3.js:

d3.select("body")
  .selectAll("p")
  .data([4, 8, 15, 16, 23, 42])
  .enter().append("p")
    .text(function(d) { return "I’m number " + d + "!"; });

We can select a DOM element, add data to it, and customize it. A similar API for Sqore would work really well.

SWAP gate support

Is your feature request related to a problem? Please describe.
It would be great and useful if you could add the SWAP gate in the qviz.

Describe the solution you'd like
You may add an attribute "isSWAP" to the Operation Properties.

Cirq support

Is your feature request related to a problem? Please describe.
It would be nice to have a way to generate qviz's json from a Cirq circuit object.

Describe the solution you'd like
Something on the lines of adding a creating a convert_to_qviz() method that takes a Cirq's Circuit object and returns a dictionary/ojbect that can be serialized to the json that qviz supports. For example:

import json
import cirq

from quantum_viz import convert_to_qviz

# Create qubits
q0 = cirq.LineQubit(0)
q1 = cirq.LineQubit(1)
q2 = cirq.LineQubit(2)

# Create a circuit
circuit = cirq.Circuit(
    cirq.H(q0),  # H gate
    cirq.CNOT(q0, q1),
    cirq.CNOT(q1, q2),
    cirq.measure(q0, key='q0'),
    cirq.measure(q1, key='q1'),
    cirq.measure(q2, key='q2'),
)

qviz = convert_to_qviz(circuit)
print(json.dumps(qviz))

QIR support

Is your feature request related to a problem? Please describe.
It would be nice to have a way to generate qviz's json from the trace of a QIR program.

Describe the solution you'd like
Something on the lines of how we generate the json of a Q# program, i.e., use a tracer to identify the gates that might be executed on a QIR program and serialize this trace on the json expected by qviz.

Write up schema for qviz JSON

It would be helpful to document what the input schema should look like so that users can create their own inputs.

This will also be helpful to create qviz objects from other packages such as Q# and Qiskit.

Qiskit support

Is your feature request related to a problem? Please describe.
It would be nice to have a way to generate qviz's json from a Qiskit QuantumCircuit object.

Describe the solution you'd like
Something on the lines of adding a creating a convert_to_qviz() method that takes a Qiskit's Circuit object and returns a dictionary/ojbect that can be serialized to the json that qviz supports. For example:

import json

from qiskit import QuantumCircuit
from quantum_viz import convert_to_qviz

circuit = QuantumCircuit(2, 2)
circuit.name = "Qiskit Sample - Bell circuit"
circuit.h(0)
circuit.cx(0, 1)
circuit.measure([0,1], [0, 1])

qviz = convert_to_qviz(circuit)
print(json.dumps(qviz))

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.