Skip to content

Commit

Permalink
Merge pull request #80 from chensgit169/master
Browse files Browse the repository at this point in the history
Replace ``pygraphviz`` with ``graphviz``
  • Loading branch information
Zhaoyilunnn authored Sep 13, 2023
2 parents 3a1ef2c + fc71e32 commit d6ea733
Show file tree
Hide file tree
Showing 9 changed files with 72 additions and 93 deletions.
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)
6 changes: 1 addition & 5 deletions quafu/tasks/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,8 +187,7 @@ def send(self,
qc: QuantumCircuit,
name: str = "",
group: str = "",
wait: bool = True,
verbose: bool = False,
wait: bool = True
) -> ExecResult:
"""
Run the circuit on experimental device.
Expand All @@ -198,7 +197,6 @@ def send(self,
name: Task name.
group: The task belong which group.
wait: Whether wait until the execution return.
verbose:
Returns:
ExecResult object that contain the dict return from quantum device.
"""
Expand Down Expand Up @@ -253,9 +251,7 @@ def send(self,
raise UserError()
else:
res_dict = response.json()
import pprint

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

0 comments on commit d6ea733

Please sign in to comment.