Skip to content

Commit

Permalink
Add python bindings for loading guppy jsons
Browse files Browse the repository at this point in the history
  • Loading branch information
aborgna-q committed Jun 10, 2024
1 parent 57737cc commit 1901d6c
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
18 changes: 13 additions & 5 deletions tket2-py/src/circuit/tk2circuit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,15 @@ impl Tk2Circuit {
Ok(Tk2Circuit { circ: hugr.into() })
}

/// Load a function from a compiled guppy module, encoded as a json string.
#[staticmethod]
pub fn from_guppy_json(json: &str, function: &str) -> PyResult<Self> {
let circ = tket2::serialize::load_guppy_json_str(json, function).map_err(|e| {
PyErr::new::<PyAttributeError, _>(format!("Invalid encoded circuit: {e}"))
})?;
Ok(Tk2Circuit { circ })
}

/// Encode the circuit as a tket1 json string.
pub fn to_tket1_json(&self) -> PyResult<String> {
Ok(serde_json::to_string(&SerialCircuit::encode(&self.circ).convert_pyerrs()?).unwrap())
Expand All @@ -106,11 +115,10 @@ impl Tk2Circuit {
/// Decode a tket1 json string to a circuit.
#[staticmethod]
pub fn from_tket1_json(json: &str) -> PyResult<Self> {
let tk1: SerialCircuit = serde_json::from_str(json)
.map_err(|e| PyErr::new::<PyAttributeError, _>(format!("Invalid encoded HUGR: {e}")))?;
Ok(Tk2Circuit {
circ: tk1.decode().convert_pyerrs()?,
})
let circ = tket2::serialize::load_tk1_json_str(json).map_err(|e| {
PyErr::new::<PyAttributeError, _>(format!("Could not load pytket circuit: {e}"))
})?;
Ok(Tk2Circuit { circ })
}

/// Compute the cost of the circuit based on a per-operation cost function.
Expand Down
4 changes: 4 additions & 0 deletions tket2-py/tket2/_tket2/circuit.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@ class Tk2Circuit:
def to_tket1_json(self) -> str:
"""Encode the circuit as a pytket json string."""

@staticmethod
def from_guppy_json(json: str, function: str) -> Tk2Circuit:
"""Load a function from a compiled guppy module, encoded as a json string."""

@staticmethod
def from_tket1_json(json: str) -> Tk2Circuit:
"""Decode a pytket json string to a Tk2Circuit."""
Expand Down

0 comments on commit 1901d6c

Please sign in to comment.