Skip to content

Commit

Permalink
refactor: s/taso/badger/ (#228)
Browse files Browse the repository at this point in the history
Closes #224
  • Loading branch information
aborgna-q authored Nov 8, 2023
1 parent 036091d commit e8ed5f6
Show file tree
Hide file tree
Showing 20 changed files with 119 additions and 117 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ lto = "thin"

[workspace]
resolver = "2"
members = ["tket2", "tket2-py", "compile-rewriter", "taso-optimiser"]
members = ["tket2", "tket2-py", "compile-rewriter", "badger-optimiser"]
default-members = ["tket2"]

[workspace.package]
Expand Down
2 changes: 1 addition & 1 deletion taso-optimiser/Cargo.toml → badger-optimiser/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[package]
name = "taso-optimiser"
name = "badger-optimiser"
edition = { workspace = true }
version = { workspace = true }
rust-version = { workspace = true }
Expand Down
12 changes: 6 additions & 6 deletions taso-optimiser/src/main.rs → badger-optimiser/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ use std::process::exit;

use clap::Parser;
use tket2::json::{load_tk1_json_file, save_tk1_json_file};
use tket2::optimiser::taso::log::TasoLogger;
use tket2::optimiser::TasoOptimiser;
use tket2::optimiser::badger::log::BadgerLogger;
use tket2::optimiser::BadgerOptimiser;

#[cfg(feature = "peak_alloc")]
#[global_allocator]
Expand Down Expand Up @@ -58,7 +58,7 @@ struct CmdLineArgs {
#[arg(
short,
long,
default_value = "taso-optimisation.log",
default_value = "badger-optimisation.log",
value_name = "LOGFILE",
help = "Logfile to to output the progress of the optimisation."
)]
Expand Down Expand Up @@ -117,12 +117,12 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
// TODO: Remove this from the Logger, and use tracing events instead.
let circ_candidates_csv = BufWriter::new(File::create("best_circs.csv")?);

let taso_logger = TasoLogger::new(circ_candidates_csv);
let badger_logger = BadgerLogger::new(circ_candidates_csv);

let circ = load_tk1_json_file(input_path)?;

