Skip to content

Commit

Permalink
Add: durations method for Target
Browse files Browse the repository at this point in the history
- Add target module to qiskit init file.
- Remove is_instance method.
- Modify set_calibration method in InstructionProperty to leave typechecking to Python.
- Change rust Target alias to Target2.
- Other tweaks and fixes,
  • Loading branch information
raynelfss committed Apr 10, 2024
1 parent 28e2e01 commit 1f9bdbf
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 50 deletions.
69 changes: 21 additions & 48 deletions crates/accelerate/src/target.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,23 +21,6 @@ use pyo3::{
types::{PyDict, PyTuple},
};

// TEMPORARY: until I can wrap around Python class
pub fn is_instance(py: Python<'_>, object: &PyObject, class_names: HashSet<String>) -> bool {
// Get type name
let type_name: Option<String> = match object.getattr(py, "__class__").ok() {
Some(class) => class
.getattr(py, "__name__")
.ok()
.map(|name| name.extract::<String>(py).ok().unwrap_or("".to_string())),
None => None,
};
// Check if it matches any option
match type_name {
Some(class_name) => class_names.contains(&class_name),
None => false,
}
}

#[derive(Eq, PartialEq, Clone, Debug)]
struct HashableVec<T> {
pub vec: Vec<T>,
Expand Down Expand Up @@ -91,36 +74,25 @@ impl InstructionProperties {
}

#[setter]
pub fn set_calibration(&mut self, py: Python<'_>, calibration: PyObject) {
// Conditional new entry
let new_entry = if is_instance(
py,
&calibration,
HashSet::from(["Schedule".to_string(), "ScheduleBlock".to_string()]),
) {
// TEMPORARY: Import calibration_entries module
let module = match py.import_bound("qiskit.pulse.calibration_entries") {
Ok(module) => module,
Err(e) => panic!(
"Could not find the module qiskit.pulse.calibration_entries: {:?}",
e
),
};
// TEMPORARY: Import SchedDef class object
let sched_def = match module.call_method0("ScheduleDef") {
Ok(sched) => sched.to_object(py),
Err(e) => panic!("Failed to import the 'ScheduleDef' class: {:?}", e),
};
pub fn set_calibration(&mut self, calibration: PyObject) -> PyResult<()> {
self.calibration_ = Some(calibration);
Ok(())
}

// TEMPORARY: Send arguments for the define call.
let args = (&calibration, true);
// Peform the function call.
sched_def.call_method1(py, "define", args).ok();
sched_def
fn __repr__(&self, py: Python<'_>) -> String {
if let Some(calibration) = self.get_calibration(py) {
format!(
"InstructionProperties(duration={:?}, error={:?}, calibration={:?})",
self.duration,
self.error,
calibration.call_method0(py, "__repr__")
)
} else {
calibration
};
self.calibration_ = Some(new_entry);
format!(
"InstructionProperties(duration={:?}, error={:?}, calibration=None)",
self.duration, self.error
)
}
}
}

Expand Down Expand Up @@ -151,7 +123,8 @@ pub struct Target {
gate_name_map: HashMap<String, PyObject>,
global_operations: HashMap<usize, HashSet<String>>,
qarg_gate_map: HashMap<HashableVec<u32>, HashSet<String>>,
instructions_durations: Option<PyObject>,
#[pyo3(get, set)]
instruction_durations: Option<PyObject>,
instruction_schedule_map: Option<PyObject>,
}

Expand Down Expand Up @@ -192,7 +165,7 @@ impl Target {
gate_name_map: HashMap::new(),
global_operations: HashMap::new(),
qarg_gate_map: HashMap::new(),
instructions_durations: Option::None,
instruction_durations: Option::None,
instruction_schedule_map: Option::None,
}
}
Expand Down Expand Up @@ -339,7 +312,7 @@ impl Target {
*qvals_qargs = properties
}
}
self.instructions_durations = None;
self.instruction_durations = None;
self.instruction_schedule_map = None;
Ok(())
}
Expand Down
1 change: 1 addition & 0 deletions qiskit/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@
qiskit._accelerate.convert_2q_block_matrix
)
sys.modules["qiskit._accelerate.two_qubit_decompose"] = qiskit._accelerate.two_qubit_decompose
sys.modules["qiskit._accelerate.target"] = qiskit._accelerate.target

# qiskit errors operator
from qiskit.exceptions import QiskitError, MissingOptionalLibraryError
Expand Down
21 changes: 19 additions & 2 deletions qiskit/transpiler/_target.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@
from qiskit.providers.models.backendproperties import BackendProperties

# import target class from the rust side
from qiskit._accelerate import target
from qiskit._accelerate.target import Target as Target2

# TODO: Use InstructionProperties from Python side
from qiskit.transpiler.target import InstructionProperties
Expand All @@ -75,7 +75,7 @@ def __init__(
qubit_properties=None,
concurrent_measurements=None,
):
self._Target = target.Target(
self._Target = Target2(
description,
num_qubits,
dt,
Expand Down Expand Up @@ -352,3 +352,20 @@ def qargs_for_operation_name(self, operation):
set: The set of qargs the gate instance applies to.
"""
return self._Target.qargs_for_operation_name(operation)

def durations(self):
"""Get an InstructionDurations object from the target
Returns:
InstructionDurations: The instruction duration represented in the
target
"""
if self._Target.instruction_durations is not None:
return self._instruction_durations
out_durations = []
for instruction, props_map in self._Target.gate_map.items():
for qarg, properties in props_map.items():
if properties is not None and properties.duration is not None:
out_durations.append((instruction, list(qarg), properties.duration, "s"))
self._Target.instruction_durations = InstructionDurations(out_durations, dt=self.dt)
return self._Target.instruction_durations

0 comments on commit 1f9bdbf

Please sign in to comment.