1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
// Copyright © 2021 HQS Quantum Simulations GmbH. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing permissions and
// limitations under the License.
use crate::operations::{Define, InvolveQubits, InvolvedQubits, Operate, Operation, Substitute};
#[cfg(feature = "overrotate")]
use crate::operations::{Rotate, Rotation};
use crate::RoqoqoError;
use qoqo_calculator::Calculator;
#[cfg(feature = "overrotate")]
use std::convert::TryFrom;
use std::ops;
use std::{
collections::{HashMap, HashSet},
usize,
};
use std::{
fmt::{Display, Formatter},
iter::{FromIterator, IntoIterator},
};
/// Represents a quantum circuit in roqoqo.
///
/// In roqoqo, single operations are collected in a circuit to build up a quantum program.
/// Roqoqo circuits are strictly linear sequences of operations.
/// The circuit struct behaves similar to a list and provides several standard
/// functions of a Vec<Operation>, such as len(), is_empty(), get(), iter() and into_iter().
///
/// # Example
///
/// ```
/// use roqoqo::Circuit;
/// use roqoqo::operations::{Operation, RotateX};
/// use qoqo_calculator::CalculatorFloat;
/// // creating circuit
/// let mut circuit = Circuit::new();
/// // adding operation to circuit
/// circuit.add_operation(RotateX::new(0,CalculatorFloat::from(0)));
/// assert_eq!(circuit.len(), 1);
/// // iterating over circuit I
/// let operation_vector: Vec<&Operation>= circuit.iter().collect();
/// // iterating over circuit II
/// for op in circuit{
/// println!("{:?}", op);
/// }
/// // collecting operations into circuit
/// let vector = vec![Operation::from(RotateX::new(0,CalculatorFloat::from(0))), Operation::from(RotateX::new(0,CalculatorFloat::from(0)))];
/// let new_circuit: Circuit = vector.into_iter().collect();
/// ```
///
/// Similarly to single Operations, Circuits can be translated to other frameworks via interfaces.
///
/// For Circuits the following functions are defined:
/// * `new()`: creates an empty Circuit
/// * `add_operation(operation)`: adds the specified operation to the Circuit
/// * `get(index)`: returns the operation at the specified index in the Circuit
/// * `get_mut(index)`: returns mutable reference to the operation at the specified index in the Circuit
/// * `iter()`: creates an iterator of the Circuit
/// * `len()`: returns the length of the Circuit
/// * `is_empty()`: returns a boolean of whether the Circuit contains any definitions and operations or not
/// * `involved_qubits()`: returns the qubits invovlved in the whole Circuit
/// * `definitions()`: returns the definitions in the Circuit
/// * `operations()`: returns the operations in the Circuit
/// * `substitute_parameters(calculator)`: substitutes any symbolic parameters in (a copy of) the Circuit according to the specified Calculator
/// * `remap_qubits(mapping)`: remaps the qubits in (a copy of) the Circuit according to the specified mapping
/// * `count_occurences(operations)`: returns the number of operations in the Circuit with the specified operation tags
/// * `get_operation_types()`: returns a list of all of the operations in the Circuit (in hqslang)
/// * `from_iter(iterator)`: creates a Circuit from the items in the specified iterator
/// * `extend(iterator)`: adds the operations in the specified iterator to the Circuit
/// * `default()`: creates an empty Circuit
/// * `[...]`: gets a slice of the Circuit (returned as a vector)
/// * `+` and `+=`: add two circuits or an operation to the Circuit
///
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
pub struct Circuit {
/// Definitions in the quantum circuit, must be unique.
definitions: Vec<Operation>,
/// Operations of the quantum circuit, do not have to be unique.
operations: Vec<Operation>,
}
impl Circuit {
/// Creates an empty quantum Circuit.
///
/// # Returns
///
/// * `Self` - The empty Circuit.
pub fn new() -> Self {
Circuit {
definitions: Vec::new(),
operations: Vec::new(),
}
}
/// Adds an Operation to Circuit (self).
///
/// # Arguments
///
/// * `op` - The Operation to add to the Circuit.
pub fn add_operation<T>(&mut self, op: T)
where
T: Into<Operation>,
{
let input: Operation = op.into();
match &input {
Operation::DefinitionBit(_) => self.definitions.push(input),
Operation::DefinitionFloat(_) => {
self.definitions.push(input);
}
Operation::DefinitionComplex(_) => {
self.definitions.push(input);
}
Operation::DefinitionUsize(_) => {
self.definitions.push(input);
}
Operation::InputSymbolic(_) => {
self.definitions.push(input);
}
_ => self.operations.push(input),
}
}
/// Returns a reference to the element at index similar to std::Vec get function.
///
/// Contrary to std::Vec get function not implemented for slices .
///
/// # Arguments
///
/// * `index` - The index of the Operation to get in the Circuit.
///
/// # Returns
///
/// * `Option<&Operation>` - The operation at the given index (if it exists).
pub fn get(&self, index: usize) -> Option<&Operation> {
let def_len = self.definitions.len();
if index >= self.definitions.len() {
self.operations.get(index - def_len)
} else {
self.definitions.get(index)
}
}
/// Returns a mutable reference to the element at index similar to std::Vec get function.
///
/// Contrary to std::Vec get function not implemented for slices.
///
/// # Arguments
///
/// * `index` - The index of the Operation to get in the Circuit.
///
/// # Returns
///
/// * `Option<mut &Operation>` - A mutable reference to the operation at the given index (if it exists).
pub fn get_mut(&mut self, index: usize) -> Option<&mut Operation> {
let def_len = self.definitions.len();
if index >= self.definitions.len() {
self.operations.get_mut(index - def_len)
} else {
self.definitions.get_mut(index)
}
}
/// Creates an iterator of the Circuit.
///
/// # Returns
///
/// `Iterator<Item = &Operation>` - The Circuit in iterator form.
pub fn iter(&self) -> impl Iterator<Item = &Operation> {
self.definitions.iter().chain(self.operations.iter())
}
/// Returns true if the Circuit contains symbolic variables.
///
/// # Returns
///
/// * `bool` - True if the Circuit contains symbolic values, false if it does not.
pub fn is_parametrized(&self) -> bool {
self.operations.iter().any(|o| o.is_parametrized())
|| self.definitions.iter().any(|o| o.is_parametrized())
}
/// Returns the length of the Circuit.
///
/// # Returns
///
/// * `usize` - The length of the Circuit.
pub fn len(&self) -> usize {
self.definitions.len() + self.operations.len()
}
/// Returns true if the Circuit does not contain any operations and definitions.
///
/// # Returns
///
/// * `bool` - True if the Circuit is empty, false if it is not.
pub fn is_empty(&self) -> bool {
self.definitions.is_empty() && self.operations.is_empty()
}
/// Returns qubits the Circuit acts on.
///
/// # Returns
///
/// * `InvolvedQubits` - The qubits involved in the Circuit.
pub fn involved_qubits(&self) -> InvolvedQubits {
let mut temp_involved: HashSet<usize> = HashSet::new();
for op in self.operations.iter() {
match &op.involved_qubits() {
InvolvedQubits::All => {
return InvolvedQubits::All;
}
InvolvedQubits::None => (),
InvolvedQubits::Set(x) => temp_involved = temp_involved.union(x).cloned().collect(),
}
}
match temp_involved.is_empty() {
true => InvolvedQubits::None,
false => InvolvedQubits::Set(temp_involved),
}
}
/// Returns reference to the vector of definitions in Circuit.
///
/// Definitions need to be unique.
///
/// # Returns
///
/// * `&Vec<Operation>` - A vector of the definitions in the Circuit.
pub fn definitions(&self) -> &Vec<Operation> {
&self.definitions
}
/// Returns reference to the vector of quantum operations in Circuit.
///
/// Operations do not need to be unique.
///
/// # Returns
///
/// * `&Vec<Operation>` - A vector of the operations in the Circuit.
pub fn operations(&self) -> &Vec<Operation> {
&self.operations
}
/// Substitutes the symbolic parameters in a clone of Circuit according to the calculator input.
///
/// # Arguments
///
/// * ``calculator` - The Calculator containing the substitutions to use in the Circuit.
///
/// # Returns
///
/// * `Ok(Self)` - The Circuit with the parameters substituted.
/// * `Err(RoqoqoError)` - The subsitution failed.
pub fn substitute_parameters(&self, calculator: &mut Calculator) -> Result<Self, RoqoqoError> {
let mut tmp_def: Vec<Operation> = Vec::new();
for def in self.definitions.iter() {
let tmp_op = def.substitute_parameters(calculator)?;
if let Operation::InputSymbolic(x) = &tmp_op {
calculator.set_variable(x.name(), *x.input())
}
tmp_def.push(tmp_op);
}
let mut tmp_op: Vec<Operation> = Vec::new();
for op in self.operations.iter() {
tmp_op.push(op.substitute_parameters(calculator)?);
}
Ok(Self {
definitions: tmp_def,
operations: tmp_op,
})
}
/// Remaps the qubits in operations in clone of Circuit.
///
/// # Arguments
///
/// * ``mapping` - The HashMap containing the {qubit: qubit} mapping to use in the Circuit.
///
/// # Returns
///
/// * `Ok(Self)` - The Circuit with the qubits remapped.
/// * `Err(RoqoqoError)` - The remapping failed.
pub fn remap_qubits(&self, mapping: &HashMap<usize, usize>) -> Result<Self, RoqoqoError> {
let mut tmp_op: Vec<Operation> = Vec::new();
for op in self.operations.iter() {
tmp_op.push(op.remap_qubits(mapping)?);
}
Ok(Self {
definitions: self.definitions.clone(),
operations: tmp_op,
})
}
/// Counts the number of occurences of a set of operation tags in the circuit.
///
/// # Arguments
///
/// `operations` - The list of operation tags that should be counted.
///
/// # Returns
///
/// * `usize` - The number of occurences of these operation tags.
pub fn count_occurences(&self, operations: &[&str]) -> usize {
let mut counter: usize = 0;
for op in self.iter() {
if operations.iter().any(|x| op.tags().contains(x)) {
counter += 1
}
}
counter
}
/// Returns a list of the hqslang names of all operations occuring in the circuit.
///
/// # Returns
///
/// * `HashSet<&str>` - The operation types in the Circuit.
pub fn get_operation_types(&self) -> HashSet<&str> {
let mut operations: HashSet<&str> = HashSet::new();
for op in self.iter() {
let _ = operations.insert(op.hqslang());
}
operations
}
/// Returns clone of the circuit with all Overrotation Pragmas applied.
///
/// # Returns
///
/// * `Ok(Circuit)` - The Circuit with overrotations applied.
/// * `Err(RoqoqoError::OverrotationError)` - Applying overrotations failed.
///
/// # Example
///
/// ```
/// use roqoqo::Circuit;
/// use roqoqo::operations::{PragmaOverrotation, RotateX, RotateY};
/// let mut circuit = Circuit::new();
/// // Adding Overrotation of next RotateY operation acting on qubit 1
/// // overrotating parameter theta with a statistical value
/// // value is drawn from normal distribution with standard deviation 30.0
/// // and multiplied by amplitude 20.0
/// circuit += PragmaOverrotation::new("RotateY".to_string(), vec![1], 20.0, 30.0);
/// circuit += RotateX::new(0, 0.0.into());
/// circuit += RotateY::new(0, 1.0.into());
/// circuit += RotateY::new(1, 2.0.into());
/// circuit += RotateY::new(1, 3.0.into());
///
/// let circuit_overrotated = circuit.overrotate().unwrap();
///
/// println!("{}", circuit);
/// println!("{}", circuit_overrotated);
/// ```
///
#[cfg(feature = "overrotate")]
pub fn overrotate(&self) -> Result<Self, RoqoqoError> {
let mut tmp_vec = self.operations.clone();
let mut return_circuit = Circuit {
definitions: self.definitions.clone(),
operations: Vec::new(),
};
let mut length = tmp_vec.len();
while length > 0 {
match tmp_vec
.iter()
.enumerate()
.find(|(_, op)| op.hqslang() == "PragmaOverrotation")
.map(|(i, op)| (i, op.clone()))
{
Some((index, Operation::PragmaOverrotation(overrotation))) => {
// for op in tmp_vec[..index].iter() {
// return_circuit.operations.push(op.clone())
// }
let hqslang = overrotation.gate_hqslang();
match tmp_vec[index..].iter().enumerate().find(|(_, op)| {
hqslang == op.hqslang()
&& overrotation.involved_qubits() == op.involved_qubits()
}) {
Some((ind, _)) => {
let mut tmp_tmp_vec: Vec<Operation> = Vec::new();
for (mov_ind, op) in tmp_vec.into_iter().enumerate() {
if mov_ind == index + ind {
println!("index: {}. op: {:?}", mov_ind, op.clone());
tmp_tmp_vec.push(
Rotation::try_from(op)?
.overrotate(
overrotation.amplitude(),
overrotation.variance(),
)
.into(),
)
} else if index != mov_ind {
tmp_tmp_vec.push(op)
}
}
tmp_vec = tmp_tmp_vec
}
None => {
let mut tmp_tmp_vec: Vec<Operation> = Vec::new();
for (mov_ind, op) in tmp_vec.into_iter().enumerate() {
if index != mov_ind {
tmp_tmp_vec.push(op)
}
}
tmp_vec = tmp_tmp_vec
}
}
}
_ => {
for op in tmp_vec {
return_circuit.operations.push(op)
}
tmp_vec = Vec::new();
}
}
length = tmp_vec.len();
}
Ok(return_circuit)
}
}
/// Implements Index Access for Circuit.
///
/// # Panics
///
/// Panics when index is out of range of operations in circuit.
/// This is consistent with standard Vec behaviour
/// and returning Option or Result enums instead would conflict with definition of Output type.
impl ops::Index<usize> for Circuit {
type Output = Operation;
/// Returns reference to Operation at index.
///
/// # Arguments
///
/// * `index` - The index of the operation.
///
/// # Panics
///
/// Panics when index is out of range of operations in circuit.
fn index(&self, index: usize) -> &Self::Output {
let def_len = self.definitions.len();
if index >= def_len {
&self.operations[index - def_len]
} else {
&self.definitions[index]
}
}
}
impl ops::IndexMut<usize> for Circuit {
/// Returns reference to Operation at index.
///
/// # Arguments
///
/// * `index` - The index of the operation.
///
/// # Panics
///
/// Panics when index is out of range of operations in circuit.
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
let def_len = self.definitions.len();
if index >= def_len {
&mut self.operations[index - def_len]
} else {
&mut self.definitions[index]
}
}
}
impl IntoIterator for Circuit {
type Item = Operation;
type IntoIter = OperationIterator;
/// Returns the Circuit in Iterator form.
///
/// # Returns
///
/// * `Self::IntoIter` - The Circuit in Iterator form.
fn into_iter(self) -> Self::IntoIter {
Self::IntoIter {
definition_iter: self.definitions.into_iter(),
operation_iter: self.operations.into_iter(),
}
}
}
impl<T> FromIterator<T> for Circuit
where
T: Into<Operation>,
{
/// Returns the circuit in Circuit form, from an Iterator form of the circuit.
///
/// # Returns
///
/// * `Self::IntoIter` - The Circuit in Circuit form.
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
let mut circuit = Circuit::new();
for op in iter {
circuit.add_operation(op.into());
}
circuit
}
}
impl<T> Extend<T> for Circuit
where
T: Into<Operation>,
{
/// Extends the Circuit by the specified operations (in Iterator form).
///
/// # Arguments
///
/// * `iter` - The iterator containing the operations by which to extend the Circuit.
fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
for op in iter {
self.add_operation(op.into());
}
}
}
impl Default for Circuit {
/// Creates a default implementation of the Circuit, which is an empty Circuit.
///
/// # Returns
///
/// * `Self` - The default Circuit (empty).
fn default() -> Self {
Self::new()
}
}
/// Trait for returning Vectors based on Range structs usually used for Index<> trait and slice access.
///
/// Required because Circuit does not have a continuous internal vector representation of the values.
/// Returns a Vec instead of slices.
///
/// # Example
///
/// ```
/// use roqoqo::{Circuit, AsVec};
/// use roqoqo::operations::{DefinitionFloat, Operation, RotateZ};
/// use qoqo_calculator::CalculatorFloat;
///
/// let mut circuit = Circuit::new();
/// let definition = DefinitionFloat::new(String::from("ro"), 1, false);
/// let rotatez0 = RotateZ::new(0, CalculatorFloat::from(0.0));
/// circuit.add_operation(definition.clone());
/// circuit.add_operation(rotatez0.clone());
///
/// let vec_ops = vec![
/// Operation::from(definition.clone()),
/// Operation::from(rotatez0.clone()),
/// ];
///
/// assert_eq!(circuit.as_vec(0..1).clone(), Some(vec![vec_ops[0].clone()])); // Range
/// assert_eq!(circuit.as_vec(0..).clone(), Some(vec_ops.clone())); // RangeTo
/// assert_eq!(circuit.as_vec(..1).clone(), Some(vec![vec_ops[0].clone()])); // RangeFrom
/// ```
///
pub trait AsVec<T> {
/// Returns slice of Circuit as Vec<Operations>.
///
/// # Arguments
///
/// * `range` - The indices of the slice of the Circuit to be returned.
///
/// # Returns
///
/// * `Option<Vec<Operation>>` - A vector of the operations in the Circuit with the specified indices.
fn as_vec(&self, range: T) -> Option<Vec<Operation>>;
}
impl AsVec<std::ops::Range<usize>> for Circuit {
/// Returns slice of Circuit as Vec<Operations>.
///
/// # Arguments
///
/// * `range` - The indices of the slice of the Circuit to be returned.
///
/// # Returns
///
/// * `Option<Vec<Operation>>` - A vector of the operations in the Circuit with the specified indices.
fn as_vec(&self, range: std::ops::Range<usize>) -> Option<Vec<Operation>> {
let mut return_vec: Vec<Operation>;
let def_len = self.definitions.len();
if range.end - def_len >= self.operations.len() {
return None;
}
if range.start < def_len {
if range.end < def_len {
return_vec = self.definitions[range].to_vec();
} else {
return_vec = self.definitions[range.start..].to_vec();
let mut tmp_vec = self.operations[..range.end - def_len].to_vec();
return_vec.append(&mut tmp_vec);
}
} else {
return_vec = self.operations[range.start - def_len..range.end - def_len].to_vec();
}
Some(return_vec)
}
}
impl AsVec<std::ops::RangeTo<usize>> for Circuit {
/// Returns slice of Circuit as Vec<Operations>.
///
/// # Arguments
///
/// * `range` - The indices of the slice of the Circuit to be returned.
///
/// # Returns
///
/// * `Option<Vec<Operation>>` - A vector of the operations in the Circuit with the specified indices.
fn as_vec(&self, range: std::ops::RangeTo<usize>) -> Option<Vec<Operation>> {
let mut return_vec: Vec<Operation>;
let def_len = self.definitions.len();
if range.end - def_len >= self.operations.len() {
return None;
}
if range.end < def_len {
return_vec = self.definitions[range].to_vec();
} else {
return_vec = self.definitions.clone();
let mut tmp_vec = self.operations[..range.end - def_len].to_vec();
return_vec.append(&mut tmp_vec);
}
Some(return_vec)
}
}
impl AsVec<std::ops::RangeFrom<usize>> for Circuit {
/// Returns slice of Circuit as Vec<Operations>.
///
/// # Arguments
///
/// * `range` - The indices of the slice of the Circuit to be returned.
///
/// # Returns
///
/// * `Option<Vec<Operation>>` - A vector of the operations in the Circuit with the specified indices.
fn as_vec(&self, range: std::ops::RangeFrom<usize>) -> Option<Vec<Operation>> {
let mut return_vec: Vec<Operation>;
let def_len = self.definitions.len();
if range.start < def_len {
return_vec = self.definitions[range.start..].to_vec();
let mut tmp_vec = self.operations.clone();
return_vec.append(&mut tmp_vec);
} else {
return_vec = self.operations[range.start - def_len..].to_vec();
}
Some(return_vec)
}
}
/// Implements `+` (add) for Circuit and generic type `T`.
///
/// # Arguments
///
/// * `other` - Any type T that implements Into<Operation> trait.
impl<T> ops::Add<T> for Circuit
where
T: Into<Operation>,
{
type Output = Self;
fn add(self, other: T) -> Self {
let mut return_circuit = self;
return_circuit.add_operation(other);
return_circuit
}
}
/// Implements `+` (add) for two Circuits.
///
/// # Arguments
///
/// * `other` - The Circuit to be added.
impl ops::Add<Circuit> for Circuit {
type Output = Self;
fn add(self, other: Circuit) -> Self {
Self {
definitions: self
.definitions
.into_iter()
.chain(other.definitions.into_iter())
.collect(),
operations: self
.operations
.into_iter()
.chain(other.operations.into_iter())
.collect(),
}
}
}
/// Implements `+` (add) for Circuit and Circuit reference.
///
/// # Arguments
///
/// * `other` - The Circuit reference to be added.
impl ops::Add<&Circuit> for Circuit {
type Output = Self;
fn add(self, other: &Circuit) -> Self {
Self {
definitions: self
.definitions
.into_iter()
.chain(other.definitions.iter().cloned())
.collect(),
operations: self
.operations
.into_iter()
.chain(other.operations.iter().cloned())
.collect(),
}
}
}
/// Implements `+=` (add) for Circuit and generic type `T`.
///
/// # Arguments
///
/// * `other` - Any type T that implements Into<Operation> trait.
impl<T> ops::AddAssign<T> for Circuit
where
T: Into<Operation>,
{
fn add_assign(&mut self, other: T) {
self.add_operation(other);
}
}
/// Implements `+=` (add) for two Circuits.
///
/// # Arguments
///
/// * `other` - The Circuit to be appended.
impl ops::AddAssign<Circuit> for Circuit {
fn add_assign(&mut self, other: Circuit) {
self.definitions.extend(other.definitions.into_iter());
self.operations.extend(other.operations.into_iter())
}
}
/// Implements `+=` (add) for Circuits and Circuit reference.
///
/// # Arguments
///
/// * `other` - The Circuit to be appended.
impl ops::AddAssign<&Circuit> for Circuit {
fn add_assign(&mut self, other: &Circuit) {
self.definitions.extend(other.definitions.iter().cloned());
self.operations.extend(other.operations.iter().cloned())
}
}
/// Implements the Display trait for Circuit.
impl Display for Circuit {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let mut s: String = String::new();
for op in self.iter() {
s.push_str(&format!("{:?}\n", op))
}
write!(f, "{}", s)
}
}
/// Iterator over roqoqo operations.
#[derive(Debug, Clone)]
pub struct OperationIterator {
/// Definitions in the quantum circuit in Iterator form, must be unique.
definition_iter: std::vec::IntoIter<Operation>,
/// Operations in the quantum circuit in Iterator form, must not be unique.
operation_iter: std::vec::IntoIter<Operation>,
}
impl Iterator for OperationIterator {
type Item = Operation;
/// Advances the iterator and returns the next value.
///
/// Returns None when iteration is finished. Individual iterator implementations may choose to resume iteration,
/// and so calling next() again may or may not eventually start returning Some(Operation) again at some point.
///
/// # Returns
///
/// * `Option<Self::Item>` - The Operation that is next in the Iterator.
fn next(&mut self) -> Option<Self::Item> {
match self.definition_iter.next() {
Some(x) => Some(x),
None => self.operation_iter.next(),
}
}
}