println!("Compiling rewriter...");
let Ok(optimiser) = TasoOptimiser::default_with_eccs_json_file(ecc_path) else {
let Ok(optimiser) = BadgerOptimiser::default_with_eccs_json_file(ecc_path) else {
eprintln!(
"Unable to load ECC file {:?}. Is it a JSON file of Quartz-generated ECCs?",
ecc_path
Expand All @@ -141,7 +141,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("Optimising...");
let opt_circ = optimiser.optimise_with_log(
&circ,
taso_logger,
badger_logger,
opts.timeout,
n_threads,
opts.split_circ,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::fs::File;
use std::io::BufWriter;
use std::path::PathBuf;

use tket2::optimiser::taso::log::{LOG_TARGET, METRICS_TARGET, PROGRESS_TARGET};
use tket2::optimiser::badger::log::{LOG_TARGET, METRICS_TARGET, PROGRESS_TARGET};

use tracing::{Metadata, Subscriber};
use tracing_appender::non_blocking;
Expand Down
2 changes: 1 addition & 1 deletion tket2-py/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,5 @@ A clean python 3.10 environment with `maturin` installed. At which point running
`maturin develop` in this directory should build and install the package in the
environment. Run `pytest` in this directory to test everything is working.

Don't forget to use the `--release` flag when using TASO and other heavy
Don't forget to use the `--release` flag when using Badger and other heavy
computational workloads.
30 changes: 15 additions & 15 deletions tket2-py/src/optimiser.rs
Original file line number Diff line number Diff line change
@@ -1,42 +1,42 @@
//! PyO3 wrapper for the TASO circuit optimiser.
//! PyO3 wrapper for the Badger circuit optimiser.
use std::io::BufWriter;
use std::{fs, num::NonZeroUsize, path::PathBuf};

use hugr::Hugr;
use pyo3::prelude::*;
use tket2::optimiser::{DefaultTasoOptimiser, TasoLogger};
use tket2::optimiser::{BadgerLogger, DefaultBadgerOptimiser};

use crate::circuit::update_hugr;

/// The module definition
pub fn module(py: Python) -> PyResult<&PyModule> {
let m = PyModule::new(py, "_optimiser")?;
m.add_class::<PyTasoOptimiser>()?;
m.add_class::<PyBadgerOptimiser>()?;
Ok(m)
}

/// Wrapped [`DefaultTasoOptimiser`].
/// Wrapped [`DefaultBadgerOptimiser`].
///
/// Currently only exposes loading from an ECC file using the constructor
/// and optimising using default logging settings.
#[pyclass(name = "TasoOptimiser")]
pub struct PyTasoOptimiser(DefaultTasoOptimiser);
#[pyclass(name = "BadgerOptimiser")]
pub struct PyBadgerOptimiser(DefaultBadgerOptimiser);

#[pymethods]
impl PyTasoOptimiser {
/// Create a new [`PyDefaultTasoOptimiser`] from a precompiled rewriter.
impl PyBadgerOptimiser {
/// Create a new [`PyDefaultBadgerOptimiser`] from a precompiled rewriter.
#[staticmethod]
pub fn load_precompiled(path: PathBuf) -> Self {
Self(DefaultTasoOptimiser::default_with_rewriter_binary(path).unwrap())
Self(DefaultBadgerOptimiser::default_with_rewriter_binary(path).unwrap())
}

/// Create a new [`PyDefaultTasoOptimiser`] from ECC sets.
/// Create a new [`PyDefaultBadgerOptimiser`] from ECC sets.
///
/// This will compile the rewriter from the provided ECC JSON file.
#[staticmethod]
pub fn compile_eccs(path: &str) -> Self {
Self(DefaultTasoOptimiser::default_with_eccs_json_file(path).unwrap())
Self(DefaultBadgerOptimiser::default_with_eccs_json_file(path).unwrap())
}

/// Run the optimiser on a circuit.
Expand Down Expand Up @@ -79,7 +79,7 @@ impl PyTasoOptimiser {
}
}

impl PyTasoOptimiser {
impl PyBadgerOptimiser {
/// The Python optimise method, but on Hugrs.
pub(super) fn optimise(
&self,
Expand All @@ -90,16 +90,16 @@ impl PyTasoOptimiser {
log_progress: Option<PathBuf>,
queue_size: Option<usize>,
) -> Hugr {
let taso_logger = log_progress
let badger_logger = log_progress
.map(|file_name| {
let log_file = fs::File::create(file_name).unwrap();
let log_file = BufWriter::new(log_file);
TasoLogger::new(log_file)
BadgerLogger::new(log_file)
})
.unwrap_or_default();
self.0.optimise_with_log(
&circ,
taso_logger,
badger_logger,
timeout,
n_threads.unwrap_or(NonZeroUsize::new(1).unwrap()),
split_circ.unwrap_or(false),
Expand Down
16 changes: 8 additions & 8 deletions tket2-py/src/passes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use tket_json_rs::circuit_json::SerialCircuit;

use crate::{
circuit::{try_update_hugr, try_with_hugr},
optimiser::PyTasoOptimiser,
optimiser::PyBadgerOptimiser,
};

/// The module definition
Expand All @@ -15,7 +15,7 @@ use crate::{
pub fn module(py: Python) -> PyResult<&PyModule> {
let m = PyModule::new(py, "_passes")?;
m.add_function(wrap_pyfunction!(greedy_depth_reduce, m)?)?;
m.add_function(wrap_pyfunction!(taso_optimise, m)?)?;
m.add_function(wrap_pyfunction!(badger_optimise, m)?)?;
m.add_class::<tket2::T2Op>()?;
m.add(
"PullForwardError",
Expand Down Expand Up @@ -56,10 +56,10 @@ fn rebase_nam(circ: &PyObject) -> PyResult<()> {
})
}

/// TASO optimisation pass.
/// Badger optimisation pass.
///
/// HyperTKET's best attempt at optimising a circuit using circuit rewriting
/// and the given TASO optimiser.
/// and the given Badger optimiser.
///
/// By default, the input circuit will be rebased to Nam, i.e. CX + Rz + H before
/// optimising. This can be deactivated by setting `rebase` to `false`, in which
Expand All @@ -71,9 +71,9 @@ fn rebase_nam(circ: &PyObject) -> PyResult<()> {
///
/// Log files will be written to the directory `log_dir` if specified.
#[pyfunction]
fn taso_optimise(
fn badger_optimise(
circ: PyObject,
optimiser: &PyTasoOptimiser,
optimiser: &PyBadgerOptimiser,
max_threads: Option<NonZeroUsize>,
timeout: Option<u64>,
log_dir: Option<PathBuf>,
Expand All @@ -92,7 +92,7 @@ fn taso_optimise(
rebase_nam(&circ)?;
}
// Logic to choose how to split the circuit
let taso_splits = |n_threads: NonZeroUsize| match n_threads.get() {
let badger_splits = |n_threads: NonZeroUsize| match n_threads.get() {
n if n >= 7 => (
vec![n, 3, 1],
vec![timeout / 2, timeout / 10 * 3, timeout / 10 * 2],
Expand All @@ -115,7 +115,7 @@ fn taso_optimise(
(n_cx / 50).try_into().unwrap_or(1.try_into().unwrap()),
max_threads,
);
let (split_threads, split_timeouts) = taso_splits(n_threads);
let (split_threads, split_timeouts) = badger_splits(n_threads);
for (i, (n_threads, timeout)) in split_threads.into_iter().zip(split_timeouts).enumerate() {
let log_file = log_dir.as_ref().map(|log_dir| {
let mut log_file = log_dir.clone();
Expand Down
4 changes: 2 additions & 2 deletions tket2-py/test/test_optimiser.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
from pytket import Circuit
from tket2.optimiser import TasoOptimiser
from tket2.optimiser import BadgerOptimiser


def test_simple_optimiser():
"""a simple circuit matching test"""
c = Circuit(3).CX(0, 1).CX(0, 1).CX(1, 2)
opt = TasoOptimiser.compile_eccs("test_files/cx_cx_eccs.json")
opt = BadgerOptimiser.compile_eccs("test_files/cx_cx_eccs.json")

# optimise for 1s
cc = opt.optimise(c, 3)
Expand Down
8 changes: 4 additions & 4 deletions tket2-py/test/test_pass.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from pytket import Circuit, OpType
from tket2.passes import taso_pass
from tket2.passes import badger_pass


def test_simple_taso_pass_no_opt():
def test_simple_badger_pass_no_opt():
c = Circuit(3).CCX(0, 1, 2)
taso = taso_pass(max_threads=1, timeout=0)
taso.apply(c)
badger = badger_pass(max_threads=1, timeout=0)
badger.apply(c)
assert c.n_gates_of_type(OpType.CX) == 6
18 changes: 9 additions & 9 deletions tket2-py/tket2/passes.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,33 +12,33 @@
from .tket2 import _passes

__all__ = [
"taso_pass",
"badger_pass",
*_passes.__all__,
]


def taso_pass(
def badger_pass(
rewriter: Optional[Path] = None,
max_threads: Optional[int] = None,
timeout: Optional[int] = None,
log_dir: Optional[Path] = None,
rebase: Optional[bool] = None,
) -> CustomPass:
"""Construct a TASO pass.
"""Construct a Badger pass.
The Taso optimiser requires a pre-compiled rewriter produced by the
`compile-rewriter <https://github.com/CQCL/tket2/tree/main/taso-optimiser>`_
The Badger optimiser requires a pre-compiled rewriter produced by the
`compile-rewriter <https://github.com/CQCL/tket2/tree/main/badger-optimiser>`_
utility. If `rewriter` is not specified, a default one will be used.
The arguments `max_threads`, `timeout`, `log_dir` and `rebase` are optional
and will be passed on to the TASO optimiser if provided."""
and will be passed on to the Badger optimiser if provided."""
if rewriter is None:
rewriter = Path(importlib.resources.files("tket2").joinpath("data/nam_6_3.rwr"))
opt = optimiser.TasoOptimiser.load_precompiled(rewriter)
opt = optimiser.BadgerOptimiser.load_precompiled(rewriter)

def apply(circuit: Circuit) -> Circuit:
"""Apply TASO optimisation to the circuit."""
return _passes.taso_optimise(
"""Apply Badger optimisation to the circuit."""
return _passes.badger_optimise(
circuit,
opt,
max_threads,
Expand Down
8 changes: 4 additions & 4 deletions tket2/src/optimiser.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
//! Optimisers for circuit rewriting.
//!
//! Currently, the only optimiser is TASO
//! Currently, the only optimiser is Badger
pub mod taso;
pub mod badger;

#[cfg(feature = "portmatching")]
pub use taso::DefaultTasoOptimiser;
pub use taso::{TasoLogger, TasoOptimiser};
pub use badger::DefaultBadgerOptimiser;
pub use badger::{BadgerLogger, BadgerOptimiser};
Loading

0 comments on commit e8ed5f6

Please sign in to comment.