-
Notifications
You must be signed in to change notification settings - Fork 6
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
feat: Python bindings for TASO #142
Changes from 6 commits
d068c3b
b158bcf
b7dd79c
8c22a9f
5681cef
98e8ccf
ee4fb54
9b3f9bb
5016d66
ba838a0
45f26cd
e8c1468
cacd27a
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
This file was deleted.
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
use std::fs; | ||
use std::path::Path; | ||
use std::process::exit; | ||
use std::time::Instant; | ||
|
||
use clap::Parser; | ||
|
||
use tket2::rewrite::ECCRewriter; | ||
|
||
/// Program to precompile patterns from files into a PatternMatcher stored as binary file. | ||
#[derive(Parser, Debug)] | ||
#[clap(version = "1.0", long_about = None)] | ||
#[clap( | ||
about = "Precompiles ECC sets into a TKET2 Rewriter. The resulting binary files can be loaded into TKET2 for circuit optimisation." | ||
)] | ||
struct CmdLineArgs { | ||
// TODO: Differentiate between TK1 input and ECC input | ||
/// Name of input file/folder | ||
#[arg( | ||
short, | ||
long, | ||
value_name = "FILE", | ||
help = "Sets the input file to use. It must be a JSON file of ECC sets in the Quartz format." | ||
)] | ||
input: String, | ||
/// Name of output file/folder | ||
#[arg( | ||
short, | ||
long, | ||
value_name = "FILE", | ||
default_value = ".", | ||
help = "Sets the output file or folder. Defaults to \"matcher.rwr\" if no file name is provided. The extension of the file name will always be set or amended to be `.rwr`." | ||
)] | ||
output: String, | ||
} | ||
|
||
fn main() { | ||
let opts = CmdLineArgs::parse(); | ||
|
||
let input_path = Path::new(&opts.input); | ||
let output_path = Path::new(&opts.output); | ||
|
||
if !input_path.is_file() || input_path.extension().unwrap() != "json" { | ||
panic!("Input must be a JSON file"); | ||
}; | ||
let start_time = Instant::now(); | ||
println!("Compiling rewriter..."); | ||
let Ok(rewriter) = ECCRewriter::try_from_eccs_json_file(input_path) else { | ||
eprintln!( | ||
"Unable to load ECC file {:?}. Is it a JSON file of Quartz-generated ECCs?", | ||
input_path | ||
); | ||
exit(1); | ||
}; | ||
println!("Saving to file..."); | ||
let output_file = if output_path.is_dir() { | ||
output_path.join("matcher.rwr") | ||
} else { | ||
output_path.to_path_buf() | ||
}; | ||
let output_file = rewriter.save_binary(output_file.to_str().unwrap()).unwrap(); | ||
println!("Written rewriter to {:?}", output_file); | ||
|
||
// Print the file size of output_file in megabytes | ||
if let Ok(metadata) = fs::metadata(&output_file) { | ||
let file_size = metadata.len() as f64 / (1024.0 * 1024.0); | ||
println!("File size: {:.2} MB", file_size); | ||
} | ||
let elapsed = start_time.elapsed(); | ||
println!( | ||
"Done in {}.{:03} seconds", | ||
elapsed.as_secs(), | ||
elapsed.subsec_millis() | ||
); | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
//! PyO3 wrapper for the TASO optimiser. | ||
|
||
use std::{fs, num::NonZeroUsize}; | ||
|
||
use pyo3::{exceptions::PyTypeError, prelude::*}; | ||
use tket_json_rs::circuit_json::SerialCircuit; | ||
|
||
use crate::{json::TKETDecode, utils::pyobj_as_hugr}; | ||
|
||
use super::{log::TasoLogger, DefaultTasoOptimiser}; | ||
|
||
/// Wrapped [`DefaultTasoOptimiser`]. | ||
/// | ||
/// Currently only exposes loading from an ECC file using the constructor | ||
/// and optimising using default logging settings. | ||
#[pyclass(name = "TasoOptimiser")] | ||
pub struct PyDefaultTasoOptimiser(DefaultTasoOptimiser); | ||
|
||
#[pymethods] | ||
impl PyDefaultTasoOptimiser { | ||
/// Create a new [`PyDefaultTasoOptimiser`] from a precompiled rewriter. | ||
#[staticmethod] | ||
pub fn load_precompiled(path: &str) -> Self { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I believe you can use Path or PathBuf objects and they will be mapped to python pathlib.Path There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Awesome! It seems I need to pass a |
||
Self(DefaultTasoOptimiser::default_with_rewriter_binary(path).unwrap()) | ||
} | ||
|
||
/// Create a new [`PyDefaultTasoOptimiser`] 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()) | ||
} | ||
|
||
/// Run the optimiser on a circuit. | ||
/// | ||
/// Returns an optimised circuit and log the progress to a CSV | ||
/// file called "best_circs.csv". | ||
pub fn optimise( | ||
&self, | ||
circ: PyObject, | ||
timeout: Option<u64>, | ||
n_threads: Option<NonZeroUsize>, | ||
) -> PyResult<PyObject> { | ||
let circ = pyobj_as_hugr(circ)?; | ||
let circ_candidates_csv = fs::File::create("best_circs.csv").unwrap(); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. make this path a (optional?) function parameter? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. For sure, done. |
||
|
||
let taso_logger = TasoLogger::new(circ_candidates_csv); | ||
let opt_circ = self.0.optimise_with_log( | ||
&circ, | ||
taso_logger, | ||
timeout, | ||
n_threads.unwrap_or(NonZeroUsize::new(1).unwrap()), | ||
); | ||
let ser_circ = | ||
SerialCircuit::encode(&opt_circ).map_err(|e| PyTypeError::new_err(e.to_string()))?; | ||
let tk1_circ = ser_circ | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. you should be able to use There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Turns out: had never known about the goodness in this file! I had to move the |
||
.to_tket1() | ||
.map_err(|e| PyTypeError::new_err(e.to_string()))?; | ||
Ok(tk1_circ) | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
git doesn't seem to have picked up this rename
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think it's because there were too many changes, so it views it as a new file. Can I do anything about it? Pretty sure I
git mv
ed it.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
no don't worry