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

Replace pygraphviz with graphviz #80

Merged
merged 15 commits into from
Sep 13, 2023
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pip install -r requirements.txt
python setup.py install
```

Note that pygraphviz requires graphviz being installed on your system. Refer to [pygraphviz documentation](https://pygraphviz.github.io/documentation/stable/install.html) for detailed installation steps.
Note that we visualize DAG(directed acyclic graph) through python package ``graphviz``. And if you need it, make sure [Graphviz software](https://graphviz.org/) being installed on your system. Refer to [graphviz · PyPI](https://pypi.org/project/graphviz/#description) for installation guidance.

## GPU support
To install PyQuafu with GPU-based circuit simulator, you need build from the source and make sure that [CUDA Toolkit](https://developer.nvidia.com/cuda-downloads) is installed. You can run
Expand Down
76 changes: 9 additions & 67 deletions quafu/dagcircuits/circuit_dag.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,18 @@
import numpy as np
from quafu import QuantumCircuit

from quafu.elements.element_gates import *
from quafu.elements.quantum_element import Barrier, Delay, Measure, XYResonance
from quafu.elements.quantum_element.pulses.quantum_pulse import GaussianPulse, RectPulse, FlattopPulse
import copy
from typing import Any, List

import networkx as nx
from typing import Dict, Any, List, Union
import copy

from quafu import QuantumCircuit
from quafu.dagcircuits.dag_circuit import (
DAGCircuit,
) # dag_circuit.py in the same folder as circuit_dag.py now
from quafu.dagcircuits.instruction_node import (
InstructionNode,
) # instruction_node.py in the same folder as circuit_dag.py now
from quafu.dagcircuits.dag_circuit import (
DAGCircuit,
) # dag_circuit.py in the same folder as circuit_dag.py now

# import pygraphviz as pgv
from networkx.drawing.nx_pydot import write_dot
from IPython.display import Image, SVG
from quafu.elements.element_gates import *
from quafu.elements.quantum_element import Barrier, Delay, Measure, XYResonance
from quafu.elements.quantum_element.pulses.quantum_pulse import GaussianPulse, RectPulse, FlattopPulse


# transform a gate in quantumcircuit of quafu(not include measure_gate),
Expand Down Expand Up @@ -340,58 +334,6 @@ def dag_to_circuit(dep_graph, n: int):
return qcircuit


# Helper function to visualize the DAG,check the example in the docstring
def draw_dag(dep_g, output_format="png"):
"""
Helper function to visualize the DAG

Args:
dep_g (DAG): DAG with Hashable Gates
output_format (str): output format, "png" or "svg"

Returns:
img (Image or SVG): show the image of DAG, which is Image(filename="dag.png") or SVG(filename="dag.svg")

example:
.. jupyter-execute::
ex1:
# directly draw PNG picture
draw_dag(dep_g, output_format="png") # save a png picture "dag.png" and show it in jupyter notebook

# directly draw SVG picture
draw_dag(dep_g, output_format="svg") # save a svg picture "dag.svg" and show it in jupyter notebook

ex2:
# generate PNG picture
img_png = draw_dag(dep_g, output_format="png")

# generate SVG picture
img_svg = draw_dag(dep_g, output_format="svg")

# show PNG picture
img_png

# show SVG picture
img_svg


"""
import pygraphviz

write_dot(dep_g, "dag.dot")
G = pygraphviz.AGraph("dag.dot")
G.layout(prog="dot")

if output_format == "png":
G.draw("dag.png")
return Image(filename="dag.png")
elif output_format == "svg":
G.draw("dag.svg")
return SVG(filename="dag.svg")
else:
raise ValueError("Unsupported output format: choose either 'png' or 'svg'")


def nodelist_to_dag(op_nodes: List[Any]) -> DAGCircuit:
# Starting Label Index
i = 0
Expand Down
6 changes: 3 additions & 3 deletions quafu/dagcircuits/dag_circuit.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
from typing import Dict

import networkx as nx
from typing import Dict, Any, List
from networkx.classes.multidigraph import MultiDiGraph

from quafu.dagcircuits.instruction_node import InstructionNode

from networkx.classes.multidigraph import MultiDiGraph


class DAGCircuit(MultiDiGraph):
def __init__(
Expand Down
4 changes: 2 additions & 2 deletions quafu/elements/quantum_element/quantum_gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,13 +253,13 @@ def __init__(cls, name, bases, attrs):


def customize_gate(cls_name: str,
gate_structure: list,
gate_structure: list[Instruction],
qubit_num: int,
):
"""
helper function to create customized gate class
:param cls_name:
:param gate_structure:
:param gate_structure: a list of instruction INSTANCES
:param qubit_num:
:return:
"""
Expand Down
13 changes: 0 additions & 13 deletions quafu/qfasm/qfasm_convertor.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
from quafu.dagcircuits.circuit_dag import node_to_gate
from quafu.dagcircuits.instruction_node import InstructionNode
from quafu.circuits import QuantumCircuit, QuantumRegister
from quafu.elements.quantum_element import Instruction


def qasm_to_circuit(qasm):
Expand Down Expand Up @@ -173,15 +172,3 @@ def qasm2_to_quafu_qc(qc: QuantumCircuit, openqasm: str):
print(
"Warning: All operations after measurement will be removed for executing on experiment"
)


if __name__ == '__main__':
import re

pattern = r"[a-z]"

text = "Hello, world! This is a test."

matches = re.findall(pattern, text)

print(matches)
2 changes: 0 additions & 2 deletions quafu/tasks/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,9 +253,7 @@ def send(self,
raise UserError()
else:
res_dict = response.json()
import pprint
Copy link
Collaborator

Choose a reason for hiding this comment

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

I assume that you want to use the verbose flag to control whether we print response, so you finally decide to remove this now? If so, maybe the verbose flag should be deleted.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Actually I intended to help debug by setting verbose=True, yet it was not completed. Let's delete it for now. By the way I just noticed status_code in two level in master branch were not seperated yet?

Copy link
Collaborator

Choose a reason for hiding this comment

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

I believe this is a mistake I made when I merge stable/0.3 branch into master. When resolving conflicts, I mistakenly removed the change in stable/0.3 branch and kept the master branch change. I will fix this later.


pprint.pprint(res_dict)
if response.status_code in [201, 205]:
raise UserError(res_dict["message"])
elif response.status_code == 5001:
Expand Down
55 changes: 55 additions & 0 deletions quafu/visualisation/draw_dag.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import graphviz

from quafu import QuantumCircuit
from quafu.dagcircuits.circuit_dag import circuit_to_dag
from quafu.dagcircuits.instruction_node import InstructionNode

from typing import Union, Any


def _extract_node_info(node):
if isinstance(node, InstructionNode):
name, label = str(id(node)), str(node)
else:
assert node == -1 or node == float("inf")
name, label = str(node), str(node)
return name, label


def draw_dag(qc: Union[QuantumCircuit, None],
dag: Any = None,
output_format: str = 'pdf',
output_filename: str = 'DAG'):
"""
TODO: complete docstring, test supports for notebook

Helper function to visualize the DAG

Args:
qc (QuantumCircuit): pyquafu quantum circuit if provided
dag (DAG): DAG object with nodes and edges, built from qc if not provided
output_format (str): output format, including "png", "svg", "pdf"...
output_filename (str): file name of generated image

Returns:
dot: graphviz.Digraph object

"""
Zhaoyilunnn marked this conversation as resolved.
Show resolved Hide resolved
if dag is None:
assert qc is not None
dag = circuit_to_dag(qc)

dot = graphviz.Digraph(filename=output_filename)

for node in dag.nodes:
name, label = _extract_node_info(node)
dot.node(name, label=label)

for edge in dag.edges(data=True):
node1, node2, link = edge
name1, label1 = _extract_node_info(node1)
name2, label2 = _extract_node_info(node2)
dot.edge(name1, name2, label=link['label'])

dot.render(format=output_format, cleanup=True)
return dot
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@ setuptools>=58.0.4
sparse>=0.13.0
scikit-build>=0.16.1
pybind11>=2.10.3
pygraphviz>=1.11
graphviz>=0.14.2
ply~=3.11
Pillow~=10.0.0
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
"sparse>=0.13.0",
"scikit-build>=0.16.1",
"pybind11>=2.10.3",
"pygraphviz>=1.11",
"graphviz>=0.14.2",
"ply~=3.11",
"Pillow~=10.0.0"
]
Expand Down