diff --git a/Cargo.lock b/Cargo.lock index 9fc4a8b0a9..493fc42ba7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1341,6 +1341,7 @@ dependencies = [ "expect-test", "indoc", "miette", + "ndarray", "num-bigint", "num-complex", "num-traits", @@ -1625,8 +1626,8 @@ dependencies = [ [[package]] name = "quantum-sparse-sim" -version = "0.7.4" -source = "git+https://github.com/qir-alliance/qir-runner?tag=v0.7.4#7b41f9313609f8309317ce91afccf0a2c7fe5a6f" +version = "0.7.5" +source = "git+https://github.com/qir-alliance/qir-runner?rev=562e2c11ad685dd01bfc1ae975e00d4133615995#562e2c11ad685dd01bfc1ae975e00d4133615995" dependencies = [ "ndarray", "num-bigint", diff --git a/Cargo.toml b/Cargo.toml index 0925ce8a6d..57aafe9faa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -58,6 +58,7 @@ log = "0.4" miette = { version = "7.2", features = ["fancy-no-syscall"] } thiserror = "1.0" nalgebra = { version = "0.33" } +ndarray = "0.15.4" num-bigint = "0.4" num-complex = "0.4" num-traits = "0.2" @@ -77,7 +78,7 @@ wasm-bindgen-futures = "0.4" rand = "0.8" serde_json = "1.0" pyo3 = "0.22" -quantum-sparse-sim = { git = "https://github.com/qir-alliance/qir-runner", tag = "v0.7.4" } +quantum-sparse-sim = { git = "https://github.com/qir-alliance/qir-runner", rev = "562e2c11ad685dd01bfc1ae975e00d4133615995" } async-trait = "0.1" tokio = { version = "1.35", features = ["macros", "rt"] } diff --git a/build.py b/build.py index 0ee53ec667..5a748a10f4 100755 --- a/build.py +++ b/build.py @@ -514,7 +514,7 @@ def run_ci_historic_benchmark(): "ipykernel", "nbconvert", "pandas", - "qiskit>=1.2.2,<2.0.0", + "qiskit>=1.3.0,<2.0.0", ] subprocess.run(pip_install_args, check=True, text=True, cwd=root_dir, env=pip_env) diff --git a/compiler/qsc_doc_gen/src/generate_docs.rs b/compiler/qsc_doc_gen/src/generate_docs.rs index ccd9f14c20..f3d7ce450f 100644 --- a/compiler/qsc_doc_gen/src/generate_docs.rs +++ b/compiler/qsc_doc_gen/src/generate_docs.rs @@ -463,10 +463,9 @@ fn generate_exported_file_content( // Note: we are assuming the package kind does not change let true_metadata = get_metadata(package_kind, true_ns.clone(), true_item, display)?; let true_fqn = true_metadata.fully_qualified_name(); - let name = true_metadata.name; let summary = format!( - "This is an exported item. The actual definition is found here: [{name}](xref:Qdk.{true_fqn})" + "This is an exported item. The actual definition is found here: [{true_fqn}](xref:Qdk.{true_fqn})" ); metadata.summary = summary.clone(); diff --git a/compiler/qsc_doc_gen/src/generate_docs/tests.rs b/compiler/qsc_doc_gen/src/generate_docs/tests.rs index 94fa1daa14..e471b3ce12 100644 --- a/compiler/qsc_doc_gen/src/generate_docs/tests.rs +++ b/compiler/qsc_doc_gen/src/generate_docs/tests.rs @@ -118,21 +118,21 @@ fn redirect_generation() { --- uid: Qdk.Microsoft.Quantum.Core.Length title: Length exported item - description: "Q# Length exported item: This is an exported item. The actual definition is found here: [Length](xref:Qdk.Std.Core.Length)" + description: "Q# Length exported item: This is an exported item. The actual definition is found here: [Std.Core.Length](xref:Qdk.Std.Core.Length)" ms.date: {TIMESTAMP} ms.topic: managed-reference qsharp.kind: export qsharp.package: __Std__ qsharp.namespace: Microsoft.Quantum.Core qsharp.name: Length - qsharp.summary: "This is an exported item. The actual definition is found here: [Length](xref:Qdk.Std.Core.Length)" + qsharp.summary: "This is an exported item. The actual definition is found here: [Std.Core.Length](xref:Qdk.Std.Core.Length)" --- # Length exported item Fully qualified name: Microsoft.Quantum.Core.Length - This is an exported item. The actual definition is found here: [Length](xref:Qdk.Std.Core.Length) + This is an exported item. The actual definition is found here: [Std.Core.Length](xref:Qdk.Std.Core.Length) "#]] .assert_eq(full_contents.as_str()); } diff --git a/compiler/qsc_eval/Cargo.toml b/compiler/qsc_eval/Cargo.toml index 366a1ea295..2dc458b16a 100644 --- a/compiler/qsc_eval/Cargo.toml +++ b/compiler/qsc_eval/Cargo.toml @@ -10,6 +10,7 @@ license.workspace = true [dependencies] miette = { workspace = true } +ndarray = { workspace = true } num-bigint = { workspace = true } num-complex = { workspace = true } num-traits = { workspace = true } diff --git a/compiler/qsc_eval/src/backend.rs b/compiler/qsc_eval/src/backend.rs index 6939e3b18a..62cd9021fe 100644 --- a/compiler/qsc_eval/src/backend.rs +++ b/compiler/qsc_eval/src/backend.rs @@ -1,8 +1,9 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -use crate::noise::PauliNoise; use crate::val::Value; +use crate::{noise::PauliNoise, val::unwrap_tuple}; +use ndarray::Array2; use num_bigint::BigUint; use num_complex::Complex; use quantum_sparse_sim::QuantumSim; @@ -419,6 +420,29 @@ impl Backend for SparseSim { self.apply_noise(q); Some(Ok(Value::unit())) } + "Apply" => { + let [matrix, qubits] = unwrap_tuple(arg); + let qubits = qubits + .unwrap_array() + .iter() + .filter_map(|q| q.clone().unwrap_qubit().try_deref().map(|q| q.0)) + .collect::>(); + let matrix = unwrap_matrix_as_array2(matrix, &qubits); + + // Confirm the matrix is unitary by checking if multiplying it by its adjoint gives the identity matrix (up to numerical precision). + let adj = matrix.t().map(Complex::::conj); + if (matrix.dot(&adj) - Array2::>::eye(1 << qubits.len())) + .map(|x| x.norm()) + .sum() + > 1e-9 + { + return Some(Err("matrix is not unitary".to_string())); + } + + self.sim.apply(&matrix, &qubits, None); + + Some(Ok(Value::unit())) + } _ => None, } } @@ -438,6 +462,27 @@ impl Backend for SparseSim { } } +fn unwrap_matrix_as_array2(matrix: Value, qubits: &[usize]) -> Array2> { + let matrix: Vec>> = matrix + .unwrap_array() + .iter() + .map(|row| { + row.clone() + .unwrap_array() + .iter() + .map(|elem| { + let [re, im] = unwrap_tuple(elem.clone()); + Complex::::new(re.unwrap_double(), im.unwrap_double()) + }) + .collect::>() + }) + .collect::>(); + + Array2::from_shape_fn((1 << qubits.len(), 1 << qubits.len()), |(i, j)| { + matrix[i][j] + }) +} + /// Simple struct that chains two backends together so that the chained /// backend is called before the main backend. /// For any intrinsics that return a value, diff --git a/compiler/qsc_eval/src/intrinsic.rs b/compiler/qsc_eval/src/intrinsic.rs index 3ea85a14be..711f34de19 100644 --- a/compiler/qsc_eval/src/intrinsic.rs +++ b/compiler/qsc_eval/src/intrinsic.rs @@ -10,13 +10,12 @@ use crate::{ backend::Backend, error::PackageSpan, output::Receiver, - val::{self, Value}, + val::{self, unwrap_tuple, Value}, Error, Rc, }; use num_bigint::BigInt; use rand::{rngs::StdRng, Rng}; use rustc_hash::{FxHashMap, FxHashSet}; -use std::array; use std::convert::TryFrom; #[allow(clippy::too_many_lines)] @@ -426,8 +425,3 @@ pub fn qubit_relabel( Ok(Value::unit()) } - -fn unwrap_tuple(value: Value) -> [Value; N] { - let values = value.unwrap_tuple(); - array::from_fn(|i| values[i].clone()) -} diff --git a/compiler/qsc_eval/src/val.rs b/compiler/qsc_eval/src/val.rs index af0000f311..f3d17f11ed 100644 --- a/compiler/qsc_eval/src/val.rs +++ b/compiler/qsc_eval/src/val.rs @@ -5,6 +5,7 @@ use num_bigint::BigInt; use qsc_data_structures::{display::join, functors::FunctorApp}; use qsc_fir::fir::{Functor, Pauli, StoreItemId}; use std::{ + array, fmt::{self, Display, Formatter}, rc::{Rc, Weak}, }; @@ -578,3 +579,9 @@ pub fn update_functor_app(functor: Functor, app: FunctorApp) -> FunctorApp { }, } } + +#[must_use] +pub fn unwrap_tuple(value: Value) -> [Value; N] { + let values = value.unwrap_tuple(); + array::from_fn(|i| values[i].clone()) +} diff --git a/compiler/qsc_frontend/src/closure.rs b/compiler/qsc_frontend/src/closure.rs index 62bd69b1fb..98bbb0f8aa 100644 --- a/compiler/qsc_frontend/src/closure.rs +++ b/compiler/qsc_frontend/src/closure.rs @@ -125,7 +125,7 @@ pub(super) fn lift( name: Ident { id: assigner.next_node(), span, - name: "lambda".into(), + name: "".into(), }, generics: Vec::new(), input, diff --git a/compiler/qsc_frontend/src/lower.rs b/compiler/qsc_frontend/src/lower.rs index f1e0958aa8..c349b203bb 100644 --- a/compiler/qsc_frontend/src/lower.rs +++ b/compiler/qsc_frontend/src/lower.rs @@ -29,7 +29,9 @@ use self::convert::TyConversionError; #[derive(Clone, Debug, Diagnostic, Error)] pub(super) enum Error { #[error("unknown attribute {0}")] - #[diagnostic(help("supported attributes are: EntryPoint, Config"))] + #[diagnostic(help( + "supported attributes are: EntryPoint, Config, SimulatableIntrinsic, Measurement, Reset" + ))] #[diagnostic(code("Qsc.LowerAst.UnknownAttr"))] UnknownAttr(String, #[label] Span), #[error("invalid attribute arguments: expected {0}")] diff --git a/compiler/qsc_frontend/src/lower/tests.rs b/compiler/qsc_frontend/src/lower/tests.rs index 408fb42c7e..f69873a75c 100644 --- a/compiler/qsc_frontend/src/lower/tests.rs +++ b/compiler/qsc_frontend/src/lower/tests.rs @@ -963,7 +963,7 @@ fn lambda_function_empty_closure() { Item 2 [57-67] (Internal): Parent: 1 Callable 15 [57-67] (function): - name: Ident 16 [57-67] "lambda" + name: Ident 16 [57-67] "" input: Pat 14 [57-67] [Type (Int,)]: Tuple: Pat 9 [57-58] [Type Int]: Bind: Ident 10 [57-58] "x" output: Int @@ -1025,7 +1025,7 @@ fn lambda_function_empty_closure_passed() { Item 3 [93-103] (Internal): Parent: 2 Callable 25 [93-103] (function): - name: Ident 26 [93-103] "lambda" + name: Ident 26 [93-103] "" input: Pat 24 [93-103] [Type (Int,)]: Tuple: Pat 19 [93-94] [Type Int]: Bind: Ident 20 [93-94] "x" output: Int @@ -1081,7 +1081,7 @@ fn lambda_function_closure() { Item 2 [76-86] (Internal): Parent: 1 Callable 21 [76-86] (function): - name: Ident 22 [76-86] "lambda" + name: Ident 22 [76-86] "" input: Pat 19 [76-86] [Type (Int, Int)]: Tuple: Pat 20 [53-54] [Type Int]: Bind: Ident 18 [53-54] "x" Pat 13 [76-77] [Type Int]: Bind: Ident 14 [76-77] "y" @@ -1138,7 +1138,7 @@ fn lambda_function_closure_repeated_var() { Item 2 [76-90] (Internal): Parent: 1 Callable 23 [76-90] (function): - name: Ident 24 [76-90] "lambda" + name: Ident 24 [76-90] "" input: Pat 21 [76-90] [Type (Int, Int)]: Tuple: Pat 22 [53-54] [Type Int]: Bind: Ident 20 [53-54] "x" Pat 13 [76-77] [Type Int]: Bind: Ident 14 [76-77] "y" @@ -1209,7 +1209,7 @@ fn lambda_function_closure_passed() { Item 3 [120-130] (Internal): Parent: 2 Callable 31 [120-130] (function): - name: Ident 32 [120-130] "lambda" + name: Ident 32 [120-130] "" input: Pat 29 [120-130] [Type (Int, Int)]: Tuple: Pat 30 [101-102] [Type Int]: Bind: Ident 28 [101-102] "x" Pat 23 [120-121] [Type Int]: Bind: Ident 24 [120-121] "y" @@ -1283,7 +1283,7 @@ fn lambda_function_nested_closure() { Item 3 [172-190] (Internal): Parent: 2 Callable 51 [172-190] (function): - name: Ident 52 [172-190] "lambda" + name: Ident 52 [172-190] "" input: Pat 47 [172-190] [Type (Int, Int, Int, Int)]: Tuple: Pat 48 [111-112] [Type Int]: Bind: Ident 44 [111-112] "a" Pat 49 [130-131] [Type Int]: Bind: Ident 45 [130-131] "b" @@ -1306,7 +1306,7 @@ fn lambda_function_nested_closure() { Item 4 [130-200] (Internal): Parent: 2 Callable 59 [130-200] (function): - name: Ident 60 [130-200] "lambda" + name: Ident 60 [130-200] "" input: Pat 57 [130-200] [Type (Int, Int)]: Tuple: Pat 58 [111-112] [Type Int]: Bind: Ident 56 [111-112] "a" Pat 25 [130-131] [Type Int]: Bind: Ident 26 [130-131] "b" @@ -1382,7 +1382,7 @@ fn lambda_operation_empty_closure() { Item 3 [137-144] (Internal): Parent: 2 Callable 27 [137-144] (operation): - name: Ident 28 [137-144] "lambda" + name: Ident 28 [137-144] "" input: Pat 26 [137-144] [Type (Qubit,)]: Tuple: Pat 23 [137-138] [Type Qubit]: Bind: Ident 24 [137-138] "q" output: Unit @@ -1465,7 +1465,7 @@ fn lambda_operation_closure() { Item 4 [199-215] (Internal): Parent: 3 Callable 35 [199-215] (operation): - name: Ident 36 [199-215] "lambda" + name: Ident 36 [199-215] "" input: Pat 33 [199-215] [Type (Qubit, Unit)]: Tuple: Pat 34 [174-175] [Type Qubit]: Bind: Ident 32 [174-175] "q" Pat 28 [199-201] [Type Unit]: Unit @@ -1543,7 +1543,7 @@ fn lambda_adj() { Item 4 [138-147] (Internal): Parent: 3 Callable 27 [138-147] (operation): - name: Ident 28 [138-147] "lambda" + name: Ident 28 [138-147] "" input: Pat 26 [138-147] [Type (Qubit,)]: Tuple: Pat 21 [138-139] [Type Qubit]: Bind: Ident 22 [138-139] "q" output: Unit @@ -1611,7 +1611,7 @@ fn partial_app_one_hole() { Item 3 [99-108] (Internal): Parent: 2 Callable 37 [99-108] (function): - name: Ident 38 [99-108] "lambda" + name: Ident 38 [99-108] "" input: Pat 35 [99-108] [Type (Int, Int)]: Tuple: Pat 36 [106-107] [Type Int]: Bind: Ident 34 [106-107] "arg" Pat 24 [103-104] [Type Int]: Bind: Ident 23 [103-104] "hole" @@ -1679,7 +1679,7 @@ fn partial_app_two_holes() { Item 3 [99-108] (Internal): Parent: 2 Callable 33 [99-108] (function): - name: Ident 34 [99-108] "lambda" + name: Ident 34 [99-108] "" input: Pat 32 [99-108] [Type ((Int, Int),)]: Tuple: Pat 30 [102-108] [Type (Int, Int)]: Tuple: Pat 24 [103-104] [Type Int]: Bind: Ident 23 [103-104] "hole" @@ -1752,7 +1752,7 @@ fn partial_app_nested_tuple() { Item 3 [130-152] (Internal): Parent: 2 Callable 52 [130-152] (function): - name: Ident 53 [130-152] "lambda" + name: Ident 53 [130-152] "" input: Pat 50 [130-152] [Type (Double, (Int, (Bool, String), Result))]: Tuple: Pat 51 [141-144] [Type Double]: Bind: Ident 49 [141-144] "arg" Pat 47 [133-152] [Type (Int, (Bool, String), Result)]: Tuple: @@ -1836,7 +1836,7 @@ fn partial_app_nested_tuple_singleton_unwrap() { Item 3 [130-155] (Internal): Parent: 2 Callable 56 [130-155] (function): - name: Ident 57 [130-155] "lambda" + name: Ident 57 [130-155] "" input: Pat 53 [130-155] [Type (Bool, Double, (Int, String, Result))]: Tuple: Pat 54 [138-142] [Type Bool]: Bind: Ident 51 [138-142] "arg" Pat 55 [144-147] [Type Double]: Bind: Ident 52 [144-147] "arg" @@ -2091,7 +2091,7 @@ fn partial_app_bound_to_non_arrow_ty() { Item 3 [113-122] (Internal): Parent: 2 Callable 37 [113-122] (function): - name: Ident 38 [113-122] "lambda" + name: Ident 38 [113-122] "" input: Pat 35 [113-122] [Type (Int, Int)]: Tuple: Pat 36 [117-118] [Type Int]: Bind: Ident 34 [117-118] "arg" Pat 30 [120-121] [Type Int]: Bind: Ident 29 [120-121] "hole" @@ -2366,7 +2366,7 @@ fn lambda_with_invalid_free_variable() { Item 2 [52-67] (Internal): Parent: 1 Callable 12 [52-67] (operation): - name: Ident 13 [52-67] "lambda" + name: Ident 13 [52-67] "" input: Pat 11 [52-67] [Type (Unit,)]: Tuple: Pat 7 [52-54] [Type Unit]: Unit output: Unit diff --git a/compiler/qsc_hir/src/hir.rs b/compiler/qsc_hir/src/hir.rs index cb42b9be3b..5c22bdd0fe 100644 --- a/compiler/qsc_hir/src/hir.rs +++ b/compiler/qsc_hir/src/hir.rs @@ -1344,23 +1344,42 @@ impl Display for Ident { /// An attribute. #[derive(Clone, Debug, PartialEq)] pub enum Attr { - /// Provide pre-processing information about when an item should be included in compilation. + /// Provides pre-processing information about when an item should be included in compilation. Config, - /// Indicates that a callable is an entry point to a program. + /// Indicates that the callable is the entry point to a program. EntryPoint, - /// Indicates that an item does not have an implementation available for use. + /// Indicates that an item is not yet implemented. Unimplemented, /// Indicates that an item should be treated as an intrinsic callable for QIR code generation - /// and any implementation should be ignored. + /// and any implementation should only be used during simulation. SimulatableIntrinsic, - /// Indicates that a callable is a measurement. This means that the operation will be marked as + /// Indicates that an intrinsic callable is a measurement. This means that the operation will be marked as /// "irreversible" in the generated QIR, and output Result types will be moved to the arguments. Measurement, - /// Indicates that a callable is a reset. This means that the operation will be marked as + /// Indicates that an intrinsic callable is a reset. This means that the operation will be marked as /// "irreversible" in the generated QIR. Reset, } +impl Attr { + /// Gets the string description of the attribute. + #[must_use] + pub fn description(&self) -> &'static str { + match self { + Attr::Config => "Provides pre-processing information about when an item should be included in compilation. + +Valid arguments are `Base`, `Adaptive`, `IntegerComputations`, `FloatingPointComputations`, `BackwardsBranching`, `HigherLevelConstructs`, `QubitReset`, and `Unrestricted`. + +The `not` operator is also supported to negate the attribute, e.g. `not Adaptive`.", + Attr::EntryPoint => "Indicates that the callable is the entry point to a program.", + Attr::Unimplemented => "Indicates that an item is not yet implemented.", + Attr::SimulatableIntrinsic => "Indicates that an item should be treated as an intrinsic callable for QIR code generation and any implementation should only be used during simulation.", + Attr::Measurement => "Indicates that an intrinsic callable is a measurement. This means that the operation will be marked as \"irreversible\" in the generated QIR, and output Result types will be moved to the arguments.", + Attr::Reset => "Indicates that an intrinsic callable is a reset. This means that the operation will be marked as \"irreversible\" in the generated QIR.", + } + } +} + impl FromStr for Attr { type Err = (); diff --git a/compiler/qsc_partial_eval/src/tests/misc.rs b/compiler/qsc_partial_eval/src/tests/misc.rs index 49dd390953..30f9094766 100644 --- a/compiler/qsc_partial_eval/src/tests/misc.rs +++ b/compiler/qsc_partial_eval/src/tests/misc.rs @@ -602,5 +602,5 @@ fn evaluation_error_within_stdlib_yield_correct_package_span() { } "#, }); - assert_error(&error, &expect!["UnexpectedDynamicValue(PackageSpan { package: PackageId(1), span: Span { lo: 13850, hi: 13865 } })"]); + assert_error(&error, &expect!["UnexpectedDynamicValue(PackageSpan { package: PackageId(1), span: Span { lo: 13910, hi: 13925 } })"]); } diff --git a/compiler/qsc_passes/src/spec_gen/tests.rs b/compiler/qsc_passes/src/spec_gen/tests.rs index 63d7bf9799..b215033b71 100644 --- a/compiler/qsc_passes/src/spec_gen/tests.rs +++ b/compiler/qsc_passes/src/spec_gen/tests.rs @@ -1906,7 +1906,7 @@ fn lambda_adj_calls_adj() { Item 4 [138-147] (Internal): Parent: 3 Callable 27 [138-147] (operation): - name: Ident 28 [138-147] "lambda" + name: Ident 28 [138-147] "" input: Pat 26 [138-147] [Type (Qubit,)]: Tuple: Pat 21 [138-139] [Type Qubit]: Bind: Ident 22 [138-139] "q" output: Unit @@ -2032,7 +2032,7 @@ fn op_array_forget_functors_with_lambdas() { Item 5 [270-281] (Internal): Parent: 4 Callable 35 [270-281] (operation): - name: Ident 36 [270-281] "lambda" + name: Ident 36 [270-281] "" input: Pat 34 [270-281] [Type (Qubit,)]: Tuple: Pat 29 [270-271] [Type Qubit]: Bind: Ident 30 [270-271] "q" output: Unit @@ -2048,7 +2048,7 @@ fn op_array_forget_functors_with_lambdas() { Item 6 [283-294] (Internal): Parent: 4 Callable 47 [283-294] (operation): - name: Ident 48 [283-294] "lambda" + name: Ident 48 [283-294] "" input: Pat 46 [283-294] [Type (Qubit,)]: Tuple: Pat 41 [283-284] [Type Qubit]: Bind: Ident 42 [283-284] "q" output: Unit diff --git a/katas/content/KatasLibrary.qs b/katas/content/KatasLibrary.qs index 1f3a86a3b4..ca71aeda83 100644 --- a/katas/content/KatasLibrary.qs +++ b/katas/content/KatasLibrary.qs @@ -2,11 +2,29 @@ // Licensed under the MIT License. namespace Microsoft.Quantum.Katas { - open Microsoft.Quantum.Arrays; - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Math; - open Microsoft.Quantum.Random; + import KatasUtils.*; + export + CheckOperationsAreEqualStrict, + CheckOperationsEquivalenceOnZeroState, + CheckOperationsEquivalenceOnInitialStateStrict, + CheckOperationsEquivalenceOnZeroStateStrict, + ShowQuantumStateComparison, + CheckOperationsEquivalenceOnZeroStateWithFeedback, + EntangleRegisters, + PrepDemoState, + DistinguishTwoStates_SingleQubit, + DistinguishStates_MultiQubit, + BoolArrayAsKetState, + IntArrayAsStateName, + CheckOracleImplementsFunction; +} + +namespace KatasUtils { + import Std.Arrays.*; + import Std.Convert.*; + import Std.Diagnostics.*; + import Std.Math.*; + import Std.Random.*; /// # Summary /// Given two operations, checks whether they act identically (including global phase) for all input states. @@ -15,8 +33,8 @@ namespace Microsoft.Quantum.Katas { operation CheckOperationsAreEqualStrict( inputSize : Int, op : (Qubit[] => Unit is Adj + Ctl), - reference : (Qubit[] => Unit is Adj + Ctl)) - : Bool { + reference : (Qubit[] => Unit is Adj + Ctl) + ) : Bool { Fact(inputSize > 0, "`inputSize` must be positive"); let controlledOp = register => Controlled op(register[...0], register[1...]); let controlledReference = register => Controlled reference(register[...0], register[1...]); @@ -30,8 +48,8 @@ namespace Microsoft.Quantum.Katas { operation CheckOperationsEquivalenceOnZeroState( op : (Qubit[] => Unit), reference : (Qubit[] => Unit is Adj), - inputSize : Int) - : Bool { + inputSize : Int + ) : Bool { Fact(inputSize > 0, "`inputSize` must be positive"); use target = Qubit[inputSize]; op(target); @@ -57,8 +75,7 @@ namespace Microsoft.Quantum.Katas { within { H(control); initialState(target); - } - apply { + } apply { Controlled op([control], target); Adjoint Controlled reference([control], target); } @@ -77,8 +94,8 @@ namespace Microsoft.Quantum.Katas { operation CheckOperationsEquivalenceOnZeroStateStrict( op : (Qubit[] => Unit is Adj + Ctl), reference : (Qubit[] => Unit is Adj + Ctl), - inputSize : Int) - : Bool { + inputSize : Int + ) : Bool { Fact(inputSize > 0, "`inputSize` must be positive"); CheckOperationsEquivalenceOnInitialStateStrict(qs => (), op, reference, inputSize) } @@ -91,8 +108,8 @@ namespace Microsoft.Quantum.Katas { registerSize : Int, initialState : Qubit[] => Unit, op : Qubit[] => Unit, - reference : Qubit[] => Unit) - : Unit { + reference : Qubit[] => Unit + ) : Unit { { use register = Qubit[registerSize]; initialState(register); @@ -142,10 +159,12 @@ namespace Microsoft.Quantum.Katas { internal operation EntangleRegisters( control : Qubit[], - target : Qubit[]) : Unit is Adj + Ctl { + target : Qubit[] + ) : Unit is Adj + Ctl { Fact( Length(control) == Length(target), - $"The length of qubit registers must be the same."); + $"The length of qubit registers must be the same." + ); for index in IndexRange(control) { H(control[index]); @@ -158,7 +177,7 @@ namespace Microsoft.Quantum.Katas { /// Prepare a random uneven superposition state on the given qubit array. operation PrepDemoState(qs : Qubit[]) : Unit { Fact(Length(qs) <= 4, "States with 5 qubits or more are not supported."); - let probs = [0.36, 0.25, 1. / 3., 1. / 5.][... Length(qs) - 1]; + let probs = [0.36, 0.25, 1. / 3., 1. / 5.][...Length(qs) - 1]; for (q, prob) in Zipped(qs, probs) { Ry(ArcCos(Sqrt(prob)) * 2.0, q); } @@ -171,14 +190,15 @@ namespace Microsoft.Quantum.Katas { statePrep : ((Qubit, Int) => Unit is Adj), testImpl : (Qubit => Bool), stateNames : String[], - preserveState : Bool) : Bool { + preserveState : Bool + ) : Bool { let nTotal = 100; let nStates = 2; - mutable misclassifications = [0, size=nStates]; + mutable misclassifications = [0, size = nStates]; use q = Qubit(); - for _ in 1 .. nTotal { + for _ in 1..nTotal { // get a random bit to define whether qubit will be in a state corresponding to true return (1) or to false one (0) // state = 0 false return // state = 1 true return @@ -207,7 +227,7 @@ namespace Microsoft.Quantum.Katas { } mutable totalMisclassifications = 0; - for i in 0 .. nStates - 1 { + for i in 0..nStates - 1 { if misclassifications[i] != 0 { set totalMisclassifications += misclassifications[i]; Message($"Misclassified {stateNames[i]} as {stateNames[1 - i]} in {misclassifications[i]} test runs."); @@ -226,7 +246,8 @@ namespace Microsoft.Quantum.Katas { statePrep : ((Qubit[], Int, Double) => Unit is Adj), testImpl : (Qubit[] => Int), preserveState : Bool, - stateNames : String[]) : Bool { + stateNames : String[] + ) : Bool { let nTotal = 100; // misclassifications will store the number of times state i has been classified as state j (dimension nStates^2) @@ -235,7 +256,7 @@ namespace Microsoft.Quantum.Katas { mutable unknownClassifications = [0, size = nStates]; use qs = Qubit[nQubits]; - for _ in 1 .. nTotal { + for _ in 1..nTotal { // get a random integer to define the state of the qubits let state = DrawRandomInt(0, nStates - 1); // get a random rotation angle to define the exact state of the qubits @@ -252,8 +273,7 @@ namespace Microsoft.Quantum.Katas { if ans != state { set misclassifications w/= ((state * nStates) + ans) <- (misclassifications[(state * nStates) + ans] + 1); } - } - else { + } else { // classification result is an invalid state index - file it separately set unknownClassifications w/= state <- (unknownClassifications[state] + 1); } @@ -273,8 +293,8 @@ namespace Microsoft.Quantum.Katas { } mutable totalMisclassifications = 0; - for i in 0 .. nStates - 1 { - for j in 0 .. nStates - 1 { + for i in 0..nStates - 1 { + for j in 0..nStates - 1 { if misclassifications[(i * nStates) + j] != 0 { set totalMisclassifications += misclassifications[i * nStates + j]; Message($"Misclassified {stateNames[i]} as {stateNames[j]} in {misclassifications[(i * nStates) + j]} test runs."); @@ -289,9 +309,9 @@ namespace Microsoft.Quantum.Katas { } // Helper function to convert a boolean array to its ket state representation - function BoolArrayAsKetState (bits : Bool[]) : String { + function BoolArrayAsKetState(bits : Bool[]) : String { mutable stateName = "|"; - for i in 0 .. Length(bits) - 1 { + for i in 0..Length(bits) - 1 { set stateName += (bits[i] ? "1" | "0"); } @@ -299,12 +319,12 @@ namespace Microsoft.Quantum.Katas { } // Helper function to convert an array of bit strings to its ket state representation - function IntArrayAsStateName ( + function IntArrayAsStateName( qubits : Int, bitStrings : Bool[][] ) : String { mutable statename = ""; - for i in 0 .. Length(bitStrings) - 1 { + for i in 0..Length(bitStrings) - 1 { if i > 0 { set statename += " + "; } @@ -315,25 +335,25 @@ namespace Microsoft.Quantum.Katas { } /// # Summary - /// Given a marking oracle acting on N inputs, and a classical function acting on N bits, + /// Given a marking oracle acting on N inputs, and a classical function acting on N bits, /// checks whether the oracle effect matches that of the function on every classical input. - operation CheckOracleImplementsFunction ( - N : Int, - oracle : (Qubit[], Qubit) => Unit, + operation CheckOracleImplementsFunction( + N : Int, + oracle : (Qubit[], Qubit) => Unit, f : Bool[] -> Bool ) : Bool { let size = 1 <<< N; use (input, target) = (Qubit[N], Qubit()); - for k in 0 .. size - 1 { + for k in 0..size - 1 { // Prepare k-th bit vector let binaryLE = IntAsBoolArray(k, N); - + // "binary" is little-endian notation, so the second vector tried has qubit 0 in state 1 and the rest in state 0 ApplyPauliFromBitString(PauliX, true, binaryLE, input); - + // Apply the operation oracle(input, target); - + // Calculate the expected classical result let val = f(binaryLE); @@ -357,5 +377,5 @@ namespace Microsoft.Quantum.Katas { } } return true; - } + } } diff --git a/katas/content/complex_arithmetic/Common.qs b/katas/content/complex_arithmetic/Common.qs index 4dd4d1c02f..1799646042 100644 --- a/katas/content/complex_arithmetic/Common.qs +++ b/katas/content/complex_arithmetic/Common.qs @@ -1,7 +1,7 @@ namespace Kata.Verification { - open Microsoft.Quantum.Math; - open Microsoft.Quantum.Random; - open Microsoft.Quantum.Convert; + import Std.Math.*; + import Std.Random.*; + import Std.Convert.*; operation DrawRandomComplex() : Complex { // Generates a random complex number. diff --git a/katas/content/complex_arithmetic/cartesian_to_polar/Placeholder.qs b/katas/content/complex_arithmetic/cartesian_to_polar/Placeholder.qs index a77fa43cef..5a4507d12d 100644 --- a/katas/content/complex_arithmetic/cartesian_to_polar/Placeholder.qs +++ b/katas/content/complex_arithmetic/cartesian_to_polar/Placeholder.qs @@ -1,6 +1,6 @@ namespace Kata { - open Microsoft.Quantum.Math; - + import Std.Math.*; + function ComplexToComplexPolar(x : Complex) : ComplexPolar { // Implement your solution here... return ComplexPolar(0., 0.); diff --git a/katas/content/complex_arithmetic/cartesian_to_polar/Solution.qs b/katas/content/complex_arithmetic/cartesian_to_polar/Solution.qs index 453ae03c92..68feb50ff5 100644 --- a/katas/content/complex_arithmetic/cartesian_to_polar/Solution.qs +++ b/katas/content/complex_arithmetic/cartesian_to_polar/Solution.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; function ComplexToComplexPolar(x : Complex) : ComplexPolar { let (a, b) = (x.Real, x.Imag); diff --git a/katas/content/complex_arithmetic/cartesian_to_polar/Verification.qs b/katas/content/complex_arithmetic/cartesian_to_polar/Verification.qs index ec9e26acde..30a11f2d61 100644 --- a/katas/content/complex_arithmetic/cartesian_to_polar/Verification.qs +++ b/katas/content/complex_arithmetic/cartesian_to_polar/Verification.qs @@ -1,15 +1,15 @@ namespace Kata.Verification { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Math; + import Std.Convert.*; + import Std.Math.*; @EntryPoint() - operation CheckSolution() : Bool { - for _ in 0 .. 24 { + operation CheckSolution() : Bool { + for _ in 0..24 { let x = DrawRandomComplex(); let expected = ComplexAsComplexPolar(x); let actual = Kata.ComplexToComplexPolar(x); - + if not ComplexPolarEqual(expected, actual) { Message("Incorrect"); Message($"For x = {ComplexAsString(x)} expected return {ComplexPolarAsString(expected)}, actual return {ComplexPolarAsString(actual)}."); @@ -20,4 +20,4 @@ namespace Kata.Verification { Message("Correct!"); return true; } -} \ No newline at end of file +} diff --git a/katas/content/complex_arithmetic/cartesian_to_polar/index.md b/katas/content/complex_arithmetic/cartesian_to_polar/index.md index 951420bf9c..ab7996150a 100644 --- a/katas/content/complex_arithmetic/cartesian_to_polar/index.md +++ b/katas/content/complex_arithmetic/cartesian_to_polar/index.md @@ -12,8 +12,8 @@ Return the polar representation of $x = re^{i\theta}$, that is, the distance fro A video explanation of this conversion can be found [here](https://www.youtube.com/watch?v=8RasCV_Lggg). - Q# namespace `Microsoft.Quantum.Math` includes a useful function `ArcTan2()`. + Q# namespace `Std.Math` includes a useful function `ArcTan2()`. -> Q# function `ComplexAsComplexPolar` from `Microsoft.Quantum.Math` namespace converts a complex number of type `Complex` to a complex number of type `ComplexPolar`. For educational purposes, try to do this task by hand. +> Q# function `ComplexAsComplexPolar` from `Std.Math` namespace converts a complex number of type `Complex` to a complex number of type `ComplexPolar`. For educational purposes, try to do this task by hand. diff --git a/katas/content/complex_arithmetic/complex_addition/Placeholder.qs b/katas/content/complex_arithmetic/complex_addition/Placeholder.qs index d78f2f1a0b..029230318c 100644 --- a/katas/content/complex_arithmetic/complex_addition/Placeholder.qs +++ b/katas/content/complex_arithmetic/complex_addition/Placeholder.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; function ComplexAdd(x : Complex, y : Complex) : Complex { // Extract real and imaginary components of the inputs. diff --git a/katas/content/complex_arithmetic/complex_addition/Solution.qs b/katas/content/complex_arithmetic/complex_addition/Solution.qs index 9166dc6aad..0e1f990bf1 100644 --- a/katas/content/complex_arithmetic/complex_addition/Solution.qs +++ b/katas/content/complex_arithmetic/complex_addition/Solution.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; function ComplexAdd(x : Complex, y : Complex) : Complex { Complex(x.Real + y.Real, x.Imag + y.Imag) diff --git a/katas/content/complex_arithmetic/complex_addition/Verification.qs b/katas/content/complex_arithmetic/complex_addition/Verification.qs index 55d061a7da..517cc4bf02 100644 --- a/katas/content/complex_arithmetic/complex_addition/Verification.qs +++ b/katas/content/complex_arithmetic/complex_addition/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Math; + import Std.Math.*; @EntryPoint() operation CheckSolution() : Bool { diff --git a/katas/content/complex_arithmetic/complex_addition/index.md b/katas/content/complex_arithmetic/complex_addition/index.md index 3488b6e2cb..5500a51ef6 100644 --- a/katas/content/complex_arithmetic/complex_addition/index.md +++ b/katas/content/complex_arithmetic/complex_addition/index.md @@ -14,4 +14,4 @@ Adding complex numbers is just like adding polynomials. Add components of the sa A video explanation of adding complex numbers can be found [here](https://www.youtube.com/watch?v=SfbjqVyQljk). -> Q# function `PlusC` from `Microsoft.Quantum.Math` namespace adds two complex numbers. For educational purposes, try to do this task by hand. +> Q# function `PlusC` from `Std.Math` namespace adds two complex numbers. For educational purposes, try to do this task by hand. diff --git a/katas/content/complex_arithmetic/complex_conjugate/Placeholder.qs b/katas/content/complex_arithmetic/complex_conjugate/Placeholder.qs index 87ff346ffc..06d9ad61ad 100644 --- a/katas/content/complex_arithmetic/complex_conjugate/Placeholder.qs +++ b/katas/content/complex_arithmetic/complex_conjugate/Placeholder.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; function ComplexConjugate(x : Complex) : Complex { // Implement your solution here... diff --git a/katas/content/complex_arithmetic/complex_conjugate/Solution.qs b/katas/content/complex_arithmetic/complex_conjugate/Solution.qs index 0bc40759c0..f299756957 100644 --- a/katas/content/complex_arithmetic/complex_conjugate/Solution.qs +++ b/katas/content/complex_arithmetic/complex_conjugate/Solution.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; function ComplexConjugate(x : Complex) : Complex { Complex(x.Real, -x.Imag) diff --git a/katas/content/complex_arithmetic/complex_conjugate/Verification.qs b/katas/content/complex_arithmetic/complex_conjugate/Verification.qs index 672386e519..763f76d997 100644 --- a/katas/content/complex_arithmetic/complex_conjugate/Verification.qs +++ b/katas/content/complex_arithmetic/complex_conjugate/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Math; + import Std.Math.*; function ComplexConjugate_Reference(x : Complex) : Complex { // Return the complex conjugate diff --git a/katas/content/complex_arithmetic/complex_division/Placeholder.qs b/katas/content/complex_arithmetic/complex_division/Placeholder.qs index 19ffe29b53..8c5a36dad5 100644 --- a/katas/content/complex_arithmetic/complex_division/Placeholder.qs +++ b/katas/content/complex_arithmetic/complex_division/Placeholder.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; function ComplexDiv(x : Complex, y : Complex) : Complex { // Implement your solution here... diff --git a/katas/content/complex_arithmetic/complex_division/Solution.qs b/katas/content/complex_arithmetic/complex_division/Solution.qs index 5afe45e2bb..6b0ed76519 100644 --- a/katas/content/complex_arithmetic/complex_division/Solution.qs +++ b/katas/content/complex_arithmetic/complex_division/Solution.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; function ComplexDiv(x : Complex, y : Complex) : Complex { let (a, b) = (x.Real, x.Imag); diff --git a/katas/content/complex_arithmetic/complex_division/Verification.qs b/katas/content/complex_arithmetic/complex_division/Verification.qs index 97d4e2aafb..21b5c6e1c4 100644 --- a/katas/content/complex_arithmetic/complex_division/Verification.qs +++ b/katas/content/complex_arithmetic/complex_division/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Math; + import Std.Math.*; @EntryPoint() operation CheckSolution() : Bool { diff --git a/katas/content/complex_arithmetic/complex_division/index.md b/katas/content/complex_arithmetic/complex_division/index.md index 11566a5194..ee1f04f516 100644 --- a/katas/content/complex_arithmetic/complex_division/index.md +++ b/katas/content/complex_arithmetic/complex_division/index.md @@ -12,4 +12,4 @@ A video explanation of complex division can be found [here](https://www.youtube. -> Q# function `DividedByC` from `Microsoft.Quantum.Math` namespace divides two complex numbers. For educational purposes, try to do this task by hand. +> Q# function `DividedByC` from `Std.Math` namespace divides two complex numbers. For educational purposes, try to do this task by hand. diff --git a/katas/content/complex_arithmetic/complex_exponents/Placeholder.qs b/katas/content/complex_arithmetic/complex_exponents/Placeholder.qs index 8b4bbf02ce..9f9266e066 100644 --- a/katas/content/complex_arithmetic/complex_exponents/Placeholder.qs +++ b/katas/content/complex_arithmetic/complex_exponents/Placeholder.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; function ComplexExponent(x : Complex) : Complex { // Implement your solution here... diff --git a/katas/content/complex_arithmetic/complex_exponents/Solution.qs b/katas/content/complex_arithmetic/complex_exponents/Solution.qs index c4703ed6ce..b7224f63ed 100644 --- a/katas/content/complex_arithmetic/complex_exponents/Solution.qs +++ b/katas/content/complex_arithmetic/complex_exponents/Solution.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; function ComplexExponent(x : Complex) : Complex { Complex(E()^x.Real * Cos(x.Imag), E()^x.Real * Sin(x.Imag)) diff --git a/katas/content/complex_arithmetic/complex_exponents/Verification.qs b/katas/content/complex_arithmetic/complex_exponents/Verification.qs index 4dfe15cabd..f9e2f5d783 100644 --- a/katas/content/complex_arithmetic/complex_exponents/Verification.qs +++ b/katas/content/complex_arithmetic/complex_exponents/Verification.qs @@ -1,6 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Math; - open Microsoft.Quantum.Random; + import Std.Math.*; function ComplexExponent_Reference(x : Complex) : Complex { let expa = E()^x.Real; diff --git a/katas/content/complex_arithmetic/complex_exponents/index.md b/katas/content/complex_arithmetic/complex_exponents/index.md index 51a53b252f..600b7b62e4 100644 --- a/katas/content/complex_arithmetic/complex_exponents/index.md +++ b/katas/content/complex_arithmetic/complex_exponents/index.md @@ -4,5 +4,5 @@
Need a hint? - Q# namespace Microsoft.Quantum.Math includes a function E() that returns the value of the constant $e$. + Q# namespace Std.Math includes a function E() that returns the value of the constant $e$.
diff --git a/katas/content/complex_arithmetic/complex_modulus/Placeholder.qs b/katas/content/complex_arithmetic/complex_modulus/Placeholder.qs index 4150f0558b..31b03c153c 100644 --- a/katas/content/complex_arithmetic/complex_modulus/Placeholder.qs +++ b/katas/content/complex_arithmetic/complex_modulus/Placeholder.qs @@ -1,6 +1,6 @@ namespace Kata { - open Microsoft.Quantum.Math; - + import Std.Math.*; + function ComplexModulus(x : Complex) : Double { // Implement your solution here... return 0.; diff --git a/katas/content/complex_arithmetic/complex_modulus/Solution.qs b/katas/content/complex_arithmetic/complex_modulus/Solution.qs index bfe034f15a..4c3d617db2 100644 --- a/katas/content/complex_arithmetic/complex_modulus/Solution.qs +++ b/katas/content/complex_arithmetic/complex_modulus/Solution.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; function ComplexModulus(x : Complex) : Double { let (a, b) = (x.Real, x.Imag); diff --git a/katas/content/complex_arithmetic/complex_modulus/Verification.qs b/katas/content/complex_arithmetic/complex_modulus/Verification.qs index ef18bae52c..d6b4269e9f 100644 --- a/katas/content/complex_arithmetic/complex_modulus/Verification.qs +++ b/katas/content/complex_arithmetic/complex_modulus/Verification.qs @@ -1,16 +1,16 @@ namespace Kata.Verification { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Math; + import Std.Convert.*; + import Std.Math.*; @EntryPoint() operation CheckSolution() : Bool { - for _ in 0 .. 24 { + for _ in 0..24 { let x = DrawRandomComplex(); let expected = AbsComplex(x); let actual = Kata.ComplexModulus(x); - - if AbsD(expected - actual) > 1e-6 { + + if AbsD(expected - actual) > 1e-6 { let precision = 3; Message("Incorrect"); Message($"For x = {ComplexAsString(x)} expected return {DoubleAsStringWithPrecision(expected, precision)}, actual return {DoubleAsStringWithPrecision(actual, precision)}."); diff --git a/katas/content/complex_arithmetic/complex_modulus/index.md b/katas/content/complex_arithmetic/complex_modulus/index.md index fd51808b15..4bf8565163 100644 --- a/katas/content/complex_arithmetic/complex_modulus/index.md +++ b/katas/content/complex_arithmetic/complex_modulus/index.md @@ -9,4 +9,4 @@ -> Q# function `AbsComplex` from `Microsoft.Quantum.Math` namespace gets the absolute value of a complex number. For educational purposes, try to do this task by hand. +> Q# function `AbsComplex` from `Std.Math` namespace gets the absolute value of a complex number. For educational purposes, try to do this task by hand. diff --git a/katas/content/complex_arithmetic/complex_multiplication/Placeholder.qs b/katas/content/complex_arithmetic/complex_multiplication/Placeholder.qs index 2d176a0841..e4aae0e38c 100644 --- a/katas/content/complex_arithmetic/complex_multiplication/Placeholder.qs +++ b/katas/content/complex_arithmetic/complex_multiplication/Placeholder.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; function ComplexMult(x : Complex, y : Complex) : Complex { // Implement your solution here... diff --git a/katas/content/complex_arithmetic/complex_multiplication/Solution.qs b/katas/content/complex_arithmetic/complex_multiplication/Solution.qs index 9b5668cf6d..1b91a514cb 100644 --- a/katas/content/complex_arithmetic/complex_multiplication/Solution.qs +++ b/katas/content/complex_arithmetic/complex_multiplication/Solution.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; function ComplexMult(x : Complex, y : Complex) : Complex { let (a, b) = (x.Real, x.Imag); diff --git a/katas/content/complex_arithmetic/complex_multiplication/Verification.qs b/katas/content/complex_arithmetic/complex_multiplication/Verification.qs index c5f67481d4..f3be82596c 100644 --- a/katas/content/complex_arithmetic/complex_multiplication/Verification.qs +++ b/katas/content/complex_arithmetic/complex_multiplication/Verification.qs @@ -1,8 +1,8 @@ -namespace Kata.Verification { - open Microsoft.Quantum.Math; +namespace Kata.Verification { + import Std.Math.*; @EntryPoint() operation CheckSolution() : Bool { CheckTwoComplexOpsAreSame(Kata.ComplexMult, TimesC) } -} \ No newline at end of file +} diff --git a/katas/content/complex_arithmetic/complex_multiplication/index.md b/katas/content/complex_arithmetic/complex_multiplication/index.md index 7818d2504a..a30bdcfccf 100644 --- a/katas/content/complex_arithmetic/complex_multiplication/index.md +++ b/katas/content/complex_arithmetic/complex_multiplication/index.md @@ -17,4 +17,4 @@ A video explanation of multiplying complex numbers can be found [here](https://w -> Q# function `TimesC` from `Microsoft.Quantum.Math` namespace multiplies two complex numbers. For educational purposes, try to do this task by hand. +> Q# function `TimesC` from `Std.Math` namespace multiplies two complex numbers. For educational purposes, try to do this task by hand. diff --git a/katas/content/complex_arithmetic/complex_powers_real/Placeholder.qs b/katas/content/complex_arithmetic/complex_powers_real/Placeholder.qs index ce5f56699c..7b93906236 100644 --- a/katas/content/complex_arithmetic/complex_powers_real/Placeholder.qs +++ b/katas/content/complex_arithmetic/complex_powers_real/Placeholder.qs @@ -1,7 +1,7 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; - function ComplexExpReal (r : Double, x : Complex) : Complex { + function ComplexExpReal(r : Double, x : Complex) : Complex { // Implement your solution here... return Complex(0.0, 0.0); } diff --git a/katas/content/complex_arithmetic/complex_powers_real/Solution.qs b/katas/content/complex_arithmetic/complex_powers_real/Solution.qs index 97c38c4a56..853b1b2ca0 100644 --- a/katas/content/complex_arithmetic/complex_powers_real/Solution.qs +++ b/katas/content/complex_arithmetic/complex_powers_real/Solution.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; function ComplexExpReal(r : Double, x : Complex) : Complex { if AbsD(r) < 1e-9 { diff --git a/katas/content/complex_arithmetic/complex_powers_real/Verification.qs b/katas/content/complex_arithmetic/complex_powers_real/Verification.qs index 93000e00a2..5e278081c0 100644 --- a/katas/content/complex_arithmetic/complex_powers_real/Verification.qs +++ b/katas/content/complex_arithmetic/complex_powers_real/Verification.qs @@ -1,7 +1,7 @@ namespace Kata.Verification { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Math; - open Microsoft.Quantum.Random; + import Std.Convert.*; + import Std.Math.*; + import Std.Random.*; function ComplexExpReal_Reference(r : Double, x : Complex) : Complex { if AbsD(r) < 1e-9 { @@ -22,7 +22,7 @@ namespace Kata.Verification { let actual = Kata.ComplexExpReal(r, x); if not ComplexEqual(expected, actual) { - let precision = 3; + let precision = 3; Message("Incorrect"); Message($"For x = {ComplexAsString(x)} and r = {DoubleAsStringWithPrecision(r, precision)} expected return {ComplexAsString(expected)}, actual return {ComplexAsString(actual)}."); return false; diff --git a/katas/content/complex_arithmetic/complex_powers_real/index.md b/katas/content/complex_arithmetic/complex_powers_real/index.md index 7b1fa94227..30eec5293a 100644 --- a/katas/content/complex_arithmetic/complex_powers_real/index.md +++ b/katas/content/complex_arithmetic/complex_powers_real/index.md @@ -9,5 +9,5 @@ Need a hint? You can use the fact that $r = e^{\ln r}$ to convert exponent bases. Remember though, $\ln r$ is only defined for positive numbers - make sure to check for $r = 0$ separately! - Q# namespace `Microsoft.Quantum.Math` includes useful functions `Log()`, `Sin()`, and `Cos()`. + Q# namespace `Std.Math` includes useful functions `Log()`, `Sin()`, and `Cos()`. diff --git a/katas/content/complex_arithmetic/index.md b/katas/content/complex_arithmetic/index.md index a3829c10f9..c03a8774c8 100644 --- a/katas/content/complex_arithmetic/index.md +++ b/katas/content/complex_arithmetic/index.md @@ -67,7 +67,7 @@ For example, $3+4i$ or $-5-7i$ are valid complex numbers. Note that purely real When performing operations on complex numbers, it's often helpful to treat them as polynomials in terms of $i$. Let's see how to do the main arithmetic operations on complex numbers. -> In Q#, complex numbers are represented as user-defined struct type `Complex` from the `Microsoft.Quantum.Math` namespace. +> In Q#, complex numbers are represented as user-defined struct type `Complex` from the `Std.Math` namespace. > > Given a complex number $x = a + bi$, you can access its real and imaginary parts using their names: `let (a, b) = (x.Real, x.Imag);`. > @@ -233,7 +233,7 @@ Another way to think about this is that you're taking a point that is $1$ unit a A complex number of the format $r \cdot e^{i\theta}$ will be represented by a point which is $r$ units away from the origin, in the direction specified by the angle $\theta$. Sometimes $\theta$ will be referred to as the number's **argument** or **phase**. -> In Q#, complex numbers in polar form are represented as user-defined struct type `ComplexPolar` from the `Microsoft.Quantum.Math` namespace. +> In Q#, complex numbers in polar form are represented as user-defined struct type `ComplexPolar` from the `Std.Math` namespace. > > Given a complex number $x = r \cdot e^{i\theta}$, you can access its magnitude and phase using their names: `let r = x.Magnitude;` and `let theta = x.Argument;`. > diff --git a/katas/content/complex_arithmetic/polar_multiplication/Placeholder.qs b/katas/content/complex_arithmetic/polar_multiplication/Placeholder.qs index 30c96bd3a8..fed58300e2 100644 --- a/katas/content/complex_arithmetic/polar_multiplication/Placeholder.qs +++ b/katas/content/complex_arithmetic/polar_multiplication/Placeholder.qs @@ -1,6 +1,6 @@ namespace Kata { - open Microsoft.Quantum.Math; - + import Std.Math.*; + function ComplexPolarMult(x : ComplexPolar, y : ComplexPolar) : ComplexPolar { // Implement your solution here... return ComplexPolar(0., 0.); diff --git a/katas/content/complex_arithmetic/polar_multiplication/Solution.qs b/katas/content/complex_arithmetic/polar_multiplication/Solution.qs index 095f7f5afd..a42795f563 100644 --- a/katas/content/complex_arithmetic/polar_multiplication/Solution.qs +++ b/katas/content/complex_arithmetic/polar_multiplication/Solution.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; function ComplexPolarMult(x : ComplexPolar, y : ComplexPolar) : ComplexPolar { mutable theta = x.Argument + y.Argument; diff --git a/katas/content/complex_arithmetic/polar_multiplication/Verification.qs b/katas/content/complex_arithmetic/polar_multiplication/Verification.qs index 1d6c3e51aa..f1184caa03 100644 --- a/katas/content/complex_arithmetic/polar_multiplication/Verification.qs +++ b/katas/content/complex_arithmetic/polar_multiplication/Verification.qs @@ -1,10 +1,10 @@ -namespace Kata.Verification { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Math; +namespace Kata.Verification { + import Std.Convert.*; + import Std.Math.*; @EntryPoint() operation CheckSolution() : Bool { - for _ in 0 .. 24 { + for _ in 0..24 { let x = DrawRandomComplex(); let y = DrawRandomComplex(); let xp = ComplexAsComplexPolar(x); @@ -12,7 +12,7 @@ namespace Kata.Verification { let expected = ComplexAsComplexPolar(TimesC(x, y)); let actual = Kata.ComplexPolarMult(xp, yp); - + if not ComplexPolarEqual(expected, actual) { Message("Incorrect"); Message($"For x = {ComplexPolarAsString(xp)}, y = {ComplexPolarAsString(yp)} " + @@ -24,4 +24,4 @@ namespace Kata.Verification { Message("Correct!"); return true; } -} \ No newline at end of file +} diff --git a/katas/content/complex_arithmetic/polar_multiplication/index.md b/katas/content/complex_arithmetic/polar_multiplication/index.md index e2fc4f215c..7db9c5c8ac 100644 --- a/katas/content/complex_arithmetic/polar_multiplication/index.md +++ b/katas/content/complex_arithmetic/polar_multiplication/index.md @@ -20,4 +20,4 @@ Return the product of $x$ and $y$ as a complex polar number $x \cdot y = r_{3}e^ Is the value of $\theta$ in the product incorrect? Remember you might have to check your boundaries and adjust it to be in the range requested. -> Q# function `TimesCP` from `Microsoft.Quantum.Math` namespace multiplies two complex numbers, but it doesn't normalize the argument of the resulting number. For educational purposes, try to do this task by hand. +> Q# function `TimesCP` from `Std.Math` namespace multiplies two complex numbers, but it doesn't normalize the argument of the resulting number. For educational purposes, try to do this task by hand. diff --git a/katas/content/complex_arithmetic/polar_to_cartesian/Placeholder.qs b/katas/content/complex_arithmetic/polar_to_cartesian/Placeholder.qs index 7fba10a647..a3154afacd 100644 --- a/katas/content/complex_arithmetic/polar_to_cartesian/Placeholder.qs +++ b/katas/content/complex_arithmetic/polar_to_cartesian/Placeholder.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; function ComplexPolarToComplex(x : ComplexPolar) : Complex { // Implement your solution here... diff --git a/katas/content/complex_arithmetic/polar_to_cartesian/Solution.qs b/katas/content/complex_arithmetic/polar_to_cartesian/Solution.qs index 57eb2a611b..a06c10761d 100644 --- a/katas/content/complex_arithmetic/polar_to_cartesian/Solution.qs +++ b/katas/content/complex_arithmetic/polar_to_cartesian/Solution.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; function ComplexPolarToComplex(x : ComplexPolar) : Complex { let (r, theta) = (x.Magnitude, x.Argument); diff --git a/katas/content/complex_arithmetic/polar_to_cartesian/Verification.qs b/katas/content/complex_arithmetic/polar_to_cartesian/Verification.qs index 24dbac48b7..b66d22b347 100644 --- a/katas/content/complex_arithmetic/polar_to_cartesian/Verification.qs +++ b/katas/content/complex_arithmetic/polar_to_cartesian/Verification.qs @@ -1,15 +1,15 @@ namespace Kata.Verification { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Math; + import Std.Convert.*; + import Std.Math.*; @EntryPoint() - operation CheckSolution() : Bool { - for _ in 0 .. 24 { + operation CheckSolution() : Bool { + for _ in 0..24 { let x = ComplexAsComplexPolar(DrawRandomComplex()); let expected = ComplexPolarAsComplex(x); let actual = Kata.ComplexPolarToComplex(x); - + if not ComplexEqual(expected, actual) { Message("Incorrect"); Message($"For x = {ComplexPolarAsString(x)} expected return {ComplexAsString(expected)}, actual return {ComplexAsString(actual)}."); @@ -20,4 +20,4 @@ namespace Kata.Verification { Message("Correct!"); return true; } -} \ No newline at end of file +} diff --git a/katas/content/complex_arithmetic/polar_to_cartesian/index.md b/katas/content/complex_arithmetic/polar_to_cartesian/index.md index a8cbb5b764..a3e7608f04 100644 --- a/katas/content/complex_arithmetic/polar_to_cartesian/index.md +++ b/katas/content/complex_arithmetic/polar_to_cartesian/index.md @@ -11,4 +11,4 @@ A video explanation of this conversion can be found [here](https://www.youtube.c -> Q# function `ComplexPolarAsComplex` from `Microsoft.Quantum.Math` namespace converts a complex number of type `ComplexPolar` to a complex number of type `Complex`. For educational purposes, try to do this task by hand. +> Q# function `ComplexPolarAsComplex` from `Std.Math` namespace converts a complex number of type `ComplexPolar` to a complex number of type `Complex`. For educational purposes, try to do this task by hand. diff --git a/katas/content/deutsch_algo/examples/DeutschAlgorithmDemo.qs b/katas/content/deutsch_algo/examples/DeutschAlgorithmDemo.qs index 5d226735d1..9294c0a86d 100644 --- a/katas/content/deutsch_algo/examples/DeutschAlgorithmDemo.qs +++ b/katas/content/deutsch_algo/examples/DeutschAlgorithmDemo.qs @@ -1,26 +1,27 @@ namespace Kata { - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Math; + import Std.Diagnostics.*; + import Std.Math.*; @EntryPoint() - operation DeutschAlgorithmDemo () : Unit { - for (oracle, name) in [(PhaseOracle_Zero, "f(x) = 0"), - (PhaseOracle_One, "f(x) = 1"), - (PhaseOracle_X, "f(x) = x"), - (PhaseOracle_OneMinusX, "f(x) = 1-x")] { + operation DeutschAlgorithmDemo() : Unit { + for (oracle, name) in [ + (PhaseOracle_Zero, "f(x) = 0"), + (PhaseOracle_One, "f(x) = 1"), + (PhaseOracle_X, "f(x) = x"), + (PhaseOracle_OneMinusX, "f(x) = 1-x") + ] { let isConstant = DeutschAlgorithm(oracle); Message($"{name} identified as {isConstant ? "constant" | "variable"}"); } } - operation PhaseOracle_Zero (x : Qubit) : Unit { - } + operation PhaseOracle_Zero(x : Qubit) : Unit {} - operation PhaseOracle_One (x : Qubit) : Unit { + operation PhaseOracle_One(x : Qubit) : Unit { R(PauliI, 2.0 * PI(), x); } - operation PhaseOracle_X (x : Qubit) : Unit { + operation PhaseOracle_X(x : Qubit) : Unit { Z(x); } @@ -29,11 +30,11 @@ namespace Kata { R(PauliI, 2.0 * PI(), x); } - operation DeutschAlgorithm (oracle : Qubit => Unit) : Bool { + operation DeutschAlgorithm(oracle : Qubit => Unit) : Bool { use x = Qubit(); H(x); oracle(x); H(x); return MResetZ(x) == Zero; } -} \ No newline at end of file +} diff --git a/katas/content/deutsch_algo/examples/OracleImplementationDemo.qs b/katas/content/deutsch_algo/examples/OracleImplementationDemo.qs index 39df507175..934bf0ef1e 100644 --- a/katas/content/deutsch_algo/examples/OracleImplementationDemo.qs +++ b/katas/content/deutsch_algo/examples/OracleImplementationDemo.qs @@ -1,22 +1,22 @@ namespace Kata { - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Math; + import Std.Diagnostics.*; + import Std.Math.*; - operation PhaseOracle_Zero (x : Qubit) : Unit { + operation PhaseOracle_Zero(x : Qubit) : Unit { // Do nothing... } - operation PhaseOracle_One (x : Qubit) : Unit { + operation PhaseOracle_One(x : Qubit) : Unit { // Apply a global phase of -1 R(PauliI, 2.0 * PI(), x); } - operation PhaseOracle_X (x : Qubit) : Unit { + operation PhaseOracle_X(x : Qubit) : Unit { Z(x); } @EntryPoint() - operation OracleImplementationDemo () : Unit { + operation OracleImplementationDemo() : Unit { use q = Qubit(); Ry(2.0 * ArcCos(0.6), q); Message("The qubit state before oracle application is 0.6|0⟩ + 0.8|0⟩:"); @@ -32,4 +32,4 @@ namespace Kata { Reset(q); } -} \ No newline at end of file +} diff --git a/katas/content/deutsch_algo/implement_algo/Verification.qs b/katas/content/deutsch_algo/implement_algo/Verification.qs index 0f8579ea59..0b8c7e7e80 100644 --- a/katas/content/deutsch_algo/implement_algo/Verification.qs +++ b/katas/content/deutsch_algo/implement_algo/Verification.qs @@ -1,12 +1,14 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; + import KatasUtils.*; + import Std.Math.*; operation CheckSolution() : Bool { - for (oracle, expected, name) in [(I, true, "f(x) = 0"), - (R(PauliI, 2.0 * PI(), _), true, "f(x) = 1"), - (Z, false, "f(x) = x"), - (PhaseOracle_OneMinusX, false, "f(x) = 1 - x")] { + for (oracle, expected, name) in [ + (I, true, "f(x) = 0"), + (R(PauliI, 2.0 * PI(), _), true, "f(x) = 1"), + (Z, false, "f(x) = x"), + (PhaseOracle_OneMinusX, false, "f(x) = 1 - x") + ] { let actual = Kata.DeutschAlgorithm(oracle); if actual != expected { @@ -22,7 +24,7 @@ namespace Kata.Verification { true } - function ConstantOrVariable (value : Bool) : String { + function ConstantOrVariable(value : Bool) : String { return value ? "constant" | "variable"; } diff --git a/katas/content/deutsch_algo/one_minus_x_oracle/Solution.qs b/katas/content/deutsch_algo/one_minus_x_oracle/Solution.qs index ad3312bf0e..b9f96680dd 100644 --- a/katas/content/deutsch_algo/one_minus_x_oracle/Solution.qs +++ b/katas/content/deutsch_algo/one_minus_x_oracle/Solution.qs @@ -1,6 +1,6 @@ namespace Kata { - open Microsoft.Quantum.Math; - + import Std.Math.*; + operation PhaseOracle_OneMinusX(x : Qubit) : Unit is Adj + Ctl { Z(x); R(PauliI, 2.0 * PI(), x); diff --git a/katas/content/deutsch_algo/one_minus_x_oracle/Verification.qs b/katas/content/deutsch_algo/one_minus_x_oracle/Verification.qs index c63fd03c24..74fae0e899 100644 --- a/katas/content/deutsch_algo/one_minus_x_oracle/Verification.qs +++ b/katas/content/deutsch_algo/one_minus_x_oracle/Verification.qs @@ -1,6 +1,6 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; + import KatasUtils.*; + import Std.Math.*; operation PhaseOracle_OneMinusX_Reference(x : Qubit) : Unit is Adj + Ctl { Z(x); diff --git a/katas/content/deutsch_jozsa/examples/DeutschJozsaAlgorithmDemo.qs b/katas/content/deutsch_jozsa/examples/DeutschJozsaAlgorithmDemo.qs index 32e3250141..c7f9903b2d 100644 --- a/katas/content/deutsch_jozsa/examples/DeutschJozsaAlgorithmDemo.qs +++ b/katas/content/deutsch_jozsa/examples/DeutschJozsaAlgorithmDemo.qs @@ -1,20 +1,22 @@ namespace Kata { - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Math; + import Std.Diagnostics.*; + import Std.Math.*; @EntryPoint() - operation DeutschJozsaAlgorithmDemo () : Unit { - for (N, oracle, name) in [(2, qs => (), "f(x) = 0"), - (2, qs => R(PauliI, 2.0 * PI(), qs[0]), "f(x) = 1"), - (3, qs => Z(qs[Length(qs) - 1]), "f(x) = x mod 2"), - (3, qs => Z(qs[0]), "f(x) = most significant bit of x"), - (3, ApplyToEach(Z, _), "f(x) = parity of x")] { + operation DeutschJozsaAlgorithmDemo() : Unit { + for (N, oracle, name) in [ + (2, qs => (), "f(x) = 0"), + (2, qs => R(PauliI, 2.0 * PI(), qs[0]), "f(x) = 1"), + (3, qs => Z(qs[Length(qs) - 1]), "f(x) = x mod 2"), + (3, qs => Z(qs[0]), "f(x) = most significant bit of x"), + (3, ApplyToEach(Z, _), "f(x) = parity of x") + ] { let isConstant = DeutschJozsaAlgorithm(N, oracle); Message($"{name} identified as {isConstant ? "constant" | "balanced"}"); } } - operation DeutschJozsaAlgorithm (N : Int, oracle : Qubit[] => Unit) : Bool { + operation DeutschJozsaAlgorithm(N : Int, oracle : Qubit[] => Unit) : Bool { mutable isConstant = true; use x = Qubit[N]; ApplyToEach(H, x); @@ -27,4 +29,4 @@ namespace Kata { } return isConstant; } -} \ No newline at end of file +} diff --git a/katas/content/deutsch_jozsa/examples/OracleImplementationDemo.qs b/katas/content/deutsch_jozsa/examples/OracleImplementationDemo.qs index 4b8dcfb04d..0a493590ba 100644 --- a/katas/content/deutsch_jozsa/examples/OracleImplementationDemo.qs +++ b/katas/content/deutsch_jozsa/examples/OracleImplementationDemo.qs @@ -1,24 +1,24 @@ namespace Kata { - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Math; + import Std.Diagnostics.*; + import Std.Math.*; - operation PhaseOracle_Zero (x : Qubit[]) : Unit { + operation PhaseOracle_Zero(x : Qubit[]) : Unit { // Do nothing... } - operation PhaseOracle_One (x : Qubit[]) : Unit { + operation PhaseOracle_One(x : Qubit[]) : Unit { // Apply a global phase of -1 R(PauliI, 2.0 * PI(), x[0]); } - operation PhaseOracle_Xmod2 (x : Qubit[]) : Unit { + operation PhaseOracle_Xmod2(x : Qubit[]) : Unit { let N = Length(x); // Array elements are indexed 0 through Length(x) - 1, inclusive. Z(x[N - 1]); } @EntryPoint() - operation OracleImplementationDemo () : Unit { + operation OracleImplementationDemo() : Unit { use qs = Qubit[2]; Ry(2.0 * ArcCos(0.5), qs[0]); Ry(2.0 * ArcCos(0.6), qs[1]); @@ -35,4 +35,4 @@ namespace Kata { ResetAll(qs); } -} \ No newline at end of file +} diff --git a/katas/content/deutsch_jozsa/implement_bv/Verification.qs b/katas/content/deutsch_jozsa/implement_bv/Verification.qs index 92d37d55a7..01d7b8fe50 100644 --- a/katas/content/deutsch_jozsa/implement_bv/Verification.qs +++ b/katas/content/deutsch_jozsa/implement_bv/Verification.qs @@ -1,16 +1,17 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; + import KatasUtils.*; + import Std.Math.*; operation CheckSolution() : Bool { - for (n, oracle, expected, name) in [(2, qs => (), [0, 0], "f(x) = 0"), - (3, qs => (), [0, 0, 0], "f(x) = 0"), - (2, ApplyToEach(Z, _), [1, 1], "f(x) = parity of x"), - (3, ApplyToEach(Z, _), [1, 1, 1], "f(x) = parity of x"), - (2, qs => Z(qs[0]), [1, 0], "f(x) = most significant bit of x"), - (3, qs => Z(qs[2]), [0, 0, 1], "f(x) = least significant bit of x"), - (3, qs => Z(qs[1]), [0, 1, 0], "f(x) = middle bit of x") - ] { + for (n, oracle, expected, name) in [ + (2, qs => (), [0, 0], "f(x) = 0"), + (3, qs => (), [0, 0, 0], "f(x) = 0"), + (2, ApplyToEach(Z, _), [1, 1], "f(x) = parity of x"), + (3, ApplyToEach(Z, _), [1, 1, 1], "f(x) = parity of x"), + (2, qs => Z(qs[0]), [1, 0], "f(x) = most significant bit of x"), + (3, qs => Z(qs[2]), [0, 0, 1], "f(x) = least significant bit of x"), + (3, qs => Z(qs[1]), [0, 1, 0], "f(x) = middle bit of x") + ] { let actual = Kata.BernsteinVaziraniAlgorithm(n, oracle); if actual != expected { Message("Incorrect."); diff --git a/katas/content/deutsch_jozsa/implement_dj/Verification.qs b/katas/content/deutsch_jozsa/implement_dj/Verification.qs index 06d2589e07..e98319eefa 100644 --- a/katas/content/deutsch_jozsa/implement_dj/Verification.qs +++ b/katas/content/deutsch_jozsa/implement_dj/Verification.qs @@ -1,14 +1,15 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; + import KatasUtils.*; + import Std.Math.*; operation CheckSolution() : Bool { - for (n, oracle, expected, name) in [(2, qs => (), true, "f(x) = 0"), - (3, qs => R(PauliI, 2.0 * PI(), qs[0]), true, "f(x) = 1"), - (3, ApplyToEach(Z, _), false, "f(x) = parity of x"), - (3, qs => Z(qs[0]), false, "f(x) = most significant bit of x"), - (3, qs => Z(qs[Length(qs) - 1]), false, "f(x) = x mod 2"), - ] { + for (n, oracle, expected, name) in [ + (2, qs => (), true, "f(x) = 0"), + (3, qs => R(PauliI, 2.0 * PI(), qs[0]), true, "f(x) = 1"), + (3, ApplyToEach(Z, _), false, "f(x) = parity of x"), + (3, qs => Z(qs[0]), false, "f(x) = most significant bit of x"), + (3, qs => Z(qs[Length(qs) - 1]), false, "f(x) = x mod 2"), + ] { let actual = Kata.DeutschJozsaAlgorithm(n, oracle); if actual != expected { Message("Incorrect."); @@ -23,7 +24,7 @@ namespace Kata.Verification { true } - function ConstantOrBalanced (value : Bool) : String { + function ConstantOrBalanced(value : Bool) : String { return value ? "constant" | "balanced"; } } diff --git a/katas/content/deutsch_jozsa/msb_oracle/Verification.qs b/katas/content/deutsch_jozsa/msb_oracle/Verification.qs index 20d639ad71..4722919b83 100644 --- a/katas/content/deutsch_jozsa/msb_oracle/Verification.qs +++ b/katas/content/deutsch_jozsa/msb_oracle/Verification.qs @@ -1,6 +1,6 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; + import KatasUtils.*; + import Std.Math.*; operation PhaseOracle_MostSignificantBit_Reference(x : Qubit[]) : Unit is Adj + Ctl { Z(x[0]); @@ -9,7 +9,7 @@ namespace Kata.Verification { operation CheckSolution() : Bool { let solution = Kata.PhaseOracle_MostSignificantBit; let reference = PhaseOracle_MostSignificantBit_Reference; - for N in 1 .. 4 { + for N in 1..4 { if not CheckOperationsAreEqualStrict(N, solution, reference) { Message("Incorrect."); Message($"Hint: examine the effect your solution has on the {N}-qubit and compare it with the effect it " + diff --git a/katas/content/deutsch_jozsa/parity_oracle/Verification.qs b/katas/content/deutsch_jozsa/parity_oracle/Verification.qs index 9a8f43df71..dc4bcea63a 100644 --- a/katas/content/deutsch_jozsa/parity_oracle/Verification.qs +++ b/katas/content/deutsch_jozsa/parity_oracle/Verification.qs @@ -1,6 +1,6 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; + import KatasUtils.*; + import Std.Math.*; operation PhaseOracle_Parity_Reference(x : Qubit[]) : Unit is Adj + Ctl { for xi in x { @@ -11,7 +11,7 @@ namespace Kata.Verification { operation CheckSolution() : Bool { let solution = Kata.PhaseOracle_Parity; let reference = PhaseOracle_Parity_Reference; - for N in 1 .. 4 { + for N in 1..4 { if not CheckOperationsAreEqualStrict(N, solution, reference) { Message("Incorrect."); Message($"Hint: examine the effect your solution has on the {N}-qubit state and compare it with the effect it " + diff --git a/katas/content/distinguishing_states/Common.qs b/katas/content/distinguishing_states/Common.qs index 287e9c5e4b..6dabe2a196 100644 --- a/katas/content/distinguishing_states/Common.qs +++ b/katas/content/distinguishing_states/Common.qs @@ -1,9 +1,8 @@ -namespace Kata.Verification{ - open Microsoft.Quantum.Arrays; - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Intrinsic; - open Microsoft.Quantum.Math; +namespace Kata.Verification { + import Std.Arrays.*; + import Std.Convert.*; + import Std.Diagnostics.*; + import Std.Math.*; operation StatePrep_BasisStateMeasurement( qs : Qubit[], @@ -41,11 +40,11 @@ namespace Kata.Verification{ } } - function StatePrep_FindFirstDiff ( + function StatePrep_FindFirstDiff( bits1 : Bool[], bits2 : Bool[] ) : Int { - for i in 0 .. Length(bits1) - 1 { + for i in 0..Length(bits1) - 1 { if bits1[i] != bits2[i] { return i; } @@ -54,26 +53,26 @@ namespace Kata.Verification{ return -1; } - operation StatePrep_SuperpositionMeasurement ( + operation StatePrep_SuperpositionMeasurement( qs : Qubit[], bits1 : Bool[][], bits2 : Bool[][], state : Int, - dummyVar: Double + dummyVar : Double ) : Unit is Adj { let bits = state == 0 ? bits1 | bits2; StatePrep_BitstringSuperposition(qs, bits); } // A combination of tasks 14 and 15 from the Superposition kata - operation StatePrep_BitstringSuperposition ( + operation StatePrep_BitstringSuperposition( qs : Qubit[], bits : Bool[][] ) : Unit is Adj + Ctl { let L = Length(bits); Fact(L == 1 or L == 2 or L == 4, "State preparation only supports arrays of 1, 2 or 4 bit strings."); if L == 1 { - for i in 0 .. Length(qs) - 1 { + for i in 0..Length(qs) - 1 { if bits[0][i] { X(qs[i]); } @@ -87,7 +86,7 @@ namespace Kata.Verification{ H(qs[firstDiff]); // iterate through the bit strings again setting the final state of qubits - for i in 0 .. Length(qs) - 1 { + for i in 0..Length(qs) - 1 { if bits[0][i] == bits[1][i] { // if two bits are the same, apply X or nothing if bits[0][i] { @@ -112,8 +111,8 @@ namespace Kata.Verification{ ApplyToEachCA(H, anc); // Set up the right pattern on the main qubits with control on ancillas - for i in 0 .. 3 { - for j in 0 .. N - 1 { + for i in 0..3 { + for j in 0..N - 1 { if bits[i][j] { ApplyControlledOnInt(i, X, anc, qs[j]); } @@ -121,7 +120,7 @@ namespace Kata.Verification{ } // Uncompute the ancillas, using patterns on main qubits as control - for i in 0 .. 3 { + for i in 0..3 { if i % 2 == 1 { ApplyControlledOnBitString(bits[i], X, qs, anc[0]); } diff --git a/katas/content/distinguishing_states/a_b/Verification.qs b/katas/content/distinguishing_states/a_b/Verification.qs index 271932b889..4c6a8529ed 100644 --- a/katas/content/distinguishing_states/a_b/Verification.qs +++ b/katas/content/distinguishing_states/a_b/Verification.qs @@ -1,7 +1,7 @@ namespace Kata.Verification { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Math; - open Microsoft.Quantum.Katas; + import Std.Convert.*; + import Std.Math.*; + import KatasUtils.*; // |A⟩ = cos(alpha) * |0⟩ + sin(alpha) * |1⟩, // |B⟩ = - sin(alpha) * |0⟩ + cos(alpha) * |1⟩. @@ -18,7 +18,7 @@ namespace Kata.Verification { // We can use the StatePrep_IsQubitA operation for the testing operation CheckSolution() : Bool { - for i in 0 .. 10 { + for i in 0..10 { let alpha = (PI() * IntAsDouble(i)) / 10.0; let isCorrect = DistinguishTwoStates_SingleQubit( StatePrep_IsQubitA(alpha, _, _), diff --git a/katas/content/distinguishing_states/all_zeros_w/Verification.qs b/katas/content/distinguishing_states/all_zeros_w/Verification.qs index e9826f356c..3d8ad05d84 100644 --- a/katas/content/distinguishing_states/all_zeros_w/Verification.qs +++ b/katas/content/distinguishing_states/all_zeros_w/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; operation StatePrep_AllZerosOrWState( qs : Qubit[], @@ -14,13 +14,15 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { - for i in 2 .. 6 { + for i in 2..6 { let isCorrect = DistinguishStates_MultiQubit( - i, 2, + i, + 2, StatePrep_AllZerosOrWState, Kata.AllZerosOrWState, false, - ["|0...0⟩", "|W⟩"]); + ["|0...0⟩", "|W⟩"] + ); if not isCorrect { Message("Incorrect."); diff --git a/katas/content/distinguishing_states/four_basis_states/Verification.qs b/katas/content/distinguishing_states/four_basis_states/Verification.qs index c3986e1636..55c4fbe99c 100644 --- a/katas/content/distinguishing_states/four_basis_states/Verification.qs +++ b/katas/content/distinguishing_states/four_basis_states/Verification.qs @@ -1,7 +1,7 @@ namespace Kata.Verification { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Math; - open Microsoft.Quantum.Katas; + import Std.Convert.*; + import Std.Math.*; + import KatasUtils.*; operation CheckSolution() : Bool { let isCorrect = DistinguishStates_MultiQubit(2, 4, StatePrep_BasisStateMeasurement, Kata.BasisStateMeasurement, false, ["|00⟩", "|01⟩", "|10⟩", "|11⟩"]); diff --git a/katas/content/distinguishing_states/four_bell_states/Verification.qs b/katas/content/distinguishing_states/four_bell_states/Verification.qs index ea4e71c8dc..c7fcfb7da9 100644 --- a/katas/content/distinguishing_states/four_bell_states/Verification.qs +++ b/katas/content/distinguishing_states/four_bell_states/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; // 0 - |Φ⁺⟩ = (|00⟩ + |11⟩) / sqrt(2) // 1 - |Φ⁻⟩ = (|00⟩ - |11⟩) / sqrt(2) diff --git a/katas/content/distinguishing_states/four_orthogonal_two_qubit/Verification.qs b/katas/content/distinguishing_states/four_orthogonal_two_qubit/Verification.qs index 72f4e7a561..0e056db4b7 100644 --- a/katas/content/distinguishing_states/four_orthogonal_two_qubit/Verification.qs +++ b/katas/content/distinguishing_states/four_orthogonal_two_qubit/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; // 0 - (|00⟩ + |01⟩ + |10⟩ + |11⟩) / 2 // 1 - (|00⟩ - |01⟩ + |10⟩ - |11⟩) / 2 diff --git a/katas/content/distinguishing_states/four_orthogonal_two_qubit_part_two/Verification.qs b/katas/content/distinguishing_states/four_orthogonal_two_qubit_part_two/Verification.qs index ee34e3a022..19255c4c1a 100644 --- a/katas/content/distinguishing_states/four_orthogonal_two_qubit_part_two/Verification.qs +++ b/katas/content/distinguishing_states/four_orthogonal_two_qubit_part_two/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; // 0 - ( |00⟩ - |01⟩ - |10⟩ - |11⟩) / 2 // 1 - (-|00⟩ + |01⟩ - |10⟩ - |11⟩) / 2 @@ -27,7 +27,8 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { let isCorrect = DistinguishStates_MultiQubit( - 2, 4, + 2, + 4, StatePrep_TwoQubitStateTwo, Kata.TwoQubitStateTwo, false, diff --git a/katas/content/distinguishing_states/ghz_w/Verification.qs b/katas/content/distinguishing_states/ghz_w/Verification.qs index dc0be6e8b5..1a6d9ce87b 100644 --- a/katas/content/distinguishing_states/ghz_w/Verification.qs +++ b/katas/content/distinguishing_states/ghz_w/Verification.qs @@ -1,9 +1,9 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; operation GHZ_State_Reference(qs : Qubit[]) : Unit is Adj { H(qs[0]); - for q in qs[1 ... ] { + for q in qs[1...] { CNOT(qs[0], q); } } @@ -25,13 +25,15 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { - for i in 2 .. 6 { + for i in 2..6 { let isCorrect = DistinguishStates_MultiQubit( - i, 2, + i, + 2, StatePrep_GHZOrWState, Kata.GHZOrWState, false, - ["|GHZ⟩", "|W⟩"]); + ["|GHZ⟩", "|W⟩"] + ); if not isCorrect { Message("Incorrect."); diff --git a/katas/content/distinguishing_states/peres_wooters_game/Solution.qs b/katas/content/distinguishing_states/peres_wooters_game/Solution.qs index 002cf9fbb5..0ba246c0aa 100644 --- a/katas/content/distinguishing_states/peres_wooters_game/Solution.qs +++ b/katas/content/distinguishing_states/peres_wooters_game/Solution.qs @@ -1,6 +1,6 @@ namespace Kata { - open Microsoft.Quantum.Math; - operation IsQubitNotInABC (q : Qubit) : Int { + import Std.Math.*; + operation IsQubitNotInABC(q : Qubit) : Int { let alpha = ArcCos(Sqrt(2.0 / 3.0)); use a = Qubit(); @@ -20,16 +20,13 @@ namespace Kata { if (res0 == Zero and res1 == Zero) { return 0; - } - elif (res0 == One and res1 == Zero) { + } elif (res0 == One and res1 == Zero) { return 1; - } - elif (res0 == Zero and res1 == One) { + } elif (res0 == Zero and res1 == One) { return 2; - } - else { + } else { // this should never occur return 3; } } -} \ No newline at end of file +} diff --git a/katas/content/distinguishing_states/peres_wooters_game/Verification.qs b/katas/content/distinguishing_states/peres_wooters_game/Verification.qs index 8bf13708b1..f0f2edf574 100644 --- a/katas/content/distinguishing_states/peres_wooters_game/Verification.qs +++ b/katas/content/distinguishing_states/peres_wooters_game/Verification.qs @@ -1,21 +1,19 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Random; - open Microsoft.Quantum.Math; + import KatasUtils.*; + import Std.Convert.*; + import Std.Random.*; + import Std.Math.*; - operation StatePrep_IsQubitNotInABC (q : Qubit, state : Int) : Unit { + operation StatePrep_IsQubitNotInABC(q : Qubit, state : Int) : Unit { let alpha = (2.0 * PI()) / 3.0; H(q); if state == 0 { // convert |0⟩ to 1/sqrt(2) (|0⟩ + |1⟩) - } - elif state == 1 { + } elif state == 1 { // convert |0⟩ to 1/sqrt(2) (|0⟩ + ω |1⟩), where ω = exp(2iπ/3) R1(alpha, q); - } - else { + } else { // convert |0⟩ to 1/sqrt(2) (|0⟩ + ω² |1⟩), where ω = exp(2iπ/3) R1(2.0 * alpha, q); } @@ -23,14 +21,14 @@ namespace Kata.Verification { @EntryPoint() - operation CheckSolution () : Bool { + operation CheckSolution() : Bool { let nTotal = 1000; mutable bad_value = 0; mutable wrong_state = 0; use qs = Qubit[1]; - for i in 1 .. nTotal { + for i in 1..nTotal { // get a random integer to define the state of the qubits let state = DrawRandomInt(0, 2); @@ -68,4 +66,4 @@ namespace Kata.Verification { return false; } } -} \ No newline at end of file +} diff --git a/katas/content/distinguishing_states/plus_minus/Verification.qs b/katas/content/distinguishing_states/plus_minus/Verification.qs index 62a00bc7b3..681d003b2b 100644 --- a/katas/content/distinguishing_states/plus_minus/Verification.qs +++ b/katas/content/distinguishing_states/plus_minus/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; operation StatePrep_IsQubitPlus(q : Qubit, state : Int) : Unit is Adj { if state == 1 { diff --git a/katas/content/distinguishing_states/two_basis_states_bit_strings/Verification.qs b/katas/content/distinguishing_states/two_basis_states_bit_strings/Verification.qs index 94e53b39e9..0355b8ccf3 100644 --- a/katas/content/distinguishing_states/two_basis_states_bit_strings/Verification.qs +++ b/katas/content/distinguishing_states/two_basis_states_bit_strings/Verification.qs @@ -1,11 +1,11 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; operation StatePrep_Bitstring( qs : Qubit[], bits : Bool[] ) : Unit is Adj { - for i in 0 .. Length(qs) - 1 { + for i in 0..Length(qs) - 1 { if bits[i] { X(qs[i]); } diff --git a/katas/content/distinguishing_states/two_orthogonal_three_qubit/Placeholder.qs b/katas/content/distinguishing_states/two_orthogonal_three_qubit/Placeholder.qs index 1c56d62e3a..0f53646a68 100644 --- a/katas/content/distinguishing_states/two_orthogonal_three_qubit/Placeholder.qs +++ b/katas/content/distinguishing_states/two_orthogonal_three_qubit/Placeholder.qs @@ -1,7 +1,7 @@ namespace Kata { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Math; - open Microsoft.Quantum.Measurement; + import Std.Convert.*; + import Std.Math.*; + import Std.Measurement.*; operation ThreeQubitMeasurement(qs : Qubit[]) : Int { // Implement your solution here... diff --git a/katas/content/distinguishing_states/two_orthogonal_three_qubit/Solution.qs b/katas/content/distinguishing_states/two_orthogonal_three_qubit/Solution.qs index bbe5e3a57d..ffa2033316 100644 --- a/katas/content/distinguishing_states/two_orthogonal_three_qubit/Solution.qs +++ b/katas/content/distinguishing_states/two_orthogonal_three_qubit/Solution.qs @@ -1,7 +1,7 @@ namespace Kata { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Math; - open Microsoft.Quantum.Measurement; + import Std.Convert.*; + import Std.Math.*; + import Std.Measurement.*; operation ThreeQubitMeasurement(qs : Qubit[]) : Int { R1(-2.0 * PI() / 3.0, qs[1]); diff --git a/katas/content/distinguishing_states/two_orthogonal_three_qubit/Verification.qs b/katas/content/distinguishing_states/two_orthogonal_three_qubit/Verification.qs index b37f42883b..84487b2f52 100644 --- a/katas/content/distinguishing_states/two_orthogonal_three_qubit/Verification.qs +++ b/katas/content/distinguishing_states/two_orthogonal_three_qubit/Verification.qs @@ -1,6 +1,6 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; + import KatasUtils.*; + import Std.Math.*; operation StatePrep_ThreeQubitMeasurement( qs : Qubit[], @@ -23,11 +23,13 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { let isCorrect = DistinguishStates_MultiQubit( - 3, 2, + 3, + 2, StatePrep_ThreeQubitMeasurement, Kata.ThreeQubitMeasurement, false, - ["1/sqrt(3) (|100⟩ + ω |010⟩ + ω² |001⟩)", "1/sqrt(3) (|100⟩ + ω² |010⟩ + ω |001⟩)"]); + ["1/sqrt(3) (|100⟩ + ω |010⟩ + ω² |001⟩)", "1/sqrt(3) (|100⟩ + ω² |010⟩ + ω |001⟩)"] + ); if not isCorrect { Message("Incorrect."); diff --git a/katas/content/distinguishing_states/two_superposition_states_bit_strings/Placeholder.qs b/katas/content/distinguishing_states/two_superposition_states_bit_strings/Placeholder.qs index 2f807e3b2a..cf20b68737 100644 --- a/katas/content/distinguishing_states/two_superposition_states_bit_strings/Placeholder.qs +++ b/katas/content/distinguishing_states/two_superposition_states_bit_strings/Placeholder.qs @@ -1,7 +1,7 @@ -namespace Kata{ - open Microsoft.Quantum.Convert; +namespace Kata { + import Std.Convert.*; - operation SuperpositionMeasurement (qs : Qubit[], bits1 : Bool[][], bits2 : Bool[][]) : Int { + operation SuperpositionMeasurement(qs : Qubit[], bits1 : Bool[][], bits2 : Bool[][]) : Int { // Implement your solution here... return -1; diff --git a/katas/content/distinguishing_states/two_superposition_states_bit_strings/Solution.qs b/katas/content/distinguishing_states/two_superposition_states_bit_strings/Solution.qs index a793801fb4..79345b6c88 100644 --- a/katas/content/distinguishing_states/two_superposition_states_bit_strings/Solution.qs +++ b/katas/content/distinguishing_states/two_superposition_states_bit_strings/Solution.qs @@ -1,7 +1,7 @@ -namespace Kata{ - open Microsoft.Quantum.Convert; +namespace Kata { + import Std.Convert.*; - operation SuperpositionMeasurement (qs : Qubit[], bits1 : Bool[][], bits2 : Bool[][]) : Int { + operation SuperpositionMeasurement(qs : Qubit[], bits1 : Bool[][], bits2 : Bool[][]) : Int { let measuredState = MeasureInteger(qs); for s in bits1 { if BoolArrayAsInt(s) == measuredState { diff --git a/katas/content/distinguishing_states/two_superposition_states_bit_strings/Verification.qs b/katas/content/distinguishing_states/two_superposition_states_bit_strings/Verification.qs index 0eea72a6bd..87014bbb31 100644 --- a/katas/content/distinguishing_states/two_superposition_states_bit_strings/Verification.qs +++ b/katas/content/distinguishing_states/two_superposition_states_bit_strings/Verification.qs @@ -1,21 +1,26 @@ -namespace Kata.Verification{ - open Microsoft.Quantum.Arrays; - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Katas; +namespace Kata.Verification { + import Std.Arrays.*; + import Std.Convert.*; + import KatasUtils.*; - operation CheckSuperpositionBitstringsMeasurement ( + operation CheckSuperpositionBitstringsMeasurement( nQubits : Int, ints1 : Int[], ints2 : Int[] - ): Bool { + ) : Bool { let bits1 = Mapped(IntAsBoolArray(_, nQubits), ints1); let bits2 = Mapped(IntAsBoolArray(_, nQubits), ints2); let stateNames = [IntArrayAsStateName(nQubits, bits1), IntArrayAsStateName(nQubits, bits2)]; - let isCorrect = DistinguishStates_MultiQubit(nQubits, 2, StatePrep_SuperpositionMeasurement(_, bits1, bits2, _, _), - Kata.SuperpositionMeasurement(_, bits1, bits2), false, - stateNames); + let isCorrect = DistinguishStates_MultiQubit( + nQubits, + 2, + StatePrep_SuperpositionMeasurement(_, bits1, bits2, _, _), + Kata.SuperpositionMeasurement(_, bits1, bits2), + false, + stateNames + ); if not isCorrect { Message($"Incorrect for: [{stateNames[0]}, {stateNames[1]}]") @@ -24,7 +29,7 @@ namespace Kata.Verification{ return isCorrect; } - operation CheckSolution () : Bool { + operation CheckSolution() : Bool { // note that bit strings in the comments (big endian) are the reverse of the bit strings passed to the solutions (little endian) for (n, ints1, ints2) in [ (2, [2], [1]), // [10] vs [01] diff --git a/katas/content/distinguishing_states/two_superposition_states_bit_strings_one/Placeholder.qs b/katas/content/distinguishing_states/two_superposition_states_bit_strings_one/Placeholder.qs index b6c18e3bcc..40b4d92197 100644 --- a/katas/content/distinguishing_states/two_superposition_states_bit_strings_one/Placeholder.qs +++ b/katas/content/distinguishing_states/two_superposition_states_bit_strings_one/Placeholder.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Convert; + import Std.Convert.*; operation SuperpositionOneMeasurement(qs : Qubit[], bits1 : Bool[][], bits2 : Bool[][]) : Int { // Implement your solution here... diff --git a/katas/content/distinguishing_states/two_superposition_states_bit_strings_one/Solution.qs b/katas/content/distinguishing_states/two_superposition_states_bit_strings_one/Solution.qs index df93721f3b..64528597f0 100644 --- a/katas/content/distinguishing_states/two_superposition_states_bit_strings_one/Solution.qs +++ b/katas/content/distinguishing_states/two_superposition_states_bit_strings_one/Solution.qs @@ -1,17 +1,17 @@ namespace Kata { - open Microsoft.Quantum.Convert; + import Std.Convert.*; - function FindFirstSuperpositionDiff (bits1 : Bool[][], bits2 : Bool[][], nQubits : Int) : Int { - for i in 0 .. nQubits - 1 { + function FindFirstSuperpositionDiff(bits1 : Bool[][], bits2 : Bool[][], nQubits : Int) : Int { + for i in 0..nQubits - 1 { // count the number of 1s in i-th position in bit strings of both arrays mutable val1 = 0; mutable val2 = 0; - for j in 0 .. Length(bits1) - 1 { + for j in 0..Length(bits1) - 1 { if bits1[j][i] { set val1 += 1; } } - for k in 0 .. Length(bits2) - 1 { + for k in 0..Length(bits2) - 1 { if bits2[k][i] { set val2 += 1; } @@ -24,7 +24,7 @@ namespace Kata { return -1; } - operation SuperpositionOneMeasurement (qs : Qubit[], bits1 : Bool[][], bits2 : Bool[][]) : Int { + operation SuperpositionOneMeasurement(qs : Qubit[], bits1 : Bool[][], bits2 : Bool[][]) : Int { let diff = FindFirstSuperpositionDiff(bits1, bits2, Length(qs)); let res = ResultAsBool(M(qs[diff])); diff --git a/katas/content/distinguishing_states/two_superposition_states_bit_strings_one/Verification.qs b/katas/content/distinguishing_states/two_superposition_states_bit_strings_one/Verification.qs index 0e01516393..de524a7b19 100644 --- a/katas/content/distinguishing_states/two_superposition_states_bit_strings_one/Verification.qs +++ b/katas/content/distinguishing_states/two_superposition_states_bit_strings_one/Verification.qs @@ -1,19 +1,19 @@ namespace Kata.Verification { - open Microsoft.Quantum.Arrays; - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Katas; + import Std.Arrays.*; + import Std.Convert.*; + import KatasUtils.*; - operation CheckSuperpositionBitstringsOneMeasurement ( + operation CheckSuperpositionBitstringsOneMeasurement( nQubits : Int, ints1 : Int[], ints2 : Int[] - ): Bool { + ) : Bool { let bits1 = Mapped(IntAsBoolArray(_, nQubits), ints1); let bits2 = Mapped(IntAsBoolArray(_, nQubits), ints2); let stateNames = [IntArrayAsStateName(nQubits, bits1), IntArrayAsStateName(nQubits, bits2)]; - let isCorrect = DistinguishStates_MultiQubit( + let isCorrect = DistinguishStates_MultiQubit( nQubits, 2, StatePrep_SuperpositionMeasurement(_, bits1, bits2, _, _), diff --git a/katas/content/distinguishing_states/zero_one/Verification.qs b/katas/content/distinguishing_states/zero_one/Verification.qs index b5b2158d3d..7dc0a8168a 100644 --- a/katas/content/distinguishing_states/zero_one/Verification.qs +++ b/katas/content/distinguishing_states/zero_one/Verification.qs @@ -1,8 +1,8 @@ namespace Kata.Verification { - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Katas; + import Std.Diagnostics.*; + import KatasUtils.*; - operation StatePrep_IsQubitOne (q : Qubit, state : Int) : Unit is Adj { + operation StatePrep_IsQubitOne(q : Qubit, state : Int) : Unit is Adj { if state == 1 { // convert |0⟩ to |1⟩ X(q); @@ -15,7 +15,8 @@ namespace Kata.Verification { StatePrep_IsQubitOne, Kata.IsQubitOne, ["|0⟩", "|1⟩"], - false); + false + ); if isCorrect { Message("Correct!"); } else { diff --git a/katas/content/distinguishing_states/zero_plus/Solution.qs b/katas/content/distinguishing_states/zero_plus/Solution.qs index 2c15fd6cb3..5d3be99341 100644 --- a/katas/content/distinguishing_states/zero_plus/Solution.qs +++ b/katas/content/distinguishing_states/zero_plus/Solution.qs @@ -1,7 +1,7 @@ namespace Kata { - open Microsoft.Quantum.Math; - - operation IsQubitZeroOrPlus (q : Qubit) : Bool { + import Std.Math.*; + + operation IsQubitZeroOrPlus(q : Qubit) : Bool { Ry(0.25 * PI(), q); return M(q) == Zero; } diff --git a/katas/content/distinguishing_states/zero_plus/Verification.qs b/katas/content/distinguishing_states/zero_plus/Verification.qs index 59db1ee2bf..772875aafa 100644 --- a/katas/content/distinguishing_states/zero_plus/Verification.qs +++ b/katas/content/distinguishing_states/zero_plus/Verification.qs @@ -1,23 +1,23 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Random; + import KatasUtils.*; + import Std.Convert.*; + import Std.Random.*; - operation SetQubitZeroOrPlus (q : Qubit, state : Int) : Unit { + operation SetQubitZeroOrPlus(q : Qubit, state : Int) : Unit { if state != 0 { H(q); } } @EntryPoint() - operation CheckSolution () : Bool { + operation CheckSolution() : Bool { let nTotal = 1000; mutable nOk = 0; let threshold = 0.8; use qs = Qubit[1]; - for i in 1 .. nTotal { + for i in 1..nTotal { // get a random integer to define the state of the qubits let state = DrawRandomInt(0, 1); diff --git a/katas/content/distinguishing_states/zero_plus_inc/Solution.qs b/katas/content/distinguishing_states/zero_plus_inc/Solution.qs index a6a6060f4d..6b17218c77 100644 --- a/katas/content/distinguishing_states/zero_plus_inc/Solution.qs +++ b/katas/content/distinguishing_states/zero_plus_inc/Solution.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Random; + import Std.Random.*; operation IsQubitZeroPlusOrInconclusive(q : Qubit) : Int { // Pick a random basis let basis = DrawRandomInt(0, 1); @@ -8,8 +8,7 @@ namespace Kata { let result = M(q); // result is One only if the state was |+⟩ return result == One ? 1 | -1; - } - else { + } else { // use Hadamard basis H(q); let result = M(q); diff --git a/katas/content/distinguishing_states/zero_plus_inc/Verification.qs b/katas/content/distinguishing_states/zero_plus_inc/Verification.qs index 5b9191684e..afc5349c29 100644 --- a/katas/content/distinguishing_states/zero_plus_inc/Verification.qs +++ b/katas/content/distinguishing_states/zero_plus_inc/Verification.qs @@ -1,9 +1,9 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Random; + import KatasUtils.*; + import Std.Convert.*; + import Std.Random.*; - operation SetQubitZeroOrPlus (q : Qubit, state : Int) : Unit { + operation SetQubitZeroOrPlus(q : Qubit, state : Int) : Unit { if state != 0 { H(q); } @@ -26,7 +26,7 @@ namespace Kata.Verification { mutable nConclPlus = 0; use qs = Qubit[1]; - for i in 1 .. nTotal { + for i in 1..nTotal { // get a random integer to define the state of the qubits let state = DrawRandomInt(0, 1); @@ -67,7 +67,7 @@ namespace Kata.Verification { Message($"{nConclPlus} test runs out of {nTotal} returned conclusive |+⟩ which does not meet the required threshold of at least {thresholdConcl * 100.0}%."); set isCorrect = false; } - + if (isCorrect) { Message("Correct!"); return true; diff --git a/katas/content/distinguishing_states/zerozero_oneone/Verification.qs b/katas/content/distinguishing_states/zerozero_oneone/Verification.qs index 1258ceff1d..d9b8ea91f5 100644 --- a/katas/content/distinguishing_states/zerozero_oneone/Verification.qs +++ b/katas/content/distinguishing_states/zerozero_oneone/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; operation StatePrep_ZeroZeroOrOneOne(qs : Qubit[], state : Int, dummyVar : Double) : Unit is Adj { if state == 1 { diff --git a/katas/content/distinguishing_unitaries/Common.qs b/katas/content/distinguishing_unitaries/Common.qs index d16b25d49e..60e1909105 100644 --- a/katas/content/distinguishing_unitaries/Common.qs +++ b/katas/content/distinguishing_unitaries/Common.qs @@ -1,14 +1,14 @@ namespace Kata.Verification { - open Microsoft.Quantum.Math; - open Microsoft.Quantum.Random; + import Std.Math.*; + import Std.Random.*; // "Framework" operation for testing tasks for distinguishing unitaries // "unitaries" is the list of unitaries that can be passed to the task // "testImpl" - the solution to be tested // "unitaryNames" - the labels of unitaries in the list // "maxCalls" - max # of calls to the unitary that are allowed (-1 means unlimited) - currently unused, TODO use after #1154 - operation DistinguishUnitaries_Framework<'UInput> ( - unitaries : ('UInput => Unit is Adj + Ctl)[], + operation DistinguishUnitaries_Framework<'UInput>( + unitaries : ('UInput => Unit is Adj + Ctl)[], testImpl : ('UInput => Unit is Adj + Ctl) => Int, unitaryNames : String[], maxCalls : Int @@ -18,11 +18,11 @@ namespace Kata.Verification { let nTotal = 100; mutable wrongClassifications = [0, size = nUnitaries * nUnitaries]; // [i * nU + j] number of times unitary i was classified as j mutable unknownClassifications = [0, size = nUnitaries]; // number of times unitary i was classified as something unknown - - for i in 1 .. nTotal { + + for i in 1..nTotal { // get a random integer to define the unitary used let actualIndex = DrawRandomInt(0, nUnitaries - 1); - + // get the solution's answer and verify that it's a match let returnedIndex = testImpl(unitaries[actualIndex]); @@ -35,10 +35,10 @@ namespace Kata.Verification { } } } - + mutable totalMisclassifications = 0; - for i in 0 .. nUnitaries - 1 { - for j in 0 .. nUnitaries - 1 { + for i in 0..nUnitaries - 1 { + for j in 0..nUnitaries - 1 { let misclassifiedIasJ = wrongClassifications[(i * nUnitaries) + j]; if misclassifiedIasJ != 0 { set totalMisclassifications += misclassifiedIasJ; @@ -60,30 +60,28 @@ namespace Kata.Verification { true } - operation MinusZ (q : Qubit) : Unit is Adj + Ctl { - within { + operation MinusZ(q : Qubit) : Unit is Adj + Ctl { + within { X(q); - } - apply { + } apply { Z(q); } } - operation XZ (q : Qubit) : Unit is Adj + Ctl { + operation XZ(q : Qubit) : Unit is Adj + Ctl { Z(q); X(q); } - operation MinusY (q : Qubit) : Unit is Adj + Ctl { + operation MinusY(q : Qubit) : Unit is Adj + Ctl { within { X(q); - } - apply { + } apply { Y(q); } } - operation MinusXZ (q : Qubit) : Unit is Adj + Ctl { + operation MinusXZ(q : Qubit) : Unit is Adj + Ctl { X(q); Z(q); } diff --git a/katas/content/distinguishing_unitaries/cnot_direction/Verification.qs b/katas/content/distinguishing_unitaries/cnot_direction/Verification.qs index d24fb830c6..23345f3103 100644 --- a/katas/content/distinguishing_unitaries/cnot_direction/Verification.qs +++ b/katas/content/distinguishing_unitaries/cnot_direction/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; @EntryPoint() operation CheckSolution() : Bool { diff --git a/katas/content/distinguishing_unitaries/cnot_swap/Verification.qs b/katas/content/distinguishing_unitaries/cnot_swap/Verification.qs index 37d86ae502..3e82bee366 100644 --- a/katas/content/distinguishing_unitaries/cnot_swap/Verification.qs +++ b/katas/content/distinguishing_unitaries/cnot_swap/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; @EntryPoint() operation CheckSolution() : Bool { diff --git a/katas/content/distinguishing_unitaries/h_x/Verification.qs b/katas/content/distinguishing_unitaries/h_x/Verification.qs index 6c7ec92b2c..42034290bd 100644 --- a/katas/content/distinguishing_unitaries/h_x/Verification.qs +++ b/katas/content/distinguishing_unitaries/h_x/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; @EntryPoint() operation CheckSolution() : Bool { diff --git a/katas/content/distinguishing_unitaries/i_cnot_swap/Verification.qs b/katas/content/distinguishing_unitaries/i_cnot_swap/Verification.qs index e294eb5d0b..2a9da8fb55 100644 --- a/katas/content/distinguishing_unitaries/i_cnot_swap/Verification.qs +++ b/katas/content/distinguishing_unitaries/i_cnot_swap/Verification.qs @@ -1,8 +1,8 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; @EntryPoint() operation CheckSolution() : Bool { DistinguishUnitaries_Framework([ApplyToEachCA(I, _), qs => CNOT(qs[0], qs[1]), qs => CNOT(qs[1], qs[0]), qs => SWAP(qs[0], qs[1])], Kata.DistinguishTwoQubitUnitaries, ["I⊗I", "CNOT_12", "CNOT_21", "SWAP"], 2) } -} +} diff --git a/katas/content/distinguishing_unitaries/i_x/Verification.qs b/katas/content/distinguishing_unitaries/i_x/Verification.qs index 8a2c27828a..db4fb400c7 100644 --- a/katas/content/distinguishing_unitaries/i_x/Verification.qs +++ b/katas/content/distinguishing_unitaries/i_x/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; @EntryPoint() operation CheckSolution() : Bool { diff --git a/katas/content/distinguishing_unitaries/i_x_y_z/Verification.qs b/katas/content/distinguishing_unitaries/i_x_y_z/Verification.qs index 5bd6f50dbe..78df6c1894 100644 --- a/katas/content/distinguishing_unitaries/i_x_y_z/Verification.qs +++ b/katas/content/distinguishing_unitaries/i_x_y_z/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; @EntryPoint() operation CheckSolution() : Bool { diff --git a/katas/content/distinguishing_unitaries/i_z/Verification.qs b/katas/content/distinguishing_unitaries/i_z/Verification.qs index f54509fd5d..54e465aa1a 100644 --- a/katas/content/distinguishing_unitaries/i_z/Verification.qs +++ b/katas/content/distinguishing_unitaries/i_z/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; @EntryPoint() operation CheckSolution() : Bool { diff --git a/katas/content/distinguishing_unitaries/ix_cnot/Verification.qs b/katas/content/distinguishing_unitaries/ix_cnot/Verification.qs index f4dafd8def..f2e44ecd44 100644 --- a/katas/content/distinguishing_unitaries/ix_cnot/Verification.qs +++ b/katas/content/distinguishing_unitaries/ix_cnot/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; @EntryPoint() operation CheckSolution() : Bool { diff --git a/katas/content/distinguishing_unitaries/rz_r1/Placeholder.qs b/katas/content/distinguishing_unitaries/rz_r1/Placeholder.qs index 1c619d2f6d..c285e58057 100644 --- a/katas/content/distinguishing_unitaries/rz_r1/Placeholder.qs +++ b/katas/content/distinguishing_unitaries/rz_r1/Placeholder.qs @@ -1,7 +1,7 @@ namespace Kata { - open Microsoft.Quantum.Math; - - operation DistinguishRzFromR1 (unitary : ((Double, Qubit) => Unit is Adj + Ctl)) : Int { + import Std.Math.*; + + operation DistinguishRzFromR1(unitary : ((Double, Qubit) => Unit is Adj + Ctl)) : Int { // Implement your solution here... return -1; diff --git a/katas/content/distinguishing_unitaries/rz_r1/Solution.qs b/katas/content/distinguishing_unitaries/rz_r1/Solution.qs index 6d35fe4566..89bbcea46b 100644 --- a/katas/content/distinguishing_unitaries/rz_r1/Solution.qs +++ b/katas/content/distinguishing_unitaries/rz_r1/Solution.qs @@ -1,6 +1,6 @@ namespace Kata { - open Microsoft.Quantum.Math; - operation DistinguishRzFromR1 (unitary : ((Double, Qubit) => Unit is Adj+Ctl)) : Int { + import Std.Math.*; + operation DistinguishRzFromR1(unitary : ((Double, Qubit) => Unit is Adj + Ctl)) : Int { use qs = Qubit[2]; H(qs[0]); Controlled unitary(qs[0..0], (2.0 * PI(), qs[1])); diff --git a/katas/content/distinguishing_unitaries/rz_r1/Verification.qs b/katas/content/distinguishing_unitaries/rz_r1/Verification.qs index df1cf1ebf7..8e597adeb7 100644 --- a/katas/content/distinguishing_unitaries/rz_r1/Verification.qs +++ b/katas/content/distinguishing_unitaries/rz_r1/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; @EntryPoint() operation CheckSolution() : Bool { diff --git a/katas/content/distinguishing_unitaries/rz_ry/Placeholder.qs b/katas/content/distinguishing_unitaries/rz_ry/Placeholder.qs index 003a360c2e..f9b816755a 100644 --- a/katas/content/distinguishing_unitaries/rz_ry/Placeholder.qs +++ b/katas/content/distinguishing_unitaries/rz_ry/Placeholder.qs @@ -1,8 +1,8 @@ namespace Kata { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Math; - - operation DistinguishRzFromRy (theta : Double, unitary : (Qubit => Unit is Adj + Ctl)) : Int { + import Std.Convert.*; + import Std.Math.*; + + operation DistinguishRzFromRy(theta : Double, unitary : (Qubit => Unit is Adj + Ctl)) : Int { // Implement your solution here... return -1; diff --git a/katas/content/distinguishing_unitaries/rz_ry/Solution.qs b/katas/content/distinguishing_unitaries/rz_ry/Solution.qs index 7e7e8a2aca..77711aa53c 100644 --- a/katas/content/distinguishing_unitaries/rz_ry/Solution.qs +++ b/katas/content/distinguishing_unitaries/rz_ry/Solution.qs @@ -1,6 +1,6 @@ namespace Kata { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Math; + import Std.Convert.*; + import Std.Math.*; function ComputeRepetitions(angle : Double, offset : Int, accuracy : Double) : Int { mutable pifactor = 0; @@ -15,13 +15,13 @@ namespace Kata { return 0; } - operation DistinguishRzFromRy (theta : Double, unitary : (Qubit => Unit is Adj+Ctl)) : Int { + operation DistinguishRzFromRy(theta : Double, unitary : (Qubit => Unit is Adj + Ctl)) : Int { use q = Qubit(); let times = ComputeRepetitions(theta, 1, 0.1); mutable attempt = 1; mutable measuredOne = false; repeat { - for _ in 1 .. times { + for _ in 1..times { unitary(q); } // for Rz, we'll never venture away from |0⟩ state, so as soon as we got |1⟩ we know it's not Rz @@ -29,7 +29,7 @@ namespace Kata { set measuredOne = true; } // if we try several times and still only get |0⟩s, chances are that it is Rz - } until (attempt == 4 or measuredOne) + } until (attempt == 4 or measuredOne) fixup { set attempt += 1; } diff --git a/katas/content/distinguishing_unitaries/rz_ry/Verification.qs b/katas/content/distinguishing_unitaries/rz_ry/Verification.qs index 82a0964bcd..c3077e1df8 100644 --- a/katas/content/distinguishing_unitaries/rz_ry/Verification.qs +++ b/katas/content/distinguishing_unitaries/rz_ry/Verification.qs @@ -1,10 +1,10 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; @EntryPoint() operation CheckSolution() : Bool { for theta in [0.04, 0.1, 0.25, 0.31, 0.5, 0.87, 1.05, 1.41, 1.66, 1.75, 2.0, 2.16, 2.22, 2.51, 2.93, 3.0, 3.1] { - Message($"Testing theta = {theta}..."); + Message($"Testing theta = {theta}..."); if not DistinguishUnitaries_Framework([Rz(theta, _), Ry(theta, _)], Kata.DistinguishRzFromRy(theta, _), ["Rz", "Ry"], -1) { return false; } diff --git a/katas/content/distinguishing_unitaries/y_xz/Verification.qs b/katas/content/distinguishing_unitaries/y_xz/Verification.qs index 69995cfbf5..b98a02003d 100644 --- a/katas/content/distinguishing_unitaries/y_xz/Verification.qs +++ b/katas/content/distinguishing_unitaries/y_xz/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; @EntryPoint() operation CheckSolution() : Bool { diff --git a/katas/content/distinguishing_unitaries/y_xz_minusy_minusxz/Verification.qs b/katas/content/distinguishing_unitaries/y_xz_minusy_minusxz/Verification.qs index 112e74abdc..d815fa6d58 100644 --- a/katas/content/distinguishing_unitaries/y_xz_minusy_minusxz/Verification.qs +++ b/katas/content/distinguishing_unitaries/y_xz_minusy_minusxz/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; @EntryPoint() operation CheckSolution() : Bool { diff --git a/katas/content/distinguishing_unitaries/z_minusz/Verification.qs b/katas/content/distinguishing_unitaries/z_minusz/Verification.qs index f77037ebf5..3114e40e93 100644 --- a/katas/content/distinguishing_unitaries/z_minusz/Verification.qs +++ b/katas/content/distinguishing_unitaries/z_minusz/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; @EntryPoint() operation CheckSolution() : Bool { diff --git a/katas/content/distinguishing_unitaries/z_s/Verification.qs b/katas/content/distinguishing_unitaries/z_s/Verification.qs index 6b92b48578..e7db593490 100644 --- a/katas/content/distinguishing_unitaries/z_s/Verification.qs +++ b/katas/content/distinguishing_unitaries/z_s/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; @EntryPoint() operation CheckSolution() : Bool { diff --git a/katas/content/getting_started/flip_qubit/Verification.qs b/katas/content/getting_started/flip_qubit/Verification.qs index 1f696e31c9..b514d5c9dc 100644 --- a/katas/content/getting_started/flip_qubit/Verification.qs +++ b/katas/content/getting_started/flip_qubit/Verification.qs @@ -1,6 +1,6 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Diagnostics; + import KatasUtils.*; + import Std.Diagnostics.*; operation FlipQubit(q : Qubit) : Unit is Adj + Ctl { X(q); diff --git a/katas/content/grovers_search/conditional_phase_flip/Solution.qs b/katas/content/grovers_search/conditional_phase_flip/Solution.qs index 420c25f3b7..bfd24ba9dc 100644 --- a/katas/content/grovers_search/conditional_phase_flip/Solution.qs +++ b/katas/content/grovers_search/conditional_phase_flip/Solution.qs @@ -1,10 +1,10 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; operation ConditionalPhaseFlip(qs : Qubit[]) : Unit is Adj + Ctl { within { ApplyToEachA(X, qs); } apply { - Controlled Z(qs[1 ...], qs[0]); + Controlled Z(qs[1...], qs[0]); } R(PauliI, 2.0 * PI(), qs[0]); } diff --git a/katas/content/grovers_search/conditional_phase_flip/Verification.qs b/katas/content/grovers_search/conditional_phase_flip/Verification.qs index e41564707b..93504b57f6 100644 --- a/katas/content/grovers_search/conditional_phase_flip/Verification.qs +++ b/katas/content/grovers_search/conditional_phase_flip/Verification.qs @@ -1,18 +1,18 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; + import KatasUtils.*; + import Std.Math.*; operation ConditionalPhaseFlip(qs : Qubit[]) : Unit is Adj + Ctl { within { ApplyToEachA(X, qs); } apply { - Controlled Z(qs[1 ...], qs[0]); + Controlled Z(qs[1...], qs[0]); } R(PauliI, 2.0 * PI(), qs[0]); } @EntryPoint() operation CheckSolution() : Bool { - for N in 2 .. 4 { + for N in 2..4 { if not CheckOperationsAreEqualStrict(N, Kata.ConditionalPhaseFlip, ConditionalPhaseFlip) { Message("Incorrect."); Message("Hint: examine how your solution transforms the given state and compare it with the expected " + diff --git a/katas/content/grovers_search/examples/GroversSearchAlgorithmDemo.qs b/katas/content/grovers_search/examples/GroversSearchAlgorithmDemo.qs index 2118bcf67b..9611f7f19d 100644 --- a/katas/content/grovers_search/examples/GroversSearchAlgorithmDemo.qs +++ b/katas/content/grovers_search/examples/GroversSearchAlgorithmDemo.qs @@ -1,7 +1,7 @@ namespace Kata { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Math; + import Std.Convert.*; + import Std.Diagnostics.*; + import Std.Math.*; @EntryPoint() operation GroversSearchAlgorithmDemo() : Unit { @@ -9,9 +9,9 @@ namespace Kata { let n = 3; let prefix = [false, true, false]; let markingOracle = Oracle_StartsWith(_, _, prefix); - for iterations in 0 .. 9 { + for iterations in 0..9 { mutable success = 0; - for _ in 1 .. 100 { + for _ in 1..100 { let res = GroversSearch(n, markingOracle, iterations); if BoolArrayAsInt(prefix) == BoolArrayAsInt(res) { set success += 1; @@ -23,7 +23,7 @@ namespace Kata { operation GroversSearch( n : Int, - markingOracle : (Qubit[], Qubit) => Unit is Adj + Ctl, + markingOracle : (Qubit[], Qubit) => Unit is Adj + Ctl, iterations : Int ) : Bool[] { use qs = Qubit[n]; @@ -38,7 +38,7 @@ namespace Kata { meanStatePrep(qs); // Do Grover's iterations. - for _ in 1 .. iterations { + for _ in 1..iterations { // Apply the phase oracle. phaseOracle(qs); @@ -51,13 +51,13 @@ namespace Kata { } operation Oracle_StartsWith(x : Qubit[], y : Qubit, p : Bool[]) : Unit is Adj + Ctl { - ApplyControlledOnBitString(p, X, x[... Length(p) - 1], y); + ApplyControlledOnBitString(p, X, x[...Length(p) - 1], y); } operation ApplyMarkingOracleAsPhaseOracle( markingOracle : (Qubit[], Qubit) => Unit is Adj + Ctl, - qubits : Qubit[]) - : Unit is Adj + Ctl { + qubits : Qubit[] + ) : Unit is Adj + Ctl { use minus = Qubit(); within { X(minus); @@ -69,8 +69,8 @@ namespace Kata { operation ReflectionAboutState( qs : Qubit[], - statePrep : Qubit[] => Unit is Adj + Ctl) - : Unit is Adj + Ctl { + statePrep : Qubit[] => Unit is Adj + Ctl + ) : Unit is Adj + Ctl { within { Adjoint statePrep(qs); } apply { @@ -82,8 +82,8 @@ namespace Kata { within { ApplyToEachA(X, qs); } apply { - Controlled Z(qs[1 ...], qs[0]); + Controlled Z(qs[1...], qs[0]); } R(PauliI, 2.0 * PI(), qs[0]); } -} \ No newline at end of file +} diff --git a/katas/content/grovers_search/index.md b/katas/content/grovers_search/index.md index 6aa668aadd..4a96077d3c 100644 --- a/katas/content/grovers_search/index.md +++ b/katas/content/grovers_search/index.md @@ -56,7 +56,7 @@ for which the formula evaluates to true (or to decide that such assignment doesn This is exactly the definition of the search problem, with the input $x$ defined as the set of variables used in the formula and $f(x)$ - as the formula itself. - Vertex coloring problem aims to find an assignment of colors to the vertices of a given graph that would satisfy the given constraints. In this case, $x$ describes the colors assigned to the vertices, and $f(x)$ is $1$ if the constraints are satisfied or $0$ otherwise. -You will learn more about appliyng Grover's search to solving specific problems in later katas. +You will learn more about applying Grover's search to solving specific problems in later katas. This kata focuses on Grover's search algorithm itself rather than on applying it to a specific problem, so it uses a very simple function definition as an example. @@ -168,7 +168,7 @@ After applying $R$ iterations of Grover's search the state of the system will be $$\sin{(2R+1)\theta}\ket{\text{good}} + \cos{(2R+1)\theta}\ket{\text{bad}}$$ -At firat, each iteration brings the state of the system closer to the vertical axis, increasing the probability of measuring one of the basis states that are part of $\ket{\text{good}}$ - the states that are solutions to the problem. +At first, each iteration brings the state of the system closer to the vertical axis, increasing the probability of measuring one of the basis states that are part of $\ket{\text{good}}$ - the states that are solutions to the problem. @[exercise]({ "id": "grovers_search__phase_oracle", @@ -198,7 +198,7 @@ The optimal number of iterations to use in Grover's search algorithm is typicall after which the success probability of the algorithm - the probability of measuring one of the "good" states - is maximized. Geometrically, this means that the state vector should be rotated to be as close to the vertical axis as possible. -Mathematically, this means maximizing the ampitude $\sin{(2R+1)\theta}$ of the state $\ket{\text{good}}$ +Mathematically, this means maximizing the amplitude $\sin{(2R+1)\theta}$ of the state $\ket{\text{good}}$ in the superposition. With either definition, the goal is to have the angle $(2R+1)\theta$ that describes the system after $R$ rotations as close to $\frac{\pi}{2}$ as possible: @@ -279,8 +279,8 @@ In fact, the first iteration is likely to decrease the probability of success! The last two scenarios are a lot easier to handle classically. Indeed, a randomly selected classical value has a probability of being a problem solution $p = \frac{M}{N} > \frac{1}{2}$! -If we repeat the random selection of the variable $k$ times, the probability of success grows to $1-(1-p)^k$, thus by increasing $k$ we can get this probabilty as close to $1$ as we need. -For example, For $p=0.5$ and $k=10$ the probality of success is about $99.9\%$. +If we repeat the random selection of the variable $k$ times, the probability of success grows to $1-(1-p)^k$, thus by increasing $k$ we can get this probability as close to $1$ as we need. +For example, For $p=0.5$ and $k=10$ the probability of success is about $99.9\%$. #### Unknown number of solutions diff --git a/katas/content/grovers_search/phase_oracle/Verification.qs b/katas/content/grovers_search/phase_oracle/Verification.qs index 73b25454ef..4a67f24f94 100644 --- a/katas/content/grovers_search/phase_oracle/Verification.qs +++ b/katas/content/grovers_search/phase_oracle/Verification.qs @@ -1,11 +1,12 @@ namespace Kata.Verification { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Random; + import Std.Convert.*; + import KatasUtils.*; + import Std.Random.*; operation ApplyMarkingOracleAsPhaseOracle_Reference( markingOracle : ((Qubit[], Qubit) => Unit is Adj + Ctl), - qubits : Qubit[]) : Unit is Adj + Ctl { + qubits : Qubit[] + ) : Unit is Adj + Ctl { use minus = Qubit(); within { @@ -18,8 +19,8 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { - for N in 1 .. 3 { - for k in 0 .. 2^N - 1 { + for N in 1..3 { + for k in 0..2^N - 1 { let pattern = IntAsBoolArray(k, N); let marking = ApplyControlledOnBitString(pattern, X, _, _); let sol = Kata.ApplyMarkingOracleAsPhaseOracle(marking, _); diff --git a/katas/content/grovers_search/prefix_oracle/Verification.qs b/katas/content/grovers_search/prefix_oracle/Verification.qs index 317b39cb07..51267e6ad3 100644 --- a/katas/content/grovers_search/prefix_oracle/Verification.qs +++ b/katas/content/grovers_search/prefix_oracle/Verification.qs @@ -1,14 +1,14 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; function F_StartsWith(args : Bool[], p : Bool[]) : Bool { - for i in 0 .. Length(p) - 1 { + for i in 0..Length(p) - 1 { if p[i] != args[i] { return false; } } return true; - } + } @EntryPoint() operation CheckSolution() : Bool { @@ -22,11 +22,11 @@ namespace Kata.Verification { ] { if not CheckOracleImplementsFunction(n, Kata.Oracle_StartsWith(_, _, p), F_StartsWith(_, p)) { Message($"Test failed for N = {n}, p = {p}"); - return false; + return false; } } Message("Correct!"); - true - } + true + } } diff --git a/katas/content/grovers_search/reflection_about_state/Placeholder.qs b/katas/content/grovers_search/reflection_about_state/Placeholder.qs index 755bf36e95..e1c2a4c5d4 100644 --- a/katas/content/grovers_search/reflection_about_state/Placeholder.qs +++ b/katas/content/grovers_search/reflection_about_state/Placeholder.qs @@ -1,10 +1,10 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; operation ReflectionAboutState( qs : Qubit[], - statePrep : Qubit[] => Unit is Adj + Ctl) - : Unit is Adj + Ctl { + statePrep : Qubit[] => Unit is Adj + Ctl + ) : Unit is Adj + Ctl { // Implement your solution here... } @@ -14,7 +14,7 @@ namespace Kata { within { ApplyToEachA(X, qs); } apply { - Controlled Z(qs[1 ...], qs[0]); + Controlled Z(qs[1...], qs[0]); } R(PauliI, 2.0 * PI(), qs[0]); } diff --git a/katas/content/grovers_search/reflection_about_state/Solution.qs b/katas/content/grovers_search/reflection_about_state/Solution.qs index b5488c920f..d3318e522f 100644 --- a/katas/content/grovers_search/reflection_about_state/Solution.qs +++ b/katas/content/grovers_search/reflection_about_state/Solution.qs @@ -1,10 +1,10 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; operation ReflectionAboutState( qs : Qubit[], - statePrep : Qubit[] => Unit is Adj + Ctl) - : Unit is Adj + Ctl { + statePrep : Qubit[] => Unit is Adj + Ctl + ) : Unit is Adj + Ctl { within { Adjoint statePrep(qs); } apply { @@ -16,7 +16,7 @@ namespace Kata { within { ApplyToEachA(X, qs); } apply { - Controlled Z(qs[1 ...], qs[0]); + Controlled Z(qs[1...], qs[0]); } R(PauliI, 2.0 * PI(), qs[0]); } diff --git a/katas/content/grovers_search/reflection_about_state/Verification.qs b/katas/content/grovers_search/reflection_about_state/Verification.qs index 2c8b73f20a..4f59c4c101 100644 --- a/katas/content/grovers_search/reflection_about_state/Verification.qs +++ b/katas/content/grovers_search/reflection_about_state/Verification.qs @@ -1,11 +1,11 @@ namespace Kata.Verification { - open Microsoft.Quantum.Math; - open Microsoft.Quantum.Katas; + import Std.Math.*; + import KatasUtils.*; operation ReflectionAboutState( qs : Qubit[], - statePrep : Qubit[] => Unit is Adj + Ctl) - : Unit is Adj + Ctl { + statePrep : Qubit[] => Unit is Adj + Ctl + ) : Unit is Adj + Ctl { within { Adjoint statePrep(qs); } apply { @@ -18,7 +18,7 @@ namespace Kata.Verification { within { ApplyToEachA(X, qs); } apply { - Controlled Z(qs[1 ...], qs[0]); + Controlled Z(qs[1...], qs[0]); } R(PauliI, 2.0 * PI(), qs[0]); } diff --git a/katas/content/key_distribution/Common.qs b/katas/content/key_distribution/Common.qs index 49dc055b12..6b335d8e57 100644 --- a/katas/content/key_distribution/Common.qs +++ b/katas/content/key_distribution/Common.qs @@ -1,6 +1,6 @@ namespace Kata.Verification { - open Microsoft.Quantum.Arrays; - open Microsoft.Quantum.Random; + import Std.Arrays.*; + import Std.Random.*; operation RandomArray(N : Int) : Bool[] { ForEach(x => DrawRandomInt(0, 1) == 0, [0, size = N]) @@ -11,15 +11,17 @@ namespace Kata.Verification { } operation StateToString(base : Bool, bit : Bool) : String { - if base { // ∣+⟩ / ∣-⟩ + if base { + // ∣+⟩ / ∣-⟩ return bit ? "|-⟩" | "|+⟩"; - } else { // ∣0⟩ / ∣1⟩ + } else { + // ∣0⟩ / ∣1⟩ return bit ? "|1⟩" | "|0⟩"; } } operation PrepareQubits_Reference(qs : Qubit[], bases : Bool[], bits : Bool[]) : Unit is Adj { - for i in 0 .. Length(qs) - 1 { + for i in 0..Length(qs) - 1 { if bits[i] { X(qs[i]); } diff --git a/katas/content/key_distribution/examples/BB84Demo.qs b/katas/content/key_distribution/examples/BB84Demo.qs index 572a756936..33db128dc0 100644 --- a/katas/content/key_distribution/examples/BB84Demo.qs +++ b/katas/content/key_distribution/examples/BB84Demo.qs @@ -1,17 +1,17 @@ namespace Kata { - open Microsoft.Quantum.Arrays; - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Random; + import Std.Arrays.*; + import Std.Convert.*; + import Std.Diagnostics.*; + import Std.Random.*; @EntryPoint() operation RunBB84Protocol() : Unit { - // 1. Alice chooses a random set of bits to encode in her qubits + // 1. Alice chooses a random set of bits to encode in her qubits // and a random set of bases to prepare her qubits in. // ... // 2. Alice allocates qubits, encodes them using her choices and sends them to Bob. - // You can not express "sending the qubits to Bob" in Q#, + // You can not express "sending the qubits to Bob" in Q#, // so Bob will just use the same qubits. // ... @@ -21,11 +21,11 @@ namespace Kata { // 4. Bob measures Alice's qubits in his chosen bases. // ... - // 5. Alice and Bob compare their chosen bases and + // 5. Alice and Bob compare their chosen bases and // use the bits in the matching positions to create a shared key. // ... - // If you did everything correctly, the generated keys will always match, + // If you did everything correctly, the generated keys will always match, // since there is no eavesdropping going on. // In the next lesson we will discuss introducing eavesdropping. } @@ -33,14 +33,14 @@ namespace Kata { // You might find these helper operations from earlier tasks useful. operation RandomArray(N : Int) : Bool[] { mutable array = [false, size = N]; - for i in 0 .. N - 1 { + for i in 0..N - 1 { set array w/= i <- DrawRandomInt(0, 1) == 0; } return array; } operation PrepareQubits(qs : Qubit[], bases : Bool[], bits : Bool[]) : Unit { - for i in 0 .. Length(qs) - 1 { + for i in 0..Length(qs) - 1 { if bits[i] { X(qs[i]); } @@ -51,21 +51,21 @@ namespace Kata { } operation MeasureQubits(qs : Qubit[], bases : Bool[]) : Bool[] { - for i in 0 .. Length(qs) - 1 { + for i in 0..Length(qs) - 1 { if bases[i] { H(qs[i]); } } - return ResultArrayAsBoolArray(MeasureEachZ(qs)); + return ResultArrayAsBoolArray(MeasureEachZ(qs)); } function GenerateSharedKey(basesAlice : Bool[], basesBob : Bool[], bits : Bool[]) : Bool[] { mutable key = []; - for i in 0 .. Length(bits) - 1 { + for i in 0..Length(bits) - 1 { if basesAlice[i] == basesBob[i] { set key += [bits[i]]; } } return key; - } + } } diff --git a/katas/content/key_distribution/measure_qubits/Solution.qs b/katas/content/key_distribution/measure_qubits/Solution.qs index e4540d5671..f83c9d68b9 100644 --- a/katas/content/key_distribution/measure_qubits/Solution.qs +++ b/katas/content/key_distribution/measure_qubits/Solution.qs @@ -1,12 +1,12 @@ namespace Kata { - open Microsoft.Quantum.Convert; + import Std.Convert.*; operation MeasureQubits(qs : Qubit[], bases : Bool[]) : Bool[] { - for i in 0 .. Length(qs) - 1 { + for i in 0..Length(qs) - 1 { if bases[i] { H(qs[i]); } } - return ResultArrayAsBoolArray(MeasureEachZ(qs)); + return ResultArrayAsBoolArray(MeasureEachZ(qs)); } } diff --git a/katas/content/key_distribution/measure_qubits/Verification.qs b/katas/content/key_distribution/measure_qubits/Verification.qs index 8f515edc85..27c3c2ed9e 100644 --- a/katas/content/key_distribution/measure_qubits/Verification.qs +++ b/katas/content/key_distribution/measure_qubits/Verification.qs @@ -1,9 +1,9 @@ namespace Kata.Verification { - open Microsoft.Quantum.Diagnostics; + import Std.Diagnostics.*; @EntryPoint() operation CheckSolution() : Bool { - for N in 2 .. 10 { + for N in 2..10 { let (bases, bits) = (RandomArray(N), RandomArray(N)); use qs = Qubit[N]; PrepareQubits_Reference(qs, bases, bits); @@ -15,7 +15,7 @@ namespace Kata.Verification { return false; } - for i in 0 .. N - 1 { + for i in 0..N - 1 { if res[i] != bits[i] { Message($"Qubit qs[{i}] measured in incorrect basis."); Message($"When measuring state {StateToString(bases[i], bits[i])} in the {BasisToString(bases[i])} basis, " + diff --git a/katas/content/key_distribution/prepare_qubits/Verification.qs b/katas/content/key_distribution/prepare_qubits/Verification.qs index fa0840f671..7e498e5b61 100644 --- a/katas/content/key_distribution/prepare_qubits/Verification.qs +++ b/katas/content/key_distribution/prepare_qubits/Verification.qs @@ -1,14 +1,14 @@ namespace Kata.Verification { - open Microsoft.Quantum.Diagnostics; + import Std.Diagnostics.*; @EntryPoint() operation CheckSolution() : Bool { - for N in 2 .. 10 { + for N in 2..10 { let (bases, bits) = (RandomArray(N), RandomArray(N)); use qs = Qubit[N]; Kata.PrepareQubits(qs, bases, bits); Adjoint PrepareQubits_Reference(qs, bases, bits); - for i in 0 .. N - 1 { + for i in 0..N - 1 { if not CheckZero(qs[i]) { Message($"Qubit qs[{i}] prepared in incorrect state."); Message($"Expected state {StateToString(bases[i], bits[i])}; actual state"); diff --git a/katas/content/key_distribution/random_array/Solution.qs b/katas/content/key_distribution/random_array/Solution.qs index abc0d35589..fb5453bc8b 100644 --- a/katas/content/key_distribution/random_array/Solution.qs +++ b/katas/content/key_distribution/random_array/Solution.qs @@ -1,9 +1,9 @@ namespace Kata { - open Microsoft.Quantum.Random; + import Std.Random.*; operation RandomArray(N : Int) : Bool[] { mutable array = [false, size = N]; - for i in 0 .. N - 1 { + for i in 0..N - 1 { set array w/= i <- DrawRandomInt(0, 1) == 0; } return array; diff --git a/katas/content/key_distribution/random_array/Verification.qs b/katas/content/key_distribution/random_array/Verification.qs index 9000898115..9aa71daef3 100644 --- a/katas/content/key_distribution/random_array/Verification.qs +++ b/katas/content/key_distribution/random_array/Verification.qs @@ -1,6 +1,6 @@ namespace Kata.Verification { - open Microsoft.Quantum.Arrays; - open Microsoft.Quantum.Convert; + import Std.Arrays.*; + import Std.Convert.*; @EntryPoint() operation CheckSolution() : Bool { diff --git a/katas/content/key_distribution/shared_key/Verification.qs b/katas/content/key_distribution/shared_key/Verification.qs index f1b653614b..129e8aa169 100644 --- a/katas/content/key_distribution/shared_key/Verification.qs +++ b/katas/content/key_distribution/shared_key/Verification.qs @@ -1,9 +1,9 @@ namespace Kata.Verification { - open Microsoft.Quantum.Convert; + import Std.Convert.*; function GenerateSharedKey_Reference(basesAlice : Bool[], basesBob : Bool[], bits : Bool[]) : Bool[] { mutable key = []; - for i in 0 .. Length(bits) - 1 { + for i in 0..Length(bits) - 1 { if basesAlice[i] == basesBob[i] { set key += [bits[i]]; } @@ -15,7 +15,7 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { - for N in 8 .. 20 { + for N in 8..20 { let basesAlice = RandomArray(N); let basesBob = RandomArray(N); let bits = RandomArray(N); diff --git a/katas/content/linear_algebra/Common.qs b/katas/content/linear_algebra/Common.qs index 81f21bb92a..0c7e2ebc34 100644 --- a/katas/content/linear_algebra/Common.qs +++ b/katas/content/linear_algebra/Common.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Math; + import Std.Math.*; function ArraysEqualD(actual : Double[][], expected : Double[][]) : Bool { if Length(actual) != Length(expected) { diff --git a/katas/content/linear_algebra/adjoint/Placeholder.qs b/katas/content/linear_algebra/adjoint/Placeholder.qs index e2571fdd16..f3a1976881 100644 --- a/katas/content/linear_algebra/adjoint/Placeholder.qs +++ b/katas/content/linear_algebra/adjoint/Placeholder.qs @@ -1,9 +1,11 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; function MatrixAdjoint() : Complex[][] { // Replace the return value with correct answer. - return [[Complex(0., 0.), Complex(0., 0.)], - [Complex(0., 0.), Complex(0., 0.)]]; + return [ + [Complex(0., 0.), Complex(0., 0.)], + [Complex(0., 0.), Complex(0., 0.)] + ]; } } diff --git a/katas/content/linear_algebra/adjoint/Solution.qs b/katas/content/linear_algebra/adjoint/Solution.qs index ccd3e620d9..6db49ff881 100644 --- a/katas/content/linear_algebra/adjoint/Solution.qs +++ b/katas/content/linear_algebra/adjoint/Solution.qs @@ -1,8 +1,10 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; function MatrixAdjoint() : Complex[][] { - return [[Complex(1., -5.), Complex(3., 6.)], - [Complex(2., 0.), Complex(0., -4.)]]; + return [ + [Complex(1., -5.), Complex(3., 6.)], + [Complex(2., 0.), Complex(0., -4.)] + ]; } } diff --git a/katas/content/linear_algebra/adjoint/Verification.qs b/katas/content/linear_algebra/adjoint/Verification.qs index c55ef5a1f8..4aead9f297 100644 --- a/katas/content/linear_algebra/adjoint/Verification.qs +++ b/katas/content/linear_algebra/adjoint/Verification.qs @@ -1,9 +1,11 @@ namespace Kata.Verification { - open Microsoft.Quantum.Math; + import Std.Math.*; function MatrixAdjoint_Reference() : Complex[][] { - return [[Complex(1., -5.), Complex(3., 6.)], - [Complex(2., 0.), Complex(0., -4.)]]; + return [ + [Complex(1., -5.), Complex(3., 6.)], + [Complex(2., 0.), Complex(0., -4.)] + ]; } @EntryPoint() diff --git a/katas/content/linear_algebra/conjugate/Placeholder.qs b/katas/content/linear_algebra/conjugate/Placeholder.qs index 650ac963f6..94a81a648e 100644 --- a/katas/content/linear_algebra/conjugate/Placeholder.qs +++ b/katas/content/linear_algebra/conjugate/Placeholder.qs @@ -1,9 +1,11 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; function Conjugate() : Complex[][] { // Replace the return value with correct answer. - return [[Complex(0., 0.), Complex(0., 0.)], - [Complex(0., 0.), Complex(0., 0.)]]; + return [ + [Complex(0., 0.), Complex(0., 0.)], + [Complex(0., 0.), Complex(0., 0.)] + ]; } } diff --git a/katas/content/linear_algebra/conjugate/Solution.qs b/katas/content/linear_algebra/conjugate/Solution.qs index ee1da0225d..228f3f3a53 100644 --- a/katas/content/linear_algebra/conjugate/Solution.qs +++ b/katas/content/linear_algebra/conjugate/Solution.qs @@ -1,8 +1,10 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; function Conjugate() : Complex[][] { - return [[Complex(1., -5.), Complex(2., 0.)], - [Complex(3., 6.), Complex(0., -4.)]]; + return [ + [Complex(1., -5.), Complex(2., 0.)], + [Complex(3., 6.), Complex(0., -4.)] + ]; } } diff --git a/katas/content/linear_algebra/conjugate/Verification.qs b/katas/content/linear_algebra/conjugate/Verification.qs index 37293cc1c7..3001096769 100644 --- a/katas/content/linear_algebra/conjugate/Verification.qs +++ b/katas/content/linear_algebra/conjugate/Verification.qs @@ -1,9 +1,11 @@ namespace Kata.Verification { - open Microsoft.Quantum.Math; + import Std.Math.*; function Conjugate_Reference() : Complex[][] { - return [[Complex(1., -5.), Complex(2., 0.)], - [Complex(3., 6.), Complex(0., -4.)]]; + return [ + [Complex(1., -5.), Complex(2., 0.)], + [Complex(3., 6.), Complex(0., -4.)] + ]; } @EntryPoint() diff --git a/katas/content/linear_algebra/inner_product/Placeholder.qs b/katas/content/linear_algebra/inner_product/Placeholder.qs index f58db5b465..4c97e920b1 100644 --- a/katas/content/linear_algebra/inner_product/Placeholder.qs +++ b/katas/content/linear_algebra/inner_product/Placeholder.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; function InnerProduct() : Complex { // Replace the return value with correct answer. diff --git a/katas/content/linear_algebra/inner_product/Solution.qs b/katas/content/linear_algebra/inner_product/Solution.qs index 1b4d8fbd8b..9072e70768 100644 --- a/katas/content/linear_algebra/inner_product/Solution.qs +++ b/katas/content/linear_algebra/inner_product/Solution.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; function InnerProduct() : Complex { return Complex(-18., 72.); diff --git a/katas/content/linear_algebra/inner_product/Verification.qs b/katas/content/linear_algebra/inner_product/Verification.qs index 3c026df72e..ef10548b9a 100644 --- a/katas/content/linear_algebra/inner_product/Verification.qs +++ b/katas/content/linear_algebra/inner_product/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Math; + import Std.Math.*; function InnerProduct_Reference() : Complex { return Complex(-18., 72.); @@ -14,7 +14,7 @@ namespace Kata.Verification { Message($"Expected {ComplexAsString(expected)}, actual {ComplexAsString(actual)}"); return false; } - + Message("Correct!"); return true; } diff --git a/katas/content/linear_algebra/normalized_vector/Placeholder.qs b/katas/content/linear_algebra/normalized_vector/Placeholder.qs index 763bbda2dd..af86b64988 100644 --- a/katas/content/linear_algebra/normalized_vector/Placeholder.qs +++ b/katas/content/linear_algebra/normalized_vector/Placeholder.qs @@ -1,9 +1,11 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; function NormalizedVector() : Complex[][] { // Replace the return value with correct answer. - return [[Complex(0., 0.)], - [Complex(0., 0.)]]; + return [ + [Complex(0., 0.)], + [Complex(0., 0.)] + ]; } } diff --git a/katas/content/linear_algebra/normalized_vector/Solution.qs b/katas/content/linear_algebra/normalized_vector/Solution.qs index 587735e650..1be3bf525f 100644 --- a/katas/content/linear_algebra/normalized_vector/Solution.qs +++ b/katas/content/linear_algebra/normalized_vector/Solution.qs @@ -1,8 +1,10 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; function NormalizedVector() : Complex[][] { - return [[Complex(-0.6, 0.)], - [Complex(0., 0.8)]]; + return [ + [Complex(-0.6, 0.)], + [Complex(0., 0.8)] + ]; } } diff --git a/katas/content/linear_algebra/normalized_vector/Verification.qs b/katas/content/linear_algebra/normalized_vector/Verification.qs index 2a24194606..2c43a3d3c5 100644 --- a/katas/content/linear_algebra/normalized_vector/Verification.qs +++ b/katas/content/linear_algebra/normalized_vector/Verification.qs @@ -1,9 +1,11 @@ namespace Kata.Verification { - open Microsoft.Quantum.Math; + import Std.Math.*; function NormalizedVector_Reference() : Complex[][] { - return [[Complex(-0.6, 0.)], - [Complex(0., 0.8)]]; + return [ + [Complex(-0.6, 0.)], + [Complex(0., 0.8)] + ]; } @EntryPoint() diff --git a/katas/content/linear_algebra/outer_product/Placeholder.qs b/katas/content/linear_algebra/outer_product/Placeholder.qs index a494b052bb..7dc59045ec 100644 --- a/katas/content/linear_algebra/outer_product/Placeholder.qs +++ b/katas/content/linear_algebra/outer_product/Placeholder.qs @@ -1,9 +1,11 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; function OuterProduct() : Complex[][] { // Replace the return value with correct answer. - return [[Complex(0., 0.), Complex(0., 0.)], - [Complex(0., 0.), Complex(0., 0.)]]; + return [ + [Complex(0., 0.), Complex(0., 0.)], + [Complex(0., 0.), Complex(0., 0.)] + ]; } } diff --git a/katas/content/linear_algebra/outer_product/Solution.qs b/katas/content/linear_algebra/outer_product/Solution.qs index 5525a83579..84c2c3454d 100644 --- a/katas/content/linear_algebra/outer_product/Solution.qs +++ b/katas/content/linear_algebra/outer_product/Solution.qs @@ -1,8 +1,10 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; function OuterProduct() : Complex[][] { - return [[Complex(-27., 0.), Complex(0., -6.)], - [Complex(0., -81.), Complex(18., 0.)]]; + return [ + [Complex(-27., 0.), Complex(0., -6.)], + [Complex(0., -81.), Complex(18., 0.)] + ]; } } diff --git a/katas/content/linear_algebra/outer_product/Verification.qs b/katas/content/linear_algebra/outer_product/Verification.qs index 94ccb119e9..a5aab08054 100644 --- a/katas/content/linear_algebra/outer_product/Verification.qs +++ b/katas/content/linear_algebra/outer_product/Verification.qs @@ -1,9 +1,11 @@ namespace Kata.Verification { - open Microsoft.Quantum.Math; + import Std.Math.*; function OuterProduct_Reference() : Complex[][] { - return [[Complex(-27., 0.), Complex(0., -6.)], - [Complex(0., -81.), Complex(18., 0.)]]; + return [ + [Complex(-27., 0.), Complex(0., -6.)], + [Complex(0., -81.), Complex(18., 0.)] + ]; } @EntryPoint() diff --git a/katas/content/linear_algebra/tensor_product/Placeholder.qs b/katas/content/linear_algebra/tensor_product/Placeholder.qs index 9d035b5c0d..da4b0d65ab 100644 --- a/katas/content/linear_algebra/tensor_product/Placeholder.qs +++ b/katas/content/linear_algebra/tensor_product/Placeholder.qs @@ -1,9 +1,11 @@ namespace Kata { function TensorProduct() : Double[][] { // Replace the return value with correct answer. - return [[0., 0., 0., 0.], - [0., 0., 0., 0.], - [0., 0., 0., 0.], - [0., 0., 0., 0.]]; + return [ + [0., 0., 0., 0.], + [0., 0., 0., 0.], + [0., 0., 0., 0.], + [0., 0., 0., 0.] + ]; } } diff --git a/katas/content/linear_algebra/tensor_product/Solution.qs b/katas/content/linear_algebra/tensor_product/Solution.qs index 2f05b0153e..576fc69f01 100644 --- a/katas/content/linear_algebra/tensor_product/Solution.qs +++ b/katas/content/linear_algebra/tensor_product/Solution.qs @@ -1,8 +1,10 @@ namespace Kata { function TensorProduct() : Double[][] { - return [[5., 6., 10., 12.], - [7., 8., 14., 16.], - [15., 18., 20., 24.], - [21., 24., 28., 32.]]; + return [ + [5., 6., 10., 12.], + [7., 8., 14., 16.], + [15., 18., 20., 24.], + [21., 24., 28., 32.] + ]; } } diff --git a/katas/content/linear_algebra/tensor_product/Verification.qs b/katas/content/linear_algebra/tensor_product/Verification.qs index ce302756a2..c855511e5f 100644 --- a/katas/content/linear_algebra/tensor_product/Verification.qs +++ b/katas/content/linear_algebra/tensor_product/Verification.qs @@ -1,11 +1,13 @@ namespace Kata.Verification { - open Microsoft.Quantum.Math; + import Std.Math.*; function TensorProduct_Reference() : Double[][] { - return [[5., 6., 10., 12.], - [7., 8., 14., 16.], - [15., 18., 20., 24.], - [21., 24., 28., 32.]]; + return [ + [5., 6., 10., 12.], + [7., 8., 14., 16.], + [15., 18., 20., 24.], + [21., 24., 28., 32.] + ]; } @EntryPoint() diff --git a/katas/content/marking_oracles/balanced/Solution.qs b/katas/content/marking_oracles/balanced/Solution.qs index 3e044f0c1b..d0c0718448 100644 --- a/katas/content/marking_oracles/balanced/Solution.qs +++ b/katas/content/marking_oracles/balanced/Solution.qs @@ -1,6 +1,6 @@ namespace Kata { - open Microsoft.Quantum.Math; - + import Std.Math.*; + operation Oracle_Balanced(x : Qubit[], y : Qubit) : Unit is Adj + Ctl { let N = Length(x); let log = BitSizeI(N); @@ -16,8 +16,8 @@ namespace Kata { operation Increment(register : Qubit[]) : Unit is Adj + Ctl { if Length(register) > 1 { - Controlled Increment([register[0]], register[1 ...]); + Controlled Increment([register[0]], register[1...]); } X(register[0]); - } + } } diff --git a/katas/content/marking_oracles/balanced/Verification.qs b/katas/content/marking_oracles/balanced/Verification.qs index 5e70562036..d01060e2c3 100644 --- a/katas/content/marking_oracles/balanced/Verification.qs +++ b/katas/content/marking_oracles/balanced/Verification.qs @@ -1,6 +1,6 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Arrays; + import KatasUtils.*; + import Std.Arrays.*; function F_Balanced(args : Bool[]) : Bool { return Count(x -> x, args) == Length(args) / 2; @@ -8,7 +8,7 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { - for n in 2 .. 2 .. 6 { + for n in 2..2..6 { if not CheckOracleImplementsFunction(n, Kata.Oracle_Balanced, F_Balanced) { Message($"Test failed for n = {n}"); return false; diff --git a/katas/content/marking_oracles/bit_sum_div_3/Verification.qs b/katas/content/marking_oracles/bit_sum_div_3/Verification.qs index f40328c622..834141a46b 100644 --- a/katas/content/marking_oracles/bit_sum_div_3/Verification.qs +++ b/katas/content/marking_oracles/bit_sum_div_3/Verification.qs @@ -1,6 +1,6 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Arrays; + import KatasUtils.*; + import Std.Arrays.*; function F_BitSumDivisibleBy3(args : Bool[]) : Bool { return Count(x -> x, args) % 3 == 0; @@ -8,7 +8,7 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { - for n in 3 .. 6 { + for n in 3..6 { if not CheckOracleImplementsFunction(n, Kata.Oracle_BitSumDivisibleBy3, F_BitSumDivisibleBy3) { Message($"Test failed for n = {n}"); return false; diff --git a/katas/content/marking_oracles/contains_substring/Verification.qs b/katas/content/marking_oracles/contains_substring/Verification.qs index f397fbe482..83a2e71af4 100644 --- a/katas/content/marking_oracles/contains_substring/Verification.qs +++ b/katas/content/marking_oracles/contains_substring/Verification.qs @@ -1,16 +1,16 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; function F_ContainsSubstring(args : Bool[], r : Bool[]) : Bool { let N = Length(args); let K = Length(r); - for P in 0 .. N - K { + for P in 0..N - K { if F_ContainsSubstringAtPosition(args, r, P) { return true; } } return false; - } + } @EntryPoint() operation CheckSolution() : Bool { @@ -27,6 +27,6 @@ namespace Kata.Verification { } Message("Correct!"); - true - } + true + } } diff --git a/katas/content/marking_oracles/contains_substring_p/Verification.qs b/katas/content/marking_oracles/contains_substring_p/Verification.qs index e930a0e09e..40078e7081 100644 --- a/katas/content/marking_oracles/contains_substring_p/Verification.qs +++ b/katas/content/marking_oracles/contains_substring_p/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; @EntryPoint() operation CheckSolution() : Bool { @@ -11,11 +11,11 @@ namespace Kata.Verification { ] { if not CheckOracleImplementsFunction(n, Kata.Oracle_ContainsSubstringAtPosition(_, _, r, p), F_ContainsSubstringAtPosition(_, r, p)) { Message($"Test failed for n = {n}, p = {p}, r = {r}"); - return false; + return false; } } Message("Correct!"); - true - } + true + } } diff --git a/katas/content/marking_oracles/kth_bit/Verification.qs b/katas/content/marking_oracles/kth_bit/Verification.qs index 763700a82e..b3869f9121 100644 --- a/katas/content/marking_oracles/kth_bit/Verification.qs +++ b/katas/content/marking_oracles/kth_bit/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; function F_Kth_Bit(x : Bool[], k : Int) : Bool { x[k] @@ -7,8 +7,8 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { - for n in 3 .. 5 { - for k in 0 .. n - 1 { + for n in 3..5 { + for k in 0..n - 1 { if not CheckOracleImplementsFunction(n, Kata.Oracle_Kth_Bit(_, _, k), F_Kth_Bit(_, k)) { Message($"Test failed for n = {n}, k = {k}"); return false; diff --git a/katas/content/marking_oracles/majority/Solution.qs b/katas/content/marking_oracles/majority/Solution.qs index 897bc1592a..26b0c68a4e 100644 --- a/katas/content/marking_oracles/majority/Solution.qs +++ b/katas/content/marking_oracles/majority/Solution.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; operation Oracle_Majority(x : Qubit[], y : Qubit) : Unit is Adj + Ctl { let N = Length(x); @@ -19,8 +19,8 @@ namespace Kata { operation Increment(register : Qubit[]) : Unit is Adj + Ctl { if Length(register) > 1 { - Controlled Increment([register[0]], register[1 ...]); + Controlled Increment([register[0]], register[1...]); } X(register[0]); - } + } } diff --git a/katas/content/marking_oracles/majority/Verification.qs b/katas/content/marking_oracles/majority/Verification.qs index 39e702f25f..17959ff571 100644 --- a/katas/content/marking_oracles/majority/Verification.qs +++ b/katas/content/marking_oracles/majority/Verification.qs @@ -1,6 +1,6 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Arrays; + import KatasUtils.*; + import Std.Arrays.*; function F_Majority(args : Bool[]) : Bool { let N = Length(args); diff --git a/katas/content/marking_oracles/num_div_3/Verification.qs b/katas/content/marking_oracles/num_div_3/Verification.qs index 658b238d76..cf57e1581d 100644 --- a/katas/content/marking_oracles/num_div_3/Verification.qs +++ b/katas/content/marking_oracles/num_div_3/Verification.qs @@ -1,6 +1,6 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Convert; + import KatasUtils.*; + import Std.Convert.*; function F_DivisibleBy3(args : Bool[]) : Bool { return BoolArrayAsInt(args) % 3 == 0; @@ -8,7 +8,7 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { - for n in 2 .. 7 { + for n in 2..7 { if not CheckOracleImplementsFunction(n, Kata.Oracle_DivisibleBy3, F_DivisibleBy3) { Message($"Test failed for n = {n}"); return false; diff --git a/katas/content/marking_oracles/palindrome/Verification.qs b/katas/content/marking_oracles/palindrome/Verification.qs index bb6a3d5120..b7eca77a31 100644 --- a/katas/content/marking_oracles/palindrome/Verification.qs +++ b/katas/content/marking_oracles/palindrome/Verification.qs @@ -1,9 +1,9 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; function F_Palindrome(args : Bool[]) : Bool { let N = Length(args); - for i in 0 .. N / 2 - 1 { + for i in 0..N / 2 - 1 { if args[i] != args[N - i - 1] { return false; } @@ -13,7 +13,7 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { - for n in 2 .. 6 { + for n in 2..6 { if not CheckOracleImplementsFunction(n, Kata.Oracle_Palindrome, F_Palindrome) { Message($"Test failed for n = {n}"); return false; @@ -22,5 +22,5 @@ namespace Kata.Verification { Message("Correct!"); true - } + } } diff --git a/katas/content/marking_oracles/parity/Verification.qs b/katas/content/marking_oracles/parity/Verification.qs index 6df1c3136f..5c48ed5496 100644 --- a/katas/content/marking_oracles/parity/Verification.qs +++ b/katas/content/marking_oracles/parity/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; function F_Parity(x : Bool[]) : Bool { mutable parity = false; @@ -13,7 +13,7 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { - for n in 1 .. 5 { + for n in 1..5 { if not CheckOracleImplementsFunction(n, Kata.Oracle_Parity, F_Parity) { return false; } diff --git a/katas/content/marking_oracles/pattern_match/Placeholder.qs b/katas/content/marking_oracles/pattern_match/Placeholder.qs index 62829e6525..b5c4d4a6da 100644 --- a/katas/content/marking_oracles/pattern_match/Placeholder.qs +++ b/katas/content/marking_oracles/pattern_match/Placeholder.qs @@ -1,8 +1,8 @@ namespace Kata { - open Microsoft.Quantum.Arrays; + import Std.Arrays.*; - operation Oracle_PatternMatching (x : Qubit[], y : Qubit, a : Int[], r : Bool[]) : Unit is Adj + Ctl { + operation Oracle_PatternMatching(x : Qubit[], y : Qubit, a : Int[], r : Bool[]) : Unit is Adj + Ctl { // Implement your solution here... - } + } } diff --git a/katas/content/marking_oracles/pattern_match/Solution.qs b/katas/content/marking_oracles/pattern_match/Solution.qs index eae9b85f7a..8d38312fe8 100644 --- a/katas/content/marking_oracles/pattern_match/Solution.qs +++ b/katas/content/marking_oracles/pattern_match/Solution.qs @@ -1,7 +1,7 @@ namespace Kata { - open Microsoft.Quantum.Arrays; + import Std.Arrays.*; - operation Oracle_PatternMatching (x : Qubit[], y : Qubit, a : Int[], r : Bool[]) : Unit is Adj + Ctl { + operation Oracle_PatternMatching(x : Qubit[], y : Qubit, a : Int[], r : Bool[]) : Unit is Adj + Ctl { let ctrl = Subarray(a, x); ApplyControlledOnBitString(r, X, ctrl, y); } diff --git a/katas/content/marking_oracles/pattern_match/Verification.qs b/katas/content/marking_oracles/pattern_match/Verification.qs index 3639bd2fec..c036b512e0 100644 --- a/katas/content/marking_oracles/pattern_match/Verification.qs +++ b/katas/content/marking_oracles/pattern_match/Verification.qs @@ -1,8 +1,8 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; function F_PatternMatching(args : Bool[], a : Int[], r : Bool[]) : Bool { - for i in 0 .. Length(a) - 1 { + for i in 0..Length(a) - 1 { if args[a[i]] != r[i] { return false; } @@ -21,11 +21,11 @@ namespace Kata.Verification { ] { if not CheckOracleImplementsFunction(n, Kata.Oracle_PatternMatching(_, _, a, r), F_PatternMatching(_, a, r)) { Message($"Test failed for n = {n}, a = {a}, r = {r}"); - return false; + return false; } } Message("Correct!"); - true - } + true + } } diff --git a/katas/content/marking_oracles/pattern_match/solution.md b/katas/content/marking_oracles/pattern_match/solution.md index e4dc490d05..3edf9e741e 100644 --- a/katas/content/marking_oracles/pattern_match/solution.md +++ b/katas/content/marking_oracles/pattern_match/solution.md @@ -1,6 +1,6 @@ This task is similar to the previous one: the function we're evaluating depends only on the states of a subset of qubits, so we can ignore the rest of them. The main difference here is getting the set of qubits we need to use as controls. -Q# library function `Subarray` from the `Microsoft.Quantum.Arrays` namespace extracts the elements of the given array at the given indices, which is exactly what we need here. +Q# library function `Subarray` from the `Std.Arrays` namespace extracts the elements of the given array at the given indices, which is exactly what we need here. @[solution]({ "id": "marking_oracles__pattern_match_solution", diff --git a/katas/content/marking_oracles/periodic/Verification.qs b/katas/content/marking_oracles/periodic/Verification.qs index 89969bb136..d250dee293 100644 --- a/katas/content/marking_oracles/periodic/Verification.qs +++ b/katas/content/marking_oracles/periodic/Verification.qs @@ -1,9 +1,9 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; function F_Periodic(args : Bool[]) : Bool { let N = Length(args); - for P in 1 .. N - 1 { + for P in 1..N - 1 { if F_PeriodicGivenPeriod(args, P) { return true; } @@ -13,14 +13,14 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { - for n in 2 .. 6 { + for n in 2..6 { if not CheckOracleImplementsFunction(n, Kata.Oracle_Periodic, F_Periodic) { Message($"Test failed for n = {n}"); - return false; + return false; } } Message("Correct!"); true - } + } } diff --git a/katas/content/marking_oracles/periodic_p/Verification.qs b/katas/content/marking_oracles/periodic_p/Verification.qs index 82c27affda..49ccc0e5e1 100644 --- a/katas/content/marking_oracles/periodic_p/Verification.qs +++ b/katas/content/marking_oracles/periodic_p/Verification.qs @@ -1,10 +1,10 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; @EntryPoint() operation CheckSolution() : Bool { - for n in 2 .. 6 { - for p in 2 .. n - 1 { + for n in 2..6 { + for p in 2..n - 1 { if not CheckOracleImplementsFunction(n, Kata.Oracle_PeriodicGivenPeriod(_, _, p), F_PeriodicGivenPeriod(_, p)) { Message($"Test failed for n = {n}, p = {p}"); return false; @@ -14,5 +14,5 @@ namespace Kata.Verification { Message("Correct!"); true - } + } } diff --git a/katas/content/marking_oracles/product/Verification.qs b/katas/content/marking_oracles/product/Verification.qs index 6ee9474764..88c51173ce 100644 --- a/katas/content/marking_oracles/product/Verification.qs +++ b/katas/content/marking_oracles/product/Verification.qs @@ -1,10 +1,10 @@ namespace Kata.Verification { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Katas; + import Std.Convert.*; + import KatasUtils.*; function F_Product(x : Bool[], r : Bool[]) : Bool { mutable product = false; - for i in 0 .. Length(x) - 1 { + for i in 0..Length(x) - 1 { if r[i] and x[i] { set product = not product; } @@ -15,7 +15,7 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { let n = 3; - for mask in 0 .. 2 ^ n - 1 { + for mask in 0..2^n - 1 { let r = IntAsBoolArray(mask, 3); if not CheckOracleImplementsFunction(n, Kata.Oracle_Product(_, _, r), F_Product(_, r)) { Message($"Test failed for n = {n}, r = {r}"); diff --git a/katas/content/marking_oracles/product_negation/Verification.qs b/katas/content/marking_oracles/product_negation/Verification.qs index a0f555b78a..37609c4781 100644 --- a/katas/content/marking_oracles/product_negation/Verification.qs +++ b/katas/content/marking_oracles/product_negation/Verification.qs @@ -1,10 +1,10 @@ namespace Kata.Verification { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Katas; + import Std.Convert.*; + import KatasUtils.*; function F_ProductWithNegation(x : Bool[], r : Bool[]) : Bool { mutable product = false; - for i in 0 .. Length(x) - 1 { + for i in 0..Length(x) - 1 { if r[i] and x[i] or (not r[i] and not x[i]) { set product = not product; } @@ -15,7 +15,7 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { let n = 3; - for mask in 0 .. 2 ^ n - 1 { + for mask in 0..2^n - 1 { let r = IntAsBoolArray(mask, 3); if not CheckOracleImplementsFunction(n, Kata.Oracle_ProductWithNegation(_, _, r), F_ProductWithNegation(_, r)) { Message($"Test failed for n = {n}, r = {r}"); diff --git a/katas/content/multi_qubit_gates/anti_controlled_gate/Verification.qs b/katas/content/multi_qubit_gates/anti_controlled_gate/Verification.qs index 2ea0340eb2..01d14cfd77 100644 --- a/katas/content/multi_qubit_gates/anti_controlled_gate/Verification.qs +++ b/katas/content/multi_qubit_gates/anti_controlled_gate/Verification.qs @@ -1,14 +1,14 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; - operation AntiControlledGate (qs : Qubit[]) : Unit is Adj + Ctl { + operation AntiControlledGate(qs : Qubit[]) : Unit is Adj + Ctl { X(qs[1]); CNOT(qs[0], qs[1]); } operation CheckSolution() : Bool { - let solution = Kata. AntiControlledGate; - let reference = AntiControlledGate; + let solution = Kata.AntiControlledGate; + let reference = AntiControlledGate; let isCorrect = CheckOperationsAreEqualStrict(2, solution, reference); // Output different feedback to the user depending on whether the solution was correct. @@ -17,7 +17,7 @@ namespace Kata.Verification { } else { Message("Incorrect."); Message("Hint: examine the state prepared by your solution and compare it with the state it " + - "is expected to prepare."); + "is expected to prepare."); ShowQuantumStateComparison(2, PrepDemoState, solution, reference); } diff --git a/katas/content/multi_qubit_gates/arbitrary_controls/Verification.qs b/katas/content/multi_qubit_gates/arbitrary_controls/Verification.qs index 4aa0188d6a..a8579c524d 100644 --- a/katas/content/multi_qubit_gates/arbitrary_controls/Verification.qs +++ b/katas/content/multi_qubit_gates/arbitrary_controls/Verification.qs @@ -1,23 +1,23 @@ namespace Kata.Verification { - open Microsoft.Quantum.Arrays; - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Katas; + import Std.Arrays.*; + import Std.Convert.*; + import Std.Diagnostics.*; + import KatasUtils.*; operation MultiControls(controls : Qubit[], target : Qubit, controlBits : Bool[]) : Unit is Adj + Ctl { within { - for index in 0 .. Length(controls) - 1 { + for index in 0..Length(controls) - 1 { if controlBits[index] == false { X(controls[index]); } } } apply { - Controlled X(controls,target); + Controlled X(controls, target); } } operation CheckSolution() : Bool { - for i in 0 .. (2 ^ 4) - 1 { + for i in 0..(2^4) - 1 { let bits = IntAsBoolArray(i, 4); let solution = register => Kata.MultiControls(Most(register), Tail(register), bits); let reference = register => MultiControls(Most(register), Tail(register), bits); @@ -31,4 +31,4 @@ namespace Kata.Verification { Message("Correct!"); true } -} \ No newline at end of file +} diff --git a/katas/content/multi_qubit_gates/compound_gate/Verification.qs b/katas/content/multi_qubit_gates/compound_gate/Verification.qs index 37699019fa..7b21540a79 100644 --- a/katas/content/multi_qubit_gates/compound_gate/Verification.qs +++ b/katas/content/multi_qubit_gates/compound_gate/Verification.qs @@ -1,8 +1,8 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; + import KatasUtils.*; + import Std.Math.*; - operation CompoundGate (qs : Qubit[]) : Unit is Adj + Ctl { + operation CompoundGate(qs : Qubit[]) : Unit is Adj + Ctl { S(qs[0]); I(qs[1]); // this line can be omitted, since it doesn't change the qubit state Y(qs[2]); @@ -25,4 +25,4 @@ namespace Kata.Verification { isCorrect } -} \ No newline at end of file +} diff --git a/katas/content/multi_qubit_gates/controlled_rotation/Verification.qs b/katas/content/multi_qubit_gates/controlled_rotation/Verification.qs index 3b0b5c83aa..2a5f936417 100644 --- a/katas/content/multi_qubit_gates/controlled_rotation/Verification.qs +++ b/katas/content/multi_qubit_gates/controlled_rotation/Verification.qs @@ -1,16 +1,16 @@ namespace Kata.Verification { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Katas; + import Std.Convert.*; + import Std.Diagnostics.*; + import KatasUtils.*; - operation ControlledRotation (qs : Qubit[], theta : Double) : Unit is Adj + Ctl { + operation ControlledRotation(qs : Qubit[], theta : Double) : Unit is Adj + Ctl { let controll = qs[0]; let target = qs[1]; Controlled Rx([controll], (theta, target)); } operation CheckSolution() : Bool { - for i in 0 .. 20 { + for i in 0..20 { let angle = IntAsDouble(i) / 10.0; let solution = register => Kata.ControlledRotation(register, angle); let reference = register => ControlledRotation(register, angle); @@ -25,4 +25,4 @@ namespace Kata.Verification { Message("Correct!"); true } -} \ No newline at end of file +} diff --git a/katas/content/multi_qubit_gates/entangle_qubits/Verification.qs b/katas/content/multi_qubit_gates/entangle_qubits/Verification.qs index 56ebf5aa39..2308782120 100644 --- a/katas/content/multi_qubit_gates/entangle_qubits/Verification.qs +++ b/katas/content/multi_qubit_gates/entangle_qubits/Verification.qs @@ -1,24 +1,25 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Math; - open Microsoft.Quantum.Convert; + import KatasUtils.*; + import Std.Diagnostics.*; + import Std.Math.*; + import Std.Convert.*; - operation EntangleQubits (qs : Qubit[]) : Unit is Adj + Ctl { + operation EntangleQubits(qs : Qubit[]) : Unit is Adj + Ctl { CNOT(qs[0], qs[1]); } @EntryPoint() operation CheckSolution() : Bool { let range = 10; - for i in 0 .. range - 1 { + for i in 0..range - 1 { let angle = 2.0 * PI() * IntAsDouble(i) / IntAsDouble(range); let initialState = qs => Ry(2.0 * angle, qs[0]); let isCorrect = CheckOperationsEquivalenceOnInitialStateStrict( initialState, - Kata.EntangleQubits, - EntangleQubits, - 2); + Kata.EntangleQubits, + EntangleQubits, + 2 + ); if not isCorrect { Message("Incorrect"); Message($"Test fails for alpha = {Cos(angle)}, beta = {Sin(angle)}."); @@ -30,4 +31,4 @@ namespace Kata.Verification { Message("Correct!"); true } -} \ No newline at end of file +} diff --git a/katas/content/multi_qubit_gates/fredkin_gate/Verification.qs b/katas/content/multi_qubit_gates/fredkin_gate/Verification.qs index 3d08984d89..5515af9566 100644 --- a/katas/content/multi_qubit_gates/fredkin_gate/Verification.qs +++ b/katas/content/multi_qubit_gates/fredkin_gate/Verification.qs @@ -1,7 +1,7 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; - operation FredkinGate (qs : Qubit[]) : Unit is Adj + Ctl { + operation FredkinGate(qs : Qubit[]) : Unit is Adj + Ctl { Controlled SWAP([qs[0]], (qs[1], qs[2])); } @@ -22,4 +22,4 @@ namespace Kata.Verification { isCorrect } -} \ No newline at end of file +} diff --git a/katas/content/multi_qubit_gates/preparing_bell_state/Verification.qs b/katas/content/multi_qubit_gates/preparing_bell_state/Verification.qs index 7183842ee0..fdd7e7a639 100644 --- a/katas/content/multi_qubit_gates/preparing_bell_state/Verification.qs +++ b/katas/content/multi_qubit_gates/preparing_bell_state/Verification.qs @@ -1,7 +1,7 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; - operation BellState (qs : Qubit[]) : Unit is Adj + Ctl { + operation BellState(qs : Qubit[]) : Unit is Adj + Ctl { H(qs[0]); CNOT(qs[0], qs[1]); } @@ -23,4 +23,4 @@ namespace Kata.Verification { isCorrect } -} \ No newline at end of file +} diff --git a/katas/content/multi_qubit_gates/qubit_swap/Verification.qs b/katas/content/multi_qubit_gates/qubit_swap/Verification.qs index ae2ed877a6..39b2bcfad9 100644 --- a/katas/content/multi_qubit_gates/qubit_swap/Verification.qs +++ b/katas/content/multi_qubit_gates/qubit_swap/Verification.qs @@ -1,15 +1,15 @@ namespace Kata.Verification { - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Katas; + import Std.Diagnostics.*; + import KatasUtils.*; - operation QubitSwap (qs : Qubit[], index1 : Int, index2 : Int) : Unit is Adj + Ctl { - SWAP(qs[index1], qs[index2]); + operation QubitSwap(qs : Qubit[], index1 : Int, index2 : Int) : Unit is Adj + Ctl { + SWAP(qs[index1], qs[index2]); } operation CheckSolution() : Bool { - for N in 2 .. 5 { - for index1 in 0 .. N-2 { - for index2 in index1+1 .. N-1 { + for N in 2..5 { + for index1 in 0..N-2 { + for index2 in index1 + 1..N-1 { let solution = register => Kata.QubitSwap(register, index1, index2); let reference = register => QubitSwap(register, index1, index2); if not CheckOperationsAreEqual(N, solution, reference) { @@ -24,4 +24,4 @@ namespace Kata.Verification { Message("Correct!"); true } -} \ No newline at end of file +} diff --git a/katas/content/multi_qubit_gates/relative_phase_minusone/Verification.qs b/katas/content/multi_qubit_gates/relative_phase_minusone/Verification.qs index 63b2a8ca16..6c16bb9940 100644 --- a/katas/content/multi_qubit_gates/relative_phase_minusone/Verification.qs +++ b/katas/content/multi_qubit_gates/relative_phase_minusone/Verification.qs @@ -1,23 +1,24 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Diagnostics; + import KatasUtils.*; + import Std.Diagnostics.*; operation PrepareState(qs : Qubit[]) : Unit is Adj + Ctl { ApplyToEachCA(H, qs); } - operation RelativePhaseMinusOne (qs : Qubit[]) : Unit is Adj + Ctl { + operation RelativePhaseMinusOne(qs : Qubit[]) : Unit is Adj + Ctl { CZ(qs[0], qs[1]); } - + @EntryPoint() operation CheckSolution() : Bool { let isCorrect = CheckOperationsEquivalenceOnInitialStateStrict( PrepareState, - Kata.RelativePhaseMinusOne, - RelativePhaseMinusOne, - 2); + Kata.RelativePhaseMinusOne, + RelativePhaseMinusOne, + 2 + ); if isCorrect { Message("Correct!"); } else { @@ -27,4 +28,4 @@ namespace Kata.Verification { return isCorrect; } -} \ No newline at end of file +} diff --git a/katas/content/multi_qubit_gates/toffoli_gate/Verification.qs b/katas/content/multi_qubit_gates/toffoli_gate/Verification.qs index 911da6009e..63e47a9194 100644 --- a/katas/content/multi_qubit_gates/toffoli_gate/Verification.qs +++ b/katas/content/multi_qubit_gates/toffoli_gate/Verification.qs @@ -1,7 +1,7 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; - operation ToffoliGate (qs : Qubit[]) : Unit is Adj + Ctl { + operation ToffoliGate(qs : Qubit[]) : Unit is Adj + Ctl { CCNOT(qs[0], qs[1], qs[2]); } @@ -22,4 +22,4 @@ namespace Kata.Verification { isCorrect } -} \ No newline at end of file +} diff --git a/katas/content/multi_qubit_measurements/examples/MeasuringOne.qs b/katas/content/multi_qubit_measurements/examples/MeasuringOne.qs index d0e92f0d3f..aec873424e 100644 --- a/katas/content/multi_qubit_measurements/examples/MeasuringOne.qs +++ b/katas/content/multi_qubit_measurements/examples/MeasuringOne.qs @@ -1,7 +1,7 @@ namespace Kata { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Math; + import Std.Convert.*; + import Std.Diagnostics.*; + import Std.Math.*; @EntryPoint() operation DemoBasisMeasurement() : Unit { @@ -12,7 +12,7 @@ namespace Kata { use qs = Qubit[2]; let numRuns = 1000; - for i in 1 .. numRuns { + for i in 1..numRuns { // Prepare the starting state. Ry(2. * ArcCos(1. / 3.), qs[1]); Controlled H([qs[1]], qs[0]); @@ -30,9 +30,8 @@ namespace Kata { // Obtain simulated probability of measurement for each outcome. mutable simulated_probabilities = []; - for i in 0 .. 3 { - set simulated_probabilities += - [IntAsDouble(countArray[i]) / IntAsDouble(numRuns)]; + for i in 0..3 { + set simulated_probabilities += [IntAsDouble(countArray[i]) / IntAsDouble(numRuns)]; } Message($"Theoretical measurement probabilities are {expected_probabilities}"); diff --git a/katas/content/multi_qubit_measurements/examples/MultiQubitProbabilities.qs b/katas/content/multi_qubit_measurements/examples/MultiQubitProbabilities.qs index 73c1874054..81db60f7a7 100644 --- a/katas/content/multi_qubit_measurements/examples/MultiQubitProbabilities.qs +++ b/katas/content/multi_qubit_measurements/examples/MultiQubitProbabilities.qs @@ -1,6 +1,6 @@ namespace Kata { - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Math; + import Std.Diagnostics.*; + import Std.Math.*; @EntryPoint() operation CalculateProbabilities() : Unit { diff --git a/katas/content/multi_qubit_measurements/examples/PartialMeasurementsDemo.qs b/katas/content/multi_qubit_measurements/examples/PartialMeasurementsDemo.qs index 4737b201d0..50b1224998 100644 --- a/katas/content/multi_qubit_measurements/examples/PartialMeasurementsDemo.qs +++ b/katas/content/multi_qubit_measurements/examples/PartialMeasurementsDemo.qs @@ -1,7 +1,7 @@ namespace Kata { - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Math; + import Std.Diagnostics.*; + import Std.Convert.*; + import Std.Math.*; @EntryPoint() operation DemoPartialMeasurement() : Unit { @@ -10,7 +10,7 @@ namespace Kata { let numRuns = 1000; mutable countArray = [0, 0]; use qs = Qubit[2]; - for i in 1 .. numRuns { + for i in 1..numRuns { // Prepare the Hardy state |𝜓❭ = (1/√12)(3|00⟩ + |01⟩ + |10⟩ + |11⟩) Ry(2. * ArcCos(Sqrt(5. / 6.)), qs[0]); ApplyControlledOnInt(0, Ry, [qs[0]], (2. * ArcCos(3. / Sqrt(10.)), qs[1])); @@ -35,7 +35,7 @@ namespace Kata { // Obtain simulated probability of measurement for each outcome. mutable simulated_probabilities = []; - for i in 0 .. 1 { + for i in 0..1 { set simulated_probabilities += [IntAsDouble(countArray[i]) / IntAsDouble(numRuns)]; } diff --git a/katas/content/multi_qubit_measurements/full_measurements/SolutionAlt.qs b/katas/content/multi_qubit_measurements/full_measurements/SolutionAlt.qs index cbd14600e2..c28cf9a0e3 100644 --- a/katas/content/multi_qubit_measurements/full_measurements/SolutionAlt.qs +++ b/katas/content/multi_qubit_measurements/full_measurements/SolutionAlt.qs @@ -1,6 +1,6 @@ namespace Kata { - open Microsoft.Quantum.Arrays; - open Microsoft.Quantum.Convert; + import Std.Arrays.*; + import Std.Convert.*; operation BasisStateMeasurement(qs : Qubit[]) : Int { return ResultArrayAsInt(Reversed(MeasureEachZ(qs))); diff --git a/katas/content/multi_qubit_measurements/full_measurements/Verification.qs b/katas/content/multi_qubit_measurements/full_measurements/Verification.qs index 0769fe058d..39aba2380d 100644 --- a/katas/content/multi_qubit_measurements/full_measurements/Verification.qs +++ b/katas/content/multi_qubit_measurements/full_measurements/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; // Distinguish four basis states operation StatePrep_BasisStateMeasurement(qs : Qubit[], state : Int, dummyVar : Double) : Unit is Adj { @@ -21,7 +21,8 @@ namespace Kata.Verification { StatePrep_BasisStateMeasurement, Kata.BasisStateMeasurement, false, - ["|00⟩", "|01⟩", "|10⟩", "|11⟩"]); + ["|00⟩", "|01⟩", "|10⟩", "|11⟩"] + ); if (isCorrect) { Message("Correct!"); diff --git a/katas/content/multi_qubit_measurements/joint_measurements/Verification.qs b/katas/content/multi_qubit_measurements/joint_measurements/Verification.qs index 8440beda6d..ca47ba2bc6 100644 --- a/katas/content/multi_qubit_measurements/joint_measurements/Verification.qs +++ b/katas/content/multi_qubit_measurements/joint_measurements/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; // Two qubit parity Measurement operation StatePrep_ParityMeasurement(qs : Qubit[], state : Int, alpha : Double) : Unit is Adj { @@ -21,7 +21,8 @@ namespace Kata.Verification { StatePrep_ParityMeasurement, Kata.ParityMeasurement, true, - ["α|00⟩ + β|11⟩", "α|01⟩ + β|10⟩"]); + ["α|00⟩ + β|11⟩", "α|01⟩ + β|10⟩"] + ); if (isCorrect) { Message("Correct!"); diff --git a/katas/content/multi_qubit_measurements/partial_measurements_for_system/Verification.qs b/katas/content/multi_qubit_measurements/partial_measurements_for_system/Verification.qs index 63885d1563..08f38d9b79 100644 --- a/katas/content/multi_qubit_measurements/partial_measurements_for_system/Verification.qs +++ b/katas/content/multi_qubit_measurements/partial_measurements_for_system/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; // Distinguish orthogonal states using partial measurements operation StatePrep_IsPlusPlusMinus(qs : Qubit[], state : Int, dummyVar : Double) : Unit is Adj { @@ -21,13 +21,14 @@ namespace Kata.Verification { StatePrep_IsPlusPlusMinus, Kata.IsPlusPlusMinus, true, - ["|++-⟩", "|---⟩"]); + ["|++-⟩", "|---⟩"] + ); if (isCorrect) { Message("Correct!"); } else { Message("Incorrect."); } - isCorrect + isCorrect } } diff --git a/katas/content/multi_qubit_measurements/state_modification/Verification.qs b/katas/content/multi_qubit_measurements/state_modification/Verification.qs index a17f2dedc7..933aee2491 100644 --- a/katas/content/multi_qubit_measurements/state_modification/Verification.qs +++ b/katas/content/multi_qubit_measurements/state_modification/Verification.qs @@ -1,7 +1,7 @@ namespace Kata.Verification { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Math; + import Std.Convert.*; + import Std.Diagnostics.*; + import Std.Math.*; // State selection using partial measurements operation StateInitialize_StateSelection(alpha : Double, qs : Qubit[]) : Unit { @@ -29,11 +29,11 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { use qs = Qubit[2]; - for i in 0 .. 5 { + for i in 0..5 { let alpha = (PI() * IntAsDouble(i)) / 5.0; let params = $"a = {Cos(alpha)}, b = {Sin(alpha)}"; - for ind in 0 .. 1 { + for ind in 0..1 { // Prepare the state to be input to the testImplementation StateInitialize_StateSelection(alpha, qs); @@ -42,7 +42,7 @@ namespace Kata.Verification { // Apply adjoint of state preparation operation Adjoint StatePrepare_StateSelection(alpha, ind, qs[1]); - // We only care about the state of the second qubit; + // We only care about the state of the second qubit; // if it's still entangled with the first one or not in zero state, this check will fail. if not CheckZero(qs[1]) { ResetAll(qs); diff --git a/katas/content/multi_qubit_measurements/state_preparation/Verification.qs b/katas/content/multi_qubit_measurements/state_preparation/Verification.qs index d9af9bb16a..3ec782ec36 100644 --- a/katas/content/multi_qubit_measurements/state_preparation/Verification.qs +++ b/katas/content/multi_qubit_measurements/state_preparation/Verification.qs @@ -1,7 +1,7 @@ namespace Kata.Verification { - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; + import Std.Diagnostics.*; + import KatasUtils.*; + import Std.Math.*; // Reference solution that does not use measurements (to be adjointable) operation StatePrep_Rotations(qs : Qubit[]) : Unit is Adj { diff --git a/katas/content/multi_qubit_systems/bell_state_change_1/Verification.qs b/katas/content/multi_qubit_systems/bell_state_change_1/Verification.qs index 706abba6c4..b93049ae0c 100644 --- a/katas/content/multi_qubit_systems/bell_state_change_1/Verification.qs +++ b/katas/content/multi_qubit_systems/bell_state_change_1/Verification.qs @@ -1,6 +1,6 @@ namespace Kata.Verification { - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Katas; + import Std.Diagnostics.*; + import KatasUtils.*; operation PrepareBellState(qs : Qubit[]) : Unit is Adj + Ctl { H(qs[0]); @@ -17,9 +17,10 @@ namespace Kata.Verification { operation CheckSolution() : Bool { let isCorrect = CheckOperationsEquivalenceOnInitialStateStrict( PrepareBellState, - Kata.BellStateChange1, - BellStateChange1_Reference, - 2); + Kata.BellStateChange1, + BellStateChange1_Reference, + 2 + ); if isCorrect { Message("Correct!"); diff --git a/katas/content/multi_qubit_systems/bell_state_change_2/Verification.qs b/katas/content/multi_qubit_systems/bell_state_change_2/Verification.qs index 9c13d2546e..e3995b82d6 100644 --- a/katas/content/multi_qubit_systems/bell_state_change_2/Verification.qs +++ b/katas/content/multi_qubit_systems/bell_state_change_2/Verification.qs @@ -1,6 +1,6 @@ namespace Kata.Verification { - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Katas; + import Std.Diagnostics.*; + import KatasUtils.*; operation PrepareBellState(qs : Qubit[]) : Unit is Adj + Ctl { H(qs[0]); @@ -17,9 +17,10 @@ namespace Kata.Verification { operation CheckSolution() : Bool { let isCorrect = CheckOperationsEquivalenceOnInitialStateStrict( PrepareBellState, - Kata.BellStateChange2, - BellStateChange2_Reference, - 2); + Kata.BellStateChange2, + BellStateChange2_Reference, + 2 + ); if isCorrect { Message("Correct!"); diff --git a/katas/content/multi_qubit_systems/bell_state_change_3/Verification.qs b/katas/content/multi_qubit_systems/bell_state_change_3/Verification.qs index d980fa3706..1514c09cba 100644 --- a/katas/content/multi_qubit_systems/bell_state_change_3/Verification.qs +++ b/katas/content/multi_qubit_systems/bell_state_change_3/Verification.qs @@ -1,6 +1,6 @@ namespace Kata.Verification { - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Katas; + import Std.Diagnostics.*; + import KatasUtils.*; operation PrepareBellState(qs : Qubit[]) : Unit is Adj + Ctl { H(qs[0]); @@ -18,9 +18,10 @@ namespace Kata.Verification { operation CheckSolution() : Bool { let isCorrect = CheckOperationsEquivalenceOnInitialStateStrict( PrepareBellState, - Kata.BellStateChange3, - BellStateChange3_Reference, - 2); + Kata.BellStateChange3, + BellStateChange3_Reference, + 2 + ); if isCorrect { Message("Correct!"); diff --git a/katas/content/multi_qubit_systems/examples/MultiQubitSystems.qs b/katas/content/multi_qubit_systems/examples/MultiQubitSystems.qs index d15b10aeef..3165dd74c3 100644 --- a/katas/content/multi_qubit_systems/examples/MultiQubitSystems.qs +++ b/katas/content/multi_qubit_systems/examples/MultiQubitSystems.qs @@ -1,8 +1,8 @@ namespace Kata { - open Microsoft.Quantum.Diagnostics; + import Std.Diagnostics.*; @EntryPoint() - operation MultiQubitSystemsDemo () : Unit { + operation MultiQubitSystemsDemo() : Unit { // This allocates an array of 2 qubits, each of them in state |0⟩. // The overall state of the system is |00⟩. use qs = Qubit[2]; @@ -30,4 +30,4 @@ namespace Kata { // This returns the system into state |00⟩. ResetAll(qs); } -} \ No newline at end of file +} diff --git a/katas/content/multi_qubit_systems/learn_basis_state_amplitudes/Solution.qs b/katas/content/multi_qubit_systems/learn_basis_state_amplitudes/Solution.qs index b4ec113e72..ccc43c464d 100644 --- a/katas/content/multi_qubit_systems/learn_basis_state_amplitudes/Solution.qs +++ b/katas/content/multi_qubit_systems/learn_basis_state_amplitudes/Solution.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Diagnostics; + import Std.Diagnostics.*; operation LearnBasisStateAmplitudes(qs : Qubit[]) : (Double, Double) { DumpMachine(); // Only used to learn the amplitudes. diff --git a/katas/content/multi_qubit_systems/learn_basis_state_amplitudes/Verification.qs b/katas/content/multi_qubit_systems/learn_basis_state_amplitudes/Verification.qs index ebc9962ea7..10c0c50bbb 100644 --- a/katas/content/multi_qubit_systems/learn_basis_state_amplitudes/Verification.qs +++ b/katas/content/multi_qubit_systems/learn_basis_state_amplitudes/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Math; + import Std.Math.*; @EntryPoint() operation CheckSolution() : Bool { @@ -18,8 +18,9 @@ namespace Kata.Verification { // * the amplitude of |01⟩ is 2nd amp of Ry(1.0)|0⟩ // * the amplitude of |10⟩ is 1st amp of Ry(2.0)|0⟩ let (x1_exp, x2_exp) = ( - 1.0/Sqrt(2.0) * Sin(0.5 * 1.0), - 1.0/Sqrt(2.0) * Cos(0.5 * 2.0)); + 1.0 / Sqrt(2.0) * Sin(0.5 * 1.0), + 1.0 / Sqrt(2.0) * Cos(0.5 * 2.0) + ); let isCorrect = (AbsD(x1 - x1_exp) <= 0.001) and diff --git a/katas/content/multi_qubit_systems/prepare_basis_state/Verification.qs b/katas/content/multi_qubit_systems/prepare_basis_state/Verification.qs index f97c6d02d7..8301ba6f9a 100644 --- a/katas/content/multi_qubit_systems/prepare_basis_state/Verification.qs +++ b/katas/content/multi_qubit_systems/prepare_basis_state/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; operation PrepareBasisState_Reference(qs : Qubit[]) : Unit is Adj + Ctl { X(qs[0]); @@ -8,7 +8,10 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { - CheckOperationsEquivalenceOnZeroStateWithFeedback(Kata.PrepareBasisState, - PrepareBasisState_Reference, 2) + CheckOperationsEquivalenceOnZeroStateWithFeedback( + Kata.PrepareBasisState, + PrepareBasisState_Reference, + 2 + ) } } diff --git a/katas/content/multi_qubit_systems/prepare_superposition/Verification.qs b/katas/content/multi_qubit_systems/prepare_superposition/Verification.qs index 8554c57abf..a27092e432 100644 --- a/katas/content/multi_qubit_systems/prepare_superposition/Verification.qs +++ b/katas/content/multi_qubit_systems/prepare_superposition/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; operation PrepareSuperposition_Reference(qs : Qubit[]) : Unit is Adj + Ctl { X(qs[1]); @@ -8,7 +8,10 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { - CheckOperationsEquivalenceOnZeroStateWithFeedback(Kata.PrepareSuperposition, - PrepareSuperposition_Reference, 2) + CheckOperationsEquivalenceOnZeroStateWithFeedback( + Kata.PrepareSuperposition, + PrepareSuperposition_Reference, + 2 + ) } } diff --git a/katas/content/multi_qubit_systems/prepare_with_complex/Verification.qs b/katas/content/multi_qubit_systems/prepare_with_complex/Verification.qs index 556dbbe701..258b5d72e7 100644 --- a/katas/content/multi_qubit_systems/prepare_with_complex/Verification.qs +++ b/katas/content/multi_qubit_systems/prepare_with_complex/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; operation PrepareWithComplex_Reference(qs : Qubit[]) : Unit is Adj + Ctl { H(qs[0]); @@ -10,7 +10,10 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { - CheckOperationsEquivalenceOnZeroStateWithFeedback(Kata.PrepareWithComplex, - PrepareWithComplex_Reference, 2) + CheckOperationsEquivalenceOnZeroStateWithFeedback( + Kata.PrepareWithComplex, + PrepareWithComplex_Reference, + 2 + ) } } diff --git a/katas/content/multi_qubit_systems/prepare_with_real/Verification.qs b/katas/content/multi_qubit_systems/prepare_with_real/Verification.qs index 1d6d765c56..e6fb26e7ec 100644 --- a/katas/content/multi_qubit_systems/prepare_with_real/Verification.qs +++ b/katas/content/multi_qubit_systems/prepare_with_real/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; operation PrepareWithReal_Reference(qs : Qubit[]) : Unit is Adj + Ctl { H(qs[0]); @@ -9,7 +9,10 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { - CheckOperationsEquivalenceOnZeroStateWithFeedback(Kata.PrepareWithReal, - PrepareWithReal_Reference, 2) + CheckOperationsEquivalenceOnZeroStateWithFeedback( + Kata.PrepareWithReal, + PrepareWithReal_Reference, + 2 + ) } } diff --git a/katas/content/nonlocal_games/chsh_classical_strategy/Verification.qs b/katas/content/nonlocal_games/chsh_classical_strategy/Verification.qs index 8526baa4d0..cddd2efc2d 100644 --- a/katas/content/nonlocal_games/chsh_classical_strategy/Verification.qs +++ b/katas/content/nonlocal_games/chsh_classical_strategy/Verification.qs @@ -1,6 +1,6 @@ namespace Kata.Verification { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Random; + import Std.Convert.*; + import Std.Random.*; @EntryPoint() operation CheckSolution() : Bool { diff --git a/katas/content/nonlocal_games/chsh_classical_win_condition/Verification.qs b/katas/content/nonlocal_games/chsh_classical_win_condition/Verification.qs index 82a16cd2d8..4b6b86215b 100644 --- a/katas/content/nonlocal_games/chsh_classical_win_condition/Verification.qs +++ b/katas/content/nonlocal_games/chsh_classical_win_condition/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Convert; + import Std.Convert.*; function WinCondition_Reference(x : Bool, y : Bool, a : Bool, b : Bool) : Bool { return (x and y) == (a != b); @@ -13,8 +13,8 @@ namespace Kata.Verification { let actual = Kata.WinCondition(bits[0], bits[1], bits[2], bits[3]); if actual != expected { - Message($"Win condition '{actual}' isn't as expected for X = {bits[0]}, Y = {bits[1]}, " + - $"A = {bits[2]}, B = {bits[3]}"); + Message($"Win condition '{actual}' isn't as expected for X = {bits[0]}, Y = {bits[1]}, " + + $"A = {bits[2]}, B = {bits[3]}"); return false; } } diff --git a/katas/content/nonlocal_games/chsh_quantum_alice_strategy/Verification.qs b/katas/content/nonlocal_games/chsh_quantum_alice_strategy/Verification.qs index d1554e79c7..7c83716fe7 100644 --- a/katas/content/nonlocal_games/chsh_quantum_alice_strategy/Verification.qs +++ b/katas/content/nonlocal_games/chsh_quantum_alice_strategy/Verification.qs @@ -1,11 +1,11 @@ namespace Kata.Verification { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Random; + import Std.Convert.*; + import Std.Random.*; @EntryPoint() operation CheckSolution() : Bool { use q = Qubit(); - for _ in 1 .. 4 { + for _ in 1..4 { // repeat 4 times since we are testing a measurement and wrong basis still might get // the correct answer, reduces probability of false positives let result = Kata.AliceQuantum(false, q); diff --git a/katas/content/nonlocal_games/chsh_quantum_bob_strategy/Placeholder.qs b/katas/content/nonlocal_games/chsh_quantum_bob_strategy/Placeholder.qs index 2477ed5ad7..47c1115b18 100644 --- a/katas/content/nonlocal_games/chsh_quantum_bob_strategy/Placeholder.qs +++ b/katas/content/nonlocal_games/chsh_quantum_bob_strategy/Placeholder.qs @@ -1,7 +1,7 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; - operation BobQuantum (bit : Bool, qubit : Qubit) : Bool { + operation BobQuantum(bit : Bool, qubit : Qubit) : Bool { // Implement your solution here... return false; diff --git a/katas/content/nonlocal_games/chsh_quantum_bob_strategy/Solution.qs b/katas/content/nonlocal_games/chsh_quantum_bob_strategy/Solution.qs index ba690fe500..ffd7f30909 100644 --- a/katas/content/nonlocal_games/chsh_quantum_bob_strategy/Solution.qs +++ b/katas/content/nonlocal_games/chsh_quantum_bob_strategy/Solution.qs @@ -1,7 +1,7 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; - operation BobQuantum (bit : Bool, qubit : Qubit) : Bool { + operation BobQuantum(bit : Bool, qubit : Qubit) : Bool { let angle = 2.0 * PI() / 8.0; Ry(not bit ? -angle | angle, qubit); return M(qubit) == One; diff --git a/katas/content/nonlocal_games/chsh_quantum_bob_strategy/Verification.qs b/katas/content/nonlocal_games/chsh_quantum_bob_strategy/Verification.qs index 1d35fd08e5..8c218525b4 100644 --- a/katas/content/nonlocal_games/chsh_quantum_bob_strategy/Verification.qs +++ b/katas/content/nonlocal_games/chsh_quantum_bob_strategy/Verification.qs @@ -1,17 +1,17 @@ namespace Kata.Verification { - open Microsoft.Quantum.Math; + import Std.Math.*; - operation RotateBobQubit (clockwise : Bool, qubit : Qubit) : Unit { + operation RotateBobQubit(clockwise : Bool, qubit : Qubit) : Unit { if (clockwise) { - Ry(-PI()/4.0, qubit); + Ry(-PI() / 4.0, qubit); } else { - Ry(PI()/4.0, qubit); + Ry(PI() / 4.0, qubit); } } @EntryPoint() operation CheckSolution() : Bool { - for _ in 1 .. 4 { + for _ in 1..4 { // repeat 4 times since we are testing a measurement and wrong basis still might get // the correct answer, reduces probability of false positives use q = Qubit(); @@ -51,5 +51,5 @@ namespace Kata.Verification { } Message("Correct!"); true - } + } } diff --git a/katas/content/nonlocal_games/examples/CHSHGameDemo.qs b/katas/content/nonlocal_games/examples/CHSHGameDemo.qs index b062f35baf..7581085e60 100644 --- a/katas/content/nonlocal_games/examples/CHSHGameDemo.qs +++ b/katas/content/nonlocal_games/examples/CHSHGameDemo.qs @@ -1,28 +1,28 @@ namespace Quantum.Kata.CHSHGame { - open Microsoft.Quantum.Random; - open Microsoft.Quantum.Math; - open Microsoft.Quantum.Convert; + import Std.Random.*; + import Std.Math.*; + import Std.Convert.*; - function WinCondition (x : Bool, y : Bool, a : Bool, b : Bool) : Bool { + function WinCondition(x : Bool, y : Bool, a : Bool, b : Bool) : Bool { return (x and y) == (a != b); } - function AliceClassical (x : Bool) : Bool { + function AliceClassical(x : Bool) : Bool { return false; } - function BobClassical (y : Bool) : Bool { + function BobClassical(y : Bool) : Bool { return false; } - operation AliceQuantum (bit : Bool, qubit : Qubit) : Bool { + operation AliceQuantum(bit : Bool, qubit : Qubit) : Bool { if bit { return MResetX(qubit) == One; } return MResetZ(qubit) == One; } - operation BobQuantum (bit : Bool, qubit : Qubit) : Bool { + operation BobQuantum(bit : Bool, qubit : Qubit) : Bool { let angle = 2.0 * PI() / 8.0; Ry(not bit ? -angle | angle, qubit); return M(qubit) == One; @@ -34,7 +34,7 @@ namespace Quantum.Kata.CHSHGame { mutable classicalWins = 0; mutable quantumWins = 0; let iterations = 1000; - for _ in 1 .. iterations { + for _ in 1..iterations { H(aliceQubit); CNOT(aliceQubit, bobQubit); let (x, y) = (DrawRandomBool(0.5), DrawRandomBool(0.5)); @@ -46,7 +46,7 @@ namespace Quantum.Kata.CHSHGame { } ResetAll([aliceQubit, bobQubit]); } - Message($"Percentage of classical wins is {100.0*IntAsDouble(classicalWins)/IntAsDouble(iterations)}%"); - Message($"Percentage of quantum wins is {100.0*IntAsDouble(quantumWins)/IntAsDouble(iterations)}%"); + Message($"Percentage of classical wins is {100.0 * IntAsDouble(classicalWins) / IntAsDouble(iterations)}%"); + Message($"Percentage of quantum wins is {100.0 * IntAsDouble(quantumWins) / IntAsDouble(iterations)}%"); } } diff --git a/katas/content/nonlocal_games/ghz_classical_strategy/Verification.qs b/katas/content/nonlocal_games/ghz_classical_strategy/Verification.qs index 853abaa47a..8f3f9e30e0 100644 --- a/katas/content/nonlocal_games/ghz_classical_strategy/Verification.qs +++ b/katas/content/nonlocal_games/ghz_classical_strategy/Verification.qs @@ -1,23 +1,25 @@ namespace Kata.Verification { - open Microsoft.Quantum.Arrays; - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Logical; - open Microsoft.Quantum.Random; + import Std.Arrays.*; + import Std.Convert.*; + import Std.Logical.*; + import Std.Random.*; - function WinCondition_Reference (rst : Bool[], abc : Bool[]) : Bool { + function WinCondition_Reference(rst : Bool[], abc : Bool[]) : Bool { return (rst[0] or rst[1] or rst[2]) == (abc[0] != abc[1] != abc[2]); } // All possible starting bits (r, s and t) that the referee can give // to Alice, Bob and Charlie. - function RefereeBits () : Bool[][] { - return [[false, false, false], - [true, true, false], - [false, true, true], - [true, false, true]]; + function RefereeBits() : Bool[][] { + return [ + [false, false, false], + [true, true, false], + [false, true, true], + [true, false, true] + ]; } - operation PlayClassicalGHZ_Reference (strategies : (Bool => Bool)[], inputs : Bool[]) : Bool[] { + operation PlayClassicalGHZ_Reference(strategies : (Bool => Bool)[], inputs : Bool[]) : Bool[] { let r = inputs[0]; let s = inputs[1]; let t = inputs[2]; @@ -34,7 +36,7 @@ namespace Kata.Verification { let iterations = 1000; mutable wins = 0; - for _ in 0 .. iterations - 1 { + for _ in 0..iterations - 1 { for bits in inputs { let abc = PlayClassicalGHZ_Reference(strategies, bits); if WinCondition_Reference(bits, abc) { @@ -43,8 +45,8 @@ namespace Kata.Verification { } } // The solution is correct if the players win 75% (3/4) of the time. - if wins < iterations*Length(inputs)*3/4 { - Message($"Alice, Bob, and Charlie's classical strategy gets {wins} wins out of {iterations*Length(inputs)} possible inputs, which is not optimal"); + if wins < iterations * Length(inputs) * 3 / 4 { + Message($"Alice, Bob, and Charlie's classical strategy gets {wins} wins out of {iterations * Length(inputs)} possible inputs, which is not optimal"); return false; } Message("Correct!"); diff --git a/katas/content/nonlocal_games/ghz_win_condition/Verification.qs b/katas/content/nonlocal_games/ghz_win_condition/Verification.qs index f4d60d7b4f..547324deae 100644 --- a/katas/content/nonlocal_games/ghz_win_condition/Verification.qs +++ b/katas/content/nonlocal_games/ghz_win_condition/Verification.qs @@ -1,23 +1,25 @@ namespace Kata.Verification { - open Microsoft.Quantum.Convert; + import Std.Convert.*; - function WinCondition_Reference (rst : Bool[], abc : Bool[]) : Bool { + function WinCondition_Reference(rst : Bool[], abc : Bool[]) : Bool { return (rst[0] or rst[1] or rst[2]) == (abc[0] != abc[1] != abc[2]); } // All possible starting bits (r, s and t) that the referee can give // to Alice, Bob and Charlie. - function RefereeBits () : Bool[][] { - return [[false, false, false], - [true, true, false], - [false, true, true], - [true, false, true]]; + function RefereeBits() : Bool[][] { + return [ + [false, false, false], + [true, true, false], + [false, true, true], + [true, false, true] + ]; } @EntryPoint() function CheckSolution() : Bool { for rst in RefereeBits() { - for i in 0 .. 1 <<< 3 - 1 { + for i in 0..1 <<< 3 - 1 { let abc = IntAsBoolArray(i, 3); let expected = WinCondition_Reference(rst, abc); let actual = Kata.WinCondition(rst, abc); diff --git a/katas/content/oracles/bit_pattern_challenge/Solution.qs b/katas/content/oracles/bit_pattern_challenge/Solution.qs index cbd4d70f04..89f83883d4 100644 --- a/katas/content/oracles/bit_pattern_challenge/Solution.qs +++ b/katas/content/oracles/bit_pattern_challenge/Solution.qs @@ -1,10 +1,10 @@ namespace Kata { - open Microsoft.Quantum.Arrays; + import Std.Arrays.*; operation ArbitraryBitPattern_Oracle_Challenge( x : Qubit[], - pattern : Bool[]) - : Unit is Adj + Ctl { + pattern : Bool[] + ) : Unit is Adj + Ctl { within { for i in IndexRange(x) { if not pattern[i] { diff --git a/katas/content/oracles/bit_pattern_challenge/Verification.qs b/katas/content/oracles/bit_pattern_challenge/Verification.qs index 525a854985..712528c9ea 100644 --- a/katas/content/oracles/bit_pattern_challenge/Verification.qs +++ b/katas/content/oracles/bit_pattern_challenge/Verification.qs @@ -1,7 +1,7 @@ namespace Kata.Verification { - open Microsoft.Quantum.Arrays; - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Katas; + import Std.Arrays.*; + import Std.Convert.*; + import KatasUtils.*; operation ArbitraryBitPattern_Oracle_Challenge_Reference(x : Qubit[], pattern : Bool[]) : Unit is Adj + Ctl { within { @@ -17,8 +17,8 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { - for N in 1 .. 3 { - for k in 0 .. 2^N -1 { + for N in 1..3 { + for k in 0..2^N -1 { let pattern = IntAsBoolArray(k, N); let sol = Kata.ArbitraryBitPattern_Oracle_Challenge(_, pattern); diff --git a/katas/content/oracles/bit_pattern_oracle/Verification.qs b/katas/content/oracles/bit_pattern_oracle/Verification.qs index 7c98881bff..2a1be9e6f4 100644 --- a/katas/content/oracles/bit_pattern_oracle/Verification.qs +++ b/katas/content/oracles/bit_pattern_oracle/Verification.qs @@ -1,16 +1,16 @@ namespace Kata.Verification { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Katas; + import Std.Convert.*; + import KatasUtils.*; - operation ArbitraryBitPattern_Oracle_Reference(x : Qubit[], y : Qubit, pattern : Bool[]) : Unit is Adj + Ctl { + operation ArbitraryBitPattern_Oracle_Reference(x : Qubit[], y : Qubit, pattern : Bool[]) : Unit is Adj + Ctl { ApplyControlledOnBitString(pattern, X, x, y); } // ------------------------------------------------------ @EntryPoint() operation CheckSolution() : Bool { - for N in 1 .. 3 { - for k in 0 .. 2^N - 1 { + for N in 1..3 { + for k in 0..2^N - 1 { let pattern = IntAsBoolArray(k, N); let sol = ApplyOracle(_, Kata.ArbitraryBitPattern_Oracle(_, _, pattern)); diff --git a/katas/content/oracles/classical_oracles/Verification.qs b/katas/content/oracles/classical_oracles/Verification.qs index 8525328fce..49a81328b5 100644 --- a/katas/content/oracles/classical_oracles/Verification.qs +++ b/katas/content/oracles/classical_oracles/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Convert; + import Std.Convert.*; function IsSeven_Reference(x : Bool[]) : Bool { return BoolArrayAsInt(x) == 7; @@ -8,7 +8,7 @@ namespace Kata.Verification { @EntryPoint() function CheckSolution() : Bool { let N = 3; - for k in 0 .. 2^N - 1 { + for k in 0..2^N - 1 { let x = IntAsBoolArray(k, N); let actual = Kata.IsSeven(x); diff --git a/katas/content/oracles/examples/MarkingOracleAltBit.qs b/katas/content/oracles/examples/MarkingOracleAltBit.qs index 339ca257fd..9b1313eee4 100644 --- a/katas/content/oracles/examples/MarkingOracleAltBit.qs +++ b/katas/content/oracles/examples/MarkingOracleAltBit.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Diagnostics; + import Std.Diagnostics.*; // This operation implements the oracle; we will learn how to implement oracles later in the kata operation AlternatingBitPattern_MarkingOracle(x : Qubit[], y : Qubit) : Unit is Adj + Ctl { diff --git a/katas/content/oracles/examples/OracleConverterDemo.qs b/katas/content/oracles/examples/OracleConverterDemo.qs index 6ac3041d64..0cad7113ec 100644 --- a/katas/content/oracles/examples/OracleConverterDemo.qs +++ b/katas/content/oracles/examples/OracleConverterDemo.qs @@ -1,9 +1,9 @@ namespace Kata { - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Arrays; + import Std.Diagnostics.*; + import Std.Arrays.*; @EntryPoint() - operation OracleConverterDemo () : Unit { + operation OracleConverterDemo() : Unit { use register = Qubit[3]; ApplyToEachA(H, register); @@ -37,8 +37,8 @@ namespace Kata { operation ApplyMarkingOracleAsPhaseOracle( markingOracle : ((Qubit[], Qubit) => Unit is Adj + Ctl), - qubits : Qubit[]) - : Unit is Adj + Ctl { + qubits : Qubit[] + ) : Unit is Adj + Ctl { use minus = Qubit(); within { X(minus); diff --git a/katas/content/oracles/examples/PhaseOracleAltBit.qs b/katas/content/oracles/examples/PhaseOracleAltBit.qs index 5ec1e54c13..d4103ddd5e 100644 --- a/katas/content/oracles/examples/PhaseOracleAltBit.qs +++ b/katas/content/oracles/examples/PhaseOracleAltBit.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Diagnostics; + import Std.Diagnostics.*; // This operation implements the oracle; we will learn how to implement oracles later in the kata operation AlternatingBitPattern_PhaseOracle(x : Qubit[]) : Unit is Adj + Ctl { diff --git a/katas/content/oracles/examples/TestMeetingOracle.qs b/katas/content/oracles/examples/TestMeetingOracle.qs index 086ad82a7b..93d62522c8 100644 --- a/katas/content/oracles/examples/TestMeetingOracle.qs +++ b/katas/content/oracles/examples/TestMeetingOracle.qs @@ -1,7 +1,7 @@ namespace Kata { - open Microsoft.Quantum.Arrays; - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Convert; + import Std.Arrays.*; + import Std.Diagnostics.*; + import Std.Convert.*; // The classical function to perform the same computation function Meeting_Classical(x : Bool[], jasmine : Bool[]) : Bool { @@ -36,8 +36,8 @@ namespace Kata { @EntryPoint() operation Test_Meeting_Oracle() : Unit { // There are 2^5 ways to arrange each of the schedules - let's try all of them - for k in 0 .. 2^5 - 1 { - for j in 0 .. 2^5 - 1 { + for k in 0..2^5 - 1 { + for j in 0..2^5 - 1 { // Convert your and Jasmine's schedules to bit arrays let binaryX = IntAsBoolArray(k, 5); let binaryJasmine = IntAsBoolArray(j, 5); diff --git a/katas/content/oracles/kth_bit_oracle/Verification.qs b/katas/content/oracles/kth_bit_oracle/Verification.qs index 7c72b4b154..46e4c81802 100644 --- a/katas/content/oracles/kth_bit_oracle/Verification.qs +++ b/katas/content/oracles/kth_bit_oracle/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; operation KthBit_Oracle_Reference(x : Qubit[], k : Int) : Unit is Adj + Ctl { Z(x[k]); @@ -7,8 +7,8 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { - for N in 1 .. 3 { - for k in 0 .. N - 1 { + for N in 1..3 { + for k in 0..N - 1 { let sol = Kata.KthBit_Oracle(_, k); let ref = KthBit_Oracle_Reference(_, k); let isCorrect = CheckOperationsAreEqualStrict(N, sol, ref); diff --git a/katas/content/oracles/marking_oracle_as_phase/Verification.qs b/katas/content/oracles/marking_oracle_as_phase/Verification.qs index 73b25454ef..4a67f24f94 100644 --- a/katas/content/oracles/marking_oracle_as_phase/Verification.qs +++ b/katas/content/oracles/marking_oracle_as_phase/Verification.qs @@ -1,11 +1,12 @@ namespace Kata.Verification { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Random; + import Std.Convert.*; + import KatasUtils.*; + import Std.Random.*; operation ApplyMarkingOracleAsPhaseOracle_Reference( markingOracle : ((Qubit[], Qubit) => Unit is Adj + Ctl), - qubits : Qubit[]) : Unit is Adj + Ctl { + qubits : Qubit[] + ) : Unit is Adj + Ctl { use minus = Qubit(); within { @@ -18,8 +19,8 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { - for N in 1 .. 3 { - for k in 0 .. 2^N - 1 { + for N in 1..3 { + for k in 0..2^N - 1 { let pattern = IntAsBoolArray(k, N); let marking = ApplyControlledOnBitString(pattern, X, _, _); let sol = Kata.ApplyMarkingOracleAsPhaseOracle(marking, _); diff --git a/katas/content/oracles/marking_oracle_seven/Verification.qs b/katas/content/oracles/marking_oracle_seven/Verification.qs index 7343ec0516..0914744040 100644 --- a/katas/content/oracles/marking_oracle_seven/Verification.qs +++ b/katas/content/oracles/marking_oracle_seven/Verification.qs @@ -1,6 +1,6 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; + import KatasUtils.*; + import Std.Math.*; operation IsSeven_MarkingOracle_Reference(x : Qubit[], y : Qubit) : Unit is Adj + Ctl { Controlled X(x, y); @@ -8,7 +8,7 @@ namespace Kata.Verification { // ------------------------------------------------------ @EntryPoint() - operation CheckSolution () : Bool { + operation CheckSolution() : Bool { let N = 3; let sol = ApplyOracle(_, Kata.IsSeven_MarkingOracle); let ref = ApplyOracle(_, IsSeven_MarkingOracle_Reference); diff --git a/katas/content/oracles/meeting_oracle/Solution.qs b/katas/content/oracles/meeting_oracle/Solution.qs index 89e46e42e4..a430b8408d 100644 --- a/katas/content/oracles/meeting_oracle/Solution.qs +++ b/katas/content/oracles/meeting_oracle/Solution.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Arrays; + import Std.Arrays.*; operation Or_Oracle(x : Qubit[], y : Qubit) : Unit is Adj + Ctl { X(y); diff --git a/katas/content/oracles/meeting_oracle/Verification.qs b/katas/content/oracles/meeting_oracle/Verification.qs index a44b09bfe1..75b4953e9a 100644 --- a/katas/content/oracles/meeting_oracle/Verification.qs +++ b/katas/content/oracles/meeting_oracle/Verification.qs @@ -1,7 +1,7 @@ namespace Kata.Verification { - open Microsoft.Quantum.Arrays; - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Katas; + import Std.Arrays.*; + import Std.Convert.*; + import KatasUtils.*; operation Or_Oracle_Reference(x : Qubit[], y : Qubit) : Unit is Adj + Ctl { X(y); @@ -23,8 +23,8 @@ namespace Kata.Verification { } operation ApplyMeetingOracle(qs : Qubit[], oracle : (Qubit[], Qubit[], Qubit) => Unit is Adj + Ctl) : Unit is Adj + Ctl { - let x = qs[0 .. 4]; - let jasmine = qs[5 .. 9]; + let x = qs[0..4]; + let jasmine = qs[5..9]; let target = qs[10]; oracle(x, jasmine, target); } diff --git a/katas/content/oracles/or_but_kth_oracle/Verification.qs b/katas/content/oracles/or_but_kth_oracle/Verification.qs index b9f8eea1a8..4f18482eed 100644 --- a/katas/content/oracles/or_but_kth_oracle/Verification.qs +++ b/katas/content/oracles/or_but_kth_oracle/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; operation Or_Oracle_Reference(x : Qubit[], y : Qubit) : Unit is Adj + Ctl { X(y); @@ -12,14 +12,14 @@ namespace Kata.Verification { X(minus); H(minus); } apply { - Or_Oracle_Reference(x[...k-1] + x[k+1...], minus); + Or_Oracle_Reference(x[...k-1] + x[k + 1...], minus); } } @EntryPoint() operation CheckSolution() : Bool { - for N in 2 .. 4 { - for k in 0 .. N - 1 { + for N in 2..4 { + for k in 0..N - 1 { let sol = Kata.OrOfBitsExceptKth_Oracle(_, k); let ref = OrOfBitsExceptKth_Oracle_Reference(_, k); let isCorrect = CheckOperationsAreEqualStrict(N, sol, ref); diff --git a/katas/content/oracles/or_oracle/Verification.qs b/katas/content/oracles/or_oracle/Verification.qs index 6ab374b2db..4665d8982f 100644 --- a/katas/content/oracles/or_oracle/Verification.qs +++ b/katas/content/oracles/or_oracle/Verification.qs @@ -1,6 +1,6 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Random; + import KatasUtils.*; + import Std.Random.*; operation Or_Oracle_Reference(x : Qubit[], y : Qubit) : Unit is Adj + Ctl { X(y); @@ -9,7 +9,7 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { - for N in 1 .. 3 { + for N in 1..3 { let sol = ApplyOracle(_, Kata.Or_Oracle); let ref = ApplyOracle(_, Or_Oracle_Reference); let isCorrect = CheckOperationsAreEqualStrict(N + 1, sol, ref); diff --git a/katas/content/oracles/phase_oracle_seven/Solution.qs b/katas/content/oracles/phase_oracle_seven/Solution.qs index 32b9110b93..866880b934 100644 --- a/katas/content/oracles/phase_oracle_seven/Solution.qs +++ b/katas/content/oracles/phase_oracle_seven/Solution.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Arrays; + import Std.Arrays.*; operation IsSeven_PhaseOracle(x : Qubit[]) : Unit is Adj + Ctl { Controlled Z(Most(x), Tail(x)); diff --git a/katas/content/oracles/phase_oracle_seven/Verification.qs b/katas/content/oracles/phase_oracle_seven/Verification.qs index 22b06dede4..50ea6e7a30 100644 --- a/katas/content/oracles/phase_oracle_seven/Verification.qs +++ b/katas/content/oracles/phase_oracle_seven/Verification.qs @@ -1,7 +1,7 @@ namespace Kata.Verification { - open Microsoft.Quantum.Arrays; - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; + import Std.Arrays.*; + import KatasUtils.*; + import Std.Math.*; operation IsSeven_PhaseOracle_Reference(x : Qubit[]) : Unit is Adj + Ctl { Controlled Z(Most(x), Tail(x)); @@ -13,7 +13,8 @@ namespace Kata.Verification { let isCorrect = CheckOperationsAreEqualStrict( 3, Kata.IsSeven_PhaseOracle, - IsSeven_PhaseOracle_Reference); + IsSeven_PhaseOracle_Reference + ); if isCorrect { Message("Correct!"); } else { diff --git a/katas/content/phase_estimation/eigenvalues_s/Placeholder.qs b/katas/content/phase_estimation/eigenvalues_s/Placeholder.qs index 1e7b39963d..a347a4cfa6 100644 --- a/katas/content/phase_estimation/eigenvalues_s/Placeholder.qs +++ b/katas/content/phase_estimation/eigenvalues_s/Placeholder.qs @@ -1,9 +1,11 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; function EigenvaluesS() : Complex[] { // Replace the return value with correct answer. - return [Complex(0.0, 0.0), - Complex(0.0, 0.0)]; + return [ + Complex(0.0, 0.0), + Complex(0.0, 0.0) + ]; } } diff --git a/katas/content/phase_estimation/eigenvalues_s/Solution.qs b/katas/content/phase_estimation/eigenvalues_s/Solution.qs index 3399fb6dcf..461e7013f2 100644 --- a/katas/content/phase_estimation/eigenvalues_s/Solution.qs +++ b/katas/content/phase_estimation/eigenvalues_s/Solution.qs @@ -1,8 +1,10 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; function EigenvaluesS() : Complex[] { - return [Complex(1.0, 0.0), - Complex(0.0, 1.0)]; + return [ + Complex(1.0, 0.0), + Complex(0.0, 1.0) + ]; } } diff --git a/katas/content/phase_estimation/eigenvalues_s/Verification.qs b/katas/content/phase_estimation/eigenvalues_s/Verification.qs index e08fff40b7..d16dcf6826 100644 --- a/katas/content/phase_estimation/eigenvalues_s/Verification.qs +++ b/katas/content/phase_estimation/eigenvalues_s/Verification.qs @@ -1,7 +1,7 @@ namespace Kata.Verification { - open Microsoft.Quantum.Math; + import Std.Math.*; - function ComplexEqual(x : Complex, y : Complex) : Bool { + function ComplexEqual(x : Complex, y : Complex) : Bool { // Tests two complex numbers for equality. AbsD(x::Real - y::Real) <= 0.001 and AbsD(x::Imag - y::Imag) <= 0.001 } @@ -15,7 +15,7 @@ namespace Kata.Verification { Message("The array of eigenvalues should have exactly two elements."); return false; } - if ComplexEqual(actual[0], expected[0]) and ComplexEqual(actual[1], expected[1]) or + if ComplexEqual(actual[0], expected[0]) and ComplexEqual(actual[1], expected[1]) or ComplexEqual(actual[0], expected[1]) and ComplexEqual(actual[1], expected[0]) { Message("Correct!"); return true; diff --git a/katas/content/phase_estimation/eigenvectors_x/Placeholder.qs b/katas/content/phase_estimation/eigenvectors_x/Placeholder.qs index cd5e6e99c3..280cfa423d 100644 --- a/katas/content/phase_estimation/eigenvectors_x/Placeholder.qs +++ b/katas/content/phase_estimation/eigenvectors_x/Placeholder.qs @@ -1,9 +1,11 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; function EigenvectorsX() : Double[][] { // Replace the return value with correct answer. - return [[0.0, 0.0], - [0.0, 0.0]]; + return [ + [0.0, 0.0], + [0.0, 0.0] + ]; } } diff --git a/katas/content/phase_estimation/eigenvectors_x/Solution.qs b/katas/content/phase_estimation/eigenvectors_x/Solution.qs index 501fe55795..efa45b8e06 100644 --- a/katas/content/phase_estimation/eigenvectors_x/Solution.qs +++ b/katas/content/phase_estimation/eigenvectors_x/Solution.qs @@ -1,8 +1,10 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; function EigenvectorsX() : Double[][] { - return [[1.0, 1.0], - [1.0, -1.0]]; + return [ + [1.0, 1.0], + [1.0, -1.0] + ]; } } diff --git a/katas/content/phase_estimation/eigenvectors_x/Verification.qs b/katas/content/phase_estimation/eigenvectors_x/Verification.qs index edc7499fb3..ffe2a6a349 100644 --- a/katas/content/phase_estimation/eigenvectors_x/Verification.qs +++ b/katas/content/phase_estimation/eigenvectors_x/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Math; + import Std.Math.*; @EntryPoint() operation CheckSolution() : Bool { @@ -8,7 +8,7 @@ namespace Kata.Verification { Message("The array of eigenvectors should have exactly two elements."); return false; } - for i in 0 .. 1 { + for i in 0..1 { if Length(actual[i]) != 2 { Message("Each eigenvector should have exactly two elements."); return false; @@ -20,11 +20,11 @@ namespace Kata.Verification { } // One eigenvector has to have equal components, the other one - opposite ones - if AbsD(actual[0][0] - actual[0][1]) < 1e-9 and AbsD(actual[1][0] + actual[1][1]) < 1e-9 or + if AbsD(actual[0][0] - actual[0][1]) < 1e-9 and AbsD(actual[1][0] + actual[1][1]) < 1e-9 or AbsD(actual[0][0] + actual[0][1]) < 1e-9 and AbsD(actual[1][0] - actual[1][1]) < 1e-9 { - Message("Correct!"); - return true; - } + Message("Correct!"); + return true; + } Message("Incorrect value for one of the eigenvectors."); return false; diff --git a/katas/content/phase_estimation/examples/QuantumPhaseEstimationDemo.qs b/katas/content/phase_estimation/examples/QuantumPhaseEstimationDemo.qs index 209d408532..3d2c971a3a 100644 --- a/katas/content/phase_estimation/examples/QuantumPhaseEstimationDemo.qs +++ b/katas/content/phase_estimation/examples/QuantumPhaseEstimationDemo.qs @@ -1,7 +1,7 @@ namespace Kata { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Math; + import Std.Convert.*; + import Std.Diagnostics.*; + import Std.Math.*; @EntryPoint() operation QuantumPhaseEstimationDemo() : Unit { @@ -16,30 +16,30 @@ namespace Kata { let U = R1Frac(1, 3, _); let P = X; // |1⟩ basis state is convenient to experiment with R1 and R1Frac gates let n = 3; - mutable counts = [0, size = 2 ^ n]; - for _ in 1 .. 100 { + mutable counts = [0, size = 2^n]; + for _ in 1..100 { let res = PhaseEstimation(U, P, n); set counts w/= res <- counts[res] + 1; } - for i in 0 .. 2 ^ n - 1 { + for i in 0..2^n - 1 { if counts[i] > 0 { - Message($"Eigenphase {IntAsDouble(i) / IntAsDouble(2 ^ n)} - {counts[i]}%"); + Message($"Eigenphase {IntAsDouble(i) / IntAsDouble(2^n)} - {counts[i]}%"); } } } operation PhaseEstimation( - U : Qubit => Unit is Ctl, + U : Qubit => Unit is Ctl, P : Qubit => Unit, n : Int ) : Int { use (phaseRegister, eigenstate) = (Qubit[n], Qubit()); P(eigenstate); ApplyToEach(H, phaseRegister); - for k in 0 .. n - 1 { - for _ in 1 .. 1 <<< k { + for k in 0..n - 1 { + for _ in 1..1 <<< k { Controlled U([phaseRegister[k]], eigenstate); - } + } } SwapReverseRegister(phaseRegister); Adjoint ApplyQFT(phaseRegister); @@ -47,4 +47,4 @@ namespace Kata { Reset(eigenstate); return MeasureInteger(phaseRegister); } -} \ No newline at end of file +} diff --git a/katas/content/phase_estimation/implement_qpe/Verification.qs b/katas/content/phase_estimation/implement_qpe/Verification.qs index 9cab1261d8..f6fe6383a3 100644 --- a/katas/content/phase_estimation/implement_qpe/Verification.qs +++ b/katas/content/phase_estimation/implement_qpe/Verification.qs @@ -1,15 +1,15 @@ namespace Kata.Verification { - open Microsoft.Quantum.Unstable.StatePreparation; + import Std.StatePreparation.*; @EntryPoint() operation CheckSolution() : Bool { let tests = [ - (Z, I, 1, 0, "Z, |0⟩"), - (Z, X, 1, 1, "Z, |1⟩"), - (X, H, 1, 0, "X, |+⟩"), + (Z, I, 1, 0, "Z, |0⟩"), + (Z, X, 1, 1, "Z, |1⟩"), + (X, H, 1, 0, "X, |+⟩"), (X, q => PreparePureStateD([1., -1.], [q]), 1, 1, "X, |-⟩"), - (S, I, 2, 0, "S, |0⟩"), - (S, X, 2, 1, "S, |1⟩"), + (S, I, 2, 0, "S, |0⟩"), + (S, X, 2, 1, "S, |1⟩"), (Z, X, 2, 2, "Z, |1⟩"), // Higher precision than necessary (T, I, 3, 0, "T, |0⟩"), (T, X, 3, 1, "T, |1⟩"), @@ -17,7 +17,8 @@ namespace Kata.Verification { (Z, X, 3, 4, "Z, |1⟩"), // Higher precision than necessary ]; for (U, P, n, expected, msg) in tests { - for _ in 1 .. 10 { // Repeat several times to catch probabilistic failures + for _ in 1..10 { + // Repeat several times to catch probabilistic failures let actual = Kata.PhaseEstimation(U, P, n); if actual != expected { Message($"Incorrect eigenphase for (U, |ψ⟩, n) = ({msg}, {n}): expected {expected}, got {actual}"); @@ -25,7 +26,7 @@ namespace Kata.Verification { } } } - + Message("Correct!"); return true; } diff --git a/katas/content/phase_estimation/one_bit_eigenphase/Verification.qs b/katas/content/phase_estimation/one_bit_eigenphase/Verification.qs index c741e17323..b6ed00dbef 100644 --- a/katas/content/phase_estimation/one_bit_eigenphase/Verification.qs +++ b/katas/content/phase_estimation/one_bit_eigenphase/Verification.qs @@ -1,14 +1,15 @@ namespace Kata.Verification { - open Microsoft.Quantum.Unstable.StatePreparation; + import Std.StatePreparation.*; @EntryPoint() operation CheckSolution() : Bool { let eigenvectors = [ - (Z, I, 1, "Z, |0⟩"), - (Z, X, -1, "Z, |1⟩"), - (S, I, 1, "S, |0⟩"), - (X, H, 1, "X, |+⟩"), - (X, q => PreparePureStateD([1., -1.], [q]), -1, "X, |-⟩")]; + (Z, I, 1, "Z, |0⟩"), + (Z, X, -1, "Z, |1⟩"), + (S, I, 1, "S, |0⟩"), + (X, H, 1, "X, |+⟩"), + (X, q => PreparePureStateD([1., -1.], [q]), -1, "X, |-⟩") + ]; for (U, P, expected, msg) in eigenvectors { let actual = Kata.OneBitPhaseEstimation(U, P); if actual != expected { @@ -16,7 +17,7 @@ namespace Kata.Verification { return false; } } - + Message("Correct!"); return true; } diff --git a/katas/content/phase_estimation/state_eigenvector/Solution.qs b/katas/content/phase_estimation/state_eigenvector/Solution.qs index e1ffe8d0e9..f1d614c302 100644 --- a/katas/content/phase_estimation/state_eigenvector/Solution.qs +++ b/katas/content/phase_estimation/state_eigenvector/Solution.qs @@ -1,5 +1,5 @@ namespace Kata { - import Microsoft.Quantum.Diagnostics.CheckZero; + import Std.Diagnostics.CheckZero; operation IsEigenvector(U : Qubit => Unit, P : Qubit => Unit is Adj) : Bool { use q = Qubit(); P(q); diff --git a/katas/content/phase_estimation/state_eigenvector/Verification.qs b/katas/content/phase_estimation/state_eigenvector/Verification.qs index 46140f03c3..c689505226 100644 --- a/katas/content/phase_estimation/state_eigenvector/Verification.qs +++ b/katas/content/phase_estimation/state_eigenvector/Verification.qs @@ -1,15 +1,16 @@ namespace Kata.Verification { - open Microsoft.Quantum.Unstable.StatePreparation; + import Std.StatePreparation.*; @EntryPoint() operation CheckSolution() : Bool { let eigenvectors = [ - (Z, I, "Z, |0⟩"), - (Z, X, "Z, |1⟩"), - (S, I, "S, |0⟩"), - (S, X, "S, |1⟩"), - (X, H, "X, |+⟩"), - (X, q => PreparePureStateD([1., -1.], [q]), "X, |-⟩")]; + (Z, I, "Z, |0⟩"), + (Z, X, "Z, |1⟩"), + (S, I, "S, |0⟩"), + (S, X, "S, |1⟩"), + (X, H, "X, |+⟩"), + (X, q => PreparePureStateD([1., -1.], [q]), "X, |-⟩") + ]; for (U, P, msg) in eigenvectors { if not Kata.IsEigenvector(U, P) { Message($"Incorrect for (U, P) = ({msg}): expected true"); @@ -18,18 +19,19 @@ namespace Kata.Verification { } let notEigenvectors = [ - (Z, H, "Z, |+⟩"), - (X, X, "X, |1⟩"), - (X, Z, "X, |0⟩"), - (Y, H, "Y, |+⟩"), - (Y, X, "Y, |1⟩")]; + (Z, H, "Z, |+⟩"), + (X, X, "X, |1⟩"), + (X, Z, "X, |0⟩"), + (Y, H, "Y, |+⟩"), + (Y, X, "Y, |1⟩") + ]; for (U, P, msg) in notEigenvectors { if Kata.IsEigenvector(U, P) { Message($"Incorrect for (U, |ψ⟩) = ({msg}): expected false"); return false; } } - + Message("Correct!"); return true; } diff --git a/katas/content/preparing_states/all_basis_vectors/Verification.qs b/katas/content/preparing_states/all_basis_vectors/Verification.qs index 39a08bf98f..7867342356 100644 --- a/katas/content/preparing_states/all_basis_vectors/Verification.qs +++ b/katas/content/preparing_states/all_basis_vectors/Verification.qs @@ -1,7 +1,7 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; - operation AllBasisVectorsSuperposition_Reference (qs : Qubit[]) : Unit is Adj + Ctl { + operation AllBasisVectorsSuperposition_Reference(qs : Qubit[]) : Unit is Adj + Ctl { for q in qs { H(q); } @@ -9,12 +9,13 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { - for i in 1 .. 5 { + for i in 1..5 { Message($"Testing {i} qubit(s)..."); if not CheckOperationsEquivalenceOnZeroStateWithFeedback( Kata.AllBasisVectorsSuperposition, AllBasisVectorsSuperposition_Reference, - i) { + i + ) { return false; } } diff --git a/katas/content/preparing_states/all_bell_states/SolutionB.qs b/katas/content/preparing_states/all_bell_states/SolutionB.qs index 4b17c4f164..891d5a058c 100644 --- a/katas/content/preparing_states/all_bell_states/SolutionB.qs +++ b/katas/content/preparing_states/all_bell_states/SolutionB.qs @@ -1,9 +1,9 @@ namespace Kata { - open Microsoft.Quantum.Convert; + import Std.Convert.*; - operation AllBellStates (qs : Qubit[], index : Int) : Unit is Adj + Ctl { + operation AllBellStates(qs : Qubit[], index : Int) : Unit is Adj + Ctl { let bitmask = IntAsBoolArray(index, 2); - + if bitmask[0] { X(qs[0]); } diff --git a/katas/content/preparing_states/all_bell_states/Verification.qs b/katas/content/preparing_states/all_bell_states/Verification.qs index a17c83f211..d5b823b3b9 100644 --- a/katas/content/preparing_states/all_bell_states/Verification.qs +++ b/katas/content/preparing_states/all_bell_states/Verification.qs @@ -1,9 +1,9 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; - operation AllBellStates_Reference (qs : Qubit[], index : Int) : Unit is Adj + Ctl { + operation AllBellStates_Reference(qs : Qubit[], index : Int) : Unit is Adj + Ctl { H(qs[0]); - + if index == 1 { Z(qs[0]); } @@ -14,18 +14,19 @@ namespace Kata.Verification { Z(qs[0]); X(qs[1]); } - + CNOT(qs[0], qs[1]); } @EntryPoint() operation CheckSolution() : Bool { - for index in 0 .. 3 { - Message($"Testing index = {index}..."); + for index in 0..3 { + Message($"Testing index = {index}..."); if not CheckOperationsEquivalenceOnZeroStateWithFeedback( Kata.AllBellStates(_, index), AllBellStates_Reference(_, index), - 2) { + 2 + ) { return false; } } diff --git a/katas/content/preparing_states/bell_state/Verification.qs b/katas/content/preparing_states/bell_state/Verification.qs index 0cdf6effb3..8b54721901 100644 --- a/katas/content/preparing_states/bell_state/Verification.qs +++ b/katas/content/preparing_states/bell_state/Verification.qs @@ -1,7 +1,7 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; - operation BellState_Reference (qs : Qubit[]) : Unit is Adj + Ctl { + operation BellState_Reference(qs : Qubit[]) : Unit is Adj + Ctl { H(qs[0]); CNOT(qs[0], qs[1]); } @@ -11,6 +11,7 @@ namespace Kata.Verification { CheckOperationsEquivalenceOnZeroStateWithFeedback( Kata.BellState, BellState_Reference, - 2) + 2 + ) } } diff --git a/katas/content/preparing_states/controlled_rotation/Verification.qs b/katas/content/preparing_states/controlled_rotation/Verification.qs index 37b90a5f94..81216f295f 100644 --- a/katas/content/preparing_states/controlled_rotation/Verification.qs +++ b/katas/content/preparing_states/controlled_rotation/Verification.qs @@ -1,9 +1,9 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; - operation ControlledRotation_Reference (qs : Qubit[]) : Unit is Adj + Ctl { + operation ControlledRotation_Reference(qs : Qubit[]) : Unit is Adj + Ctl { H(qs[0]); - Controlled H ([qs[0]], qs[1]); + Controlled H([qs[0]], qs[1]); } @EntryPoint() @@ -11,6 +11,7 @@ namespace Kata.Verification { CheckOperationsEquivalenceOnZeroStateWithFeedback( Kata.ControlledRotation, ControlledRotation_Reference, - 2) + 2 + ) } } diff --git a/katas/content/preparing_states/even_odd/Verification.qs b/katas/content/preparing_states/even_odd/Verification.qs index d10457bcbf..2b2cffb083 100644 --- a/katas/content/preparing_states/even_odd/Verification.qs +++ b/katas/content/preparing_states/even_odd/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; operation EvenOddNumbersSuperposition_Reference(qs : Qubit[], isEven : Bool) : Unit is Adj + Ctl { let N = Length(qs); @@ -15,13 +15,14 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { - for i in 1 .. 5 { + for i in 1..5 { for boolVal in [false, true] { Message($"Testing {i} qubit(s) where isEven = {boolVal}..."); if not CheckOperationsEquivalenceOnZeroStateWithFeedback( Kata.EvenOddNumbersSuperposition(_, boolVal), EvenOddNumbersSuperposition_Reference(_, boolVal), - i) { + i + ) { return false; } } diff --git a/katas/content/preparing_states/even_sup_two_qubits/Verification.qs b/katas/content/preparing_states/even_sup_two_qubits/Verification.qs index 2ad8b97208..4c0de333db 100644 --- a/katas/content/preparing_states/even_sup_two_qubits/Verification.qs +++ b/katas/content/preparing_states/even_sup_two_qubits/Verification.qs @@ -1,7 +1,7 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; - operation AllBasisVectors_TwoQubits_Reference (qs : Qubit[]) : Unit is Adj + Ctl { + operation AllBasisVectors_TwoQubits_Reference(qs : Qubit[]) : Unit is Adj + Ctl { H(qs[0]); H(qs[1]); } @@ -11,6 +11,7 @@ namespace Kata.Verification { CheckOperationsEquivalenceOnZeroStateWithFeedback( Kata.AllBasisVectors_TwoQubits, AllBasisVectors_TwoQubits_Reference, - 2) + 2 + ) } } diff --git a/katas/content/preparing_states/even_sup_two_qubits_complex_phases/Verification.qs b/katas/content/preparing_states/even_sup_two_qubits_complex_phases/Verification.qs index 8f1780db57..deaf78eade 100644 --- a/katas/content/preparing_states/even_sup_two_qubits_complex_phases/Verification.qs +++ b/katas/content/preparing_states/even_sup_two_qubits_complex_phases/Verification.qs @@ -1,7 +1,7 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; - operation AllBasisVectorsWithComplexPhases_TwoQubits_Reference (qs : Qubit[]) : Unit is Adj + Ctl { + operation AllBasisVectorsWithComplexPhases_TwoQubits_Reference(qs : Qubit[]) : Unit is Adj + Ctl { // Qubit 0 is taken into |+⟩ and then z-rotated into |-⟩. H(qs[0]); Z(qs[0]); @@ -16,6 +16,7 @@ namespace Kata.Verification { CheckOperationsEquivalenceOnZeroStateWithFeedback( Kata.AllBasisVectorsWithComplexPhases_TwoQubits, AllBasisVectorsWithComplexPhases_TwoQubits_Reference, - 2) + 2 + ) } } diff --git a/katas/content/preparing_states/even_sup_two_qubits_phase_flip/Verification.qs b/katas/content/preparing_states/even_sup_two_qubits_phase_flip/Verification.qs index fbca152e95..b52efb50b4 100644 --- a/katas/content/preparing_states/even_sup_two_qubits_phase_flip/Verification.qs +++ b/katas/content/preparing_states/even_sup_two_qubits_phase_flip/Verification.qs @@ -1,7 +1,7 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; - operation AllBasisVectorsWithPhaseFlip_TwoQubits_Reference (qs : Qubit[]) : Unit is Adj + Ctl { + operation AllBasisVectorsWithPhaseFlip_TwoQubits_Reference(qs : Qubit[]) : Unit is Adj + Ctl { H(qs[0]); H(qs[1]); CZ(qs[0], qs[1]); @@ -12,6 +12,7 @@ namespace Kata.Verification { CheckOperationsEquivalenceOnZeroStateWithFeedback( Kata.AllBasisVectorsWithPhaseFlip_TwoQubits, AllBasisVectorsWithPhaseFlip_TwoQubits_Reference, - 2) + 2 + ) } } diff --git a/katas/content/preparing_states/four_bitstrings/SolutionB.qs b/katas/content/preparing_states/four_bitstrings/SolutionB.qs index 10c62a3a0f..05b9e82708 100644 --- a/katas/content/preparing_states/four_bitstrings/SolutionB.qs +++ b/katas/content/preparing_states/four_bitstrings/SolutionB.qs @@ -1,12 +1,12 @@ namespace Kata { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Math; + import Std.Convert.*; + import Std.Math.*; - operation FourBitstringSuperposition (qs : Qubit[], bits : Bool[][]) : Unit { + operation FourBitstringSuperposition(qs : Qubit[], bits : Bool[][]) : Unit { FourBitstringSuperposition_Recursive([], qs, bits); } - operation FourBitstringSuperposition_Recursive (currentBitString : Bool[], qs : Qubit[], bits : Bool[][]) : Unit { + operation FourBitstringSuperposition_Recursive(currentBitString : Bool[], qs : Qubit[], bits : Bool[][]) : Unit { // an array of bit strings whose columns we are considering begin with |0⟩ mutable zeroLeads = []; // an array of bit strings whose columns we are considering begin with |1⟩ @@ -18,7 +18,7 @@ namespace Kata { if rows >= 1 and currentIndex < Length(qs) { // figure out what percentage of the bits should be |0⟩ - for row in 0 .. rows - 1 { + for row in 0..rows - 1 { if bits[row][currentIndex] { set oneLeads = oneLeads + [bits[row]]; } else { @@ -29,8 +29,12 @@ namespace Kata { // for the first path through, when the bit string has zero length, // the Controlled version of the rotation will perform a regular rotation let theta = ArcCos(Sqrt(IntAsDouble(Length(zeroLeads)) / IntAsDouble(rows))); - ApplyControlledOnBitString(currentBitString, Ry, qs[0 .. currentIndex - 1], - (2.0 * theta, qs[currentIndex])); + ApplyControlledOnBitString( + currentBitString, + Ry, + qs[0..currentIndex - 1], + (2.0 * theta, qs[currentIndex]) + ); // call state preparation recursively based on the bit strings so far FourBitstringSuperposition_Recursive(currentBitString + [false], qs, zeroLeads); diff --git a/katas/content/preparing_states/four_bitstrings/Verification.qs b/katas/content/preparing_states/four_bitstrings/Verification.qs index 3adcf6100e..9159b7c534 100644 --- a/katas/content/preparing_states/four_bitstrings/Verification.qs +++ b/katas/content/preparing_states/four_bitstrings/Verification.qs @@ -1,22 +1,22 @@ namespace Kata.Verification { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; - open Microsoft.Quantum.Random; + import Std.Convert.*; + import KatasUtils.*; + import Std.Math.*; + import Std.Random.*; - operation FourBitstringSuperposition_Reference (qs : Qubit[], bits : Bool[][]) : Unit is Adj { + operation FourBitstringSuperposition_Reference(qs : Qubit[], bits : Bool[][]) : Unit is Adj { use anc = Qubit[2]; ApplyToEachA(H, anc); - for i in 0 .. 3 { - for j in 0 .. Length(qs) - 1 { + for i in 0..3 { + for j in 0..Length(qs) - 1 { if bits[i][j] { ApplyControlledOnInt(i, X, anc, qs[j]); } } } - for i in 0 .. 3 { + for i in 0..3 { if i % 2 == 1 { ApplyControlledOnBitString(bits[i], X, qs, anc[0]); } diff --git a/katas/content/preparing_states/greenberger_horne_zeilinger/Placeholder.qs b/katas/content/preparing_states/greenberger_horne_zeilinger/Placeholder.qs index 0e7ca59327..7144edcd73 100644 --- a/katas/content/preparing_states/greenberger_horne_zeilinger/Placeholder.qs +++ b/katas/content/preparing_states/greenberger_horne_zeilinger/Placeholder.qs @@ -1,7 +1,7 @@ namespace Kata { - open Microsoft.Quantum.Arrays; + import Std.Arrays.*; - operation GHZ_State (qs : Qubit[]) : Unit is Adj + Ctl { + operation GHZ_State(qs : Qubit[]) : Unit is Adj + Ctl { // Implement your solution here... } diff --git a/katas/content/preparing_states/greenberger_horne_zeilinger/Solution.qs b/katas/content/preparing_states/greenberger_horne_zeilinger/Solution.qs index 712522c791..41a6507a4b 100644 --- a/katas/content/preparing_states/greenberger_horne_zeilinger/Solution.qs +++ b/katas/content/preparing_states/greenberger_horne_zeilinger/Solution.qs @@ -1,9 +1,9 @@ namespace Kata { - open Microsoft.Quantum.Arrays; - - operation GHZ_State (qs : Qubit[]) : Unit is Adj + Ctl { + import Std.Arrays.*; + + operation GHZ_State(qs : Qubit[]) : Unit is Adj + Ctl { H(qs[0]); - + // Library function Rest returns all array elements except for the first one for q in Rest(qs) { CNOT(qs[0], q); diff --git a/katas/content/preparing_states/greenberger_horne_zeilinger/Verification.qs b/katas/content/preparing_states/greenberger_horne_zeilinger/Verification.qs index 18f741e9c1..1b99e1b6be 100644 --- a/katas/content/preparing_states/greenberger_horne_zeilinger/Verification.qs +++ b/katas/content/preparing_states/greenberger_horne_zeilinger/Verification.qs @@ -1,10 +1,10 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Arrays; + import KatasUtils.*; + import Std.Arrays.*; - operation GHZ_State_Reference (qs : Qubit[]) : Unit is Adj + Ctl { + operation GHZ_State_Reference(qs : Qubit[]) : Unit is Adj + Ctl { H(qs[0]); - + for q in Rest(qs) { CNOT(qs[0], q); } @@ -12,12 +12,13 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { - for i in 1 .. 5 { + for i in 1..5 { Message($"Testing {i} qubit(s)..."); if not CheckOperationsEquivalenceOnZeroStateWithFeedback( Kata.GHZ_State, GHZ_State_Reference, - i) { + i + ) { return false; } } diff --git a/katas/content/preparing_states/hardy_state/Solution.qs b/katas/content/preparing_states/hardy_state/Solution.qs index 207e9ee96e..4daf5d2712 100644 --- a/katas/content/preparing_states/hardy_state/Solution.qs +++ b/katas/content/preparing_states/hardy_state/Solution.qs @@ -1,8 +1,8 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; - operation Hardy_State (qs : Qubit[]) : Unit is Adj { - let theta = ArcCos(Sqrt(10.0/12.0)); + operation Hardy_State(qs : Qubit[]) : Unit is Adj { + let theta = ArcCos(Sqrt(10.0 / 12.0)); Ry(2.0 * theta, qs[0]); ApplyControlledOnInt(0, Ry, [qs[0]], (2.0 * ArcCos(3.0 / Sqrt(10.0)), qs[1])); diff --git a/katas/content/preparing_states/hardy_state/Verification.qs b/katas/content/preparing_states/hardy_state/Verification.qs index 0f057d597d..fbb7ad8bf9 100644 --- a/katas/content/preparing_states/hardy_state/Verification.qs +++ b/katas/content/preparing_states/hardy_state/Verification.qs @@ -1,9 +1,9 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; + import KatasUtils.*; + import Std.Math.*; - operation Hardy_State_Reference (qs : Qubit[]) : Unit is Adj { - let theta = ArcCos(Sqrt(10.0/12.0)); + operation Hardy_State_Reference(qs : Qubit[]) : Unit is Adj { + let theta = ArcCos(Sqrt(10.0 / 12.0)); Ry(2.0 * theta, qs[0]); ApplyControlledOnInt(0, Ry, [qs[0]], (2.0 * ArcCos(3.0 / Sqrt(10.0)), qs[1])); ApplyControlledOnInt(1, Ry, [qs[0]], (2.0 * PI() / 4.0, qs[1])); diff --git a/katas/content/preparing_states/minus_state/Verification.qs b/katas/content/preparing_states/minus_state/Verification.qs index 2abaf2f32f..a938d5485b 100644 --- a/katas/content/preparing_states/minus_state/Verification.qs +++ b/katas/content/preparing_states/minus_state/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; operation MinusState_Reference(q : Qubit) : Unit is Adj + Ctl { H(q); @@ -9,8 +9,9 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { CheckOperationsEquivalenceOnZeroStateWithFeedback( - ApplyToFirstCA(Kata.MinusState, _), + ApplyToFirstCA(Kata.MinusState, _), ApplyToFirstCA(MinusState_Reference, _), - 1) + 1 + ) } } diff --git a/katas/content/preparing_states/minus_state/solution.md b/katas/content/preparing_states/minus_state/solution.md index 4c670e1567..a1dd3f663d 100644 --- a/katas/content/preparing_states/minus_state/solution.md +++ b/katas/content/preparing_states/minus_state/solution.md @@ -5,7 +5,7 @@ Fortunately, there is another operation you can use to change the state $\ket{0} $$X = \begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}$$ This gate transforms $\ket{0} \longmapsto \ket{1}$ and $\ket{1} \longmapsto \ket{0}$. -$X$ is another one of the built-in gates in Q# from the `Microsoft.Quantum.Intrinsic` namespace. +$X$ is another one of the built-in gates in Q# from the `Std.Intrinsic` namespace. Thus, your solution should apply the $X$ gate to your qubit, followed by the Hadamard gate. diff --git a/katas/content/preparing_states/parity_bitstrings/Verification.qs b/katas/content/preparing_states/parity_bitstrings/Verification.qs index 4c5f406f67..47dd4a46b8 100644 --- a/katas/content/preparing_states/parity_bitstrings/Verification.qs +++ b/katas/content/preparing_states/parity_bitstrings/Verification.qs @@ -1,23 +1,23 @@ namespace Kata.Verification { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Katas; + import Std.Convert.*; + import KatasUtils.*; - operation AllStatesWithParitySuperposition_Reference (qs : Qubit[], parity : Int) : Unit is Adj + Ctl { + operation AllStatesWithParitySuperposition_Reference(qs : Qubit[], parity : Int) : Unit is Adj + Ctl { if Length(qs) == 1 { if parity == 1 { X(qs[0]); } } else { H(qs[0]); - ApplyControlledOnInt(0, AllStatesWithParitySuperposition_Reference, qs[0 .. 0], (qs[1 ...], parity)); - ApplyControlledOnInt(1, AllStatesWithParitySuperposition_Reference, qs[0 .. 0], (qs[1 ...], 1 - parity)); + ApplyControlledOnInt(0, AllStatesWithParitySuperposition_Reference, qs[0..0], (qs[1...], parity)); + ApplyControlledOnInt(1, AllStatesWithParitySuperposition_Reference, qs[0..0], (qs[1...], 1 - parity)); } } @EntryPoint() operation CheckSolution() : Bool { - for N in 2 .. 5 { - for parity in 0 .. 1 { + for N in 2..5 { + for parity in 0..1 { Message($"Testing for N = {N}, with parity: {parity}..."); if not CheckOperationsEquivalenceOnZeroStateWithFeedback( Kata.AllStatesWithParitySuperposition(_, parity), diff --git a/katas/content/preparing_states/plus_state/Verification.qs b/katas/content/preparing_states/plus_state/Verification.qs index a3594287fc..66fd7fc1b2 100644 --- a/katas/content/preparing_states/plus_state/Verification.qs +++ b/katas/content/preparing_states/plus_state/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; operation PlusState_Reference(q : Qubit) : Unit is Adj + Ctl { H(q); @@ -8,8 +8,9 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { CheckOperationsEquivalenceOnZeroStateWithFeedback( - ApplyToFirstCA(Kata.PlusState, _), + ApplyToFirstCA(Kata.PlusState, _), ApplyToFirstCA(PlusState_Reference, _), - 1) + 1 + ) } } diff --git a/katas/content/preparing_states/plus_state/solution.md b/katas/content/preparing_states/plus_state/solution.md index 48e738076f..19dc225664 100644 --- a/katas/content/preparing_states/plus_state/solution.md +++ b/katas/content/preparing_states/plus_state/solution.md @@ -4,8 +4,8 @@ $$H = \frac{1}{\sqrt2} \begin{bmatrix} 1 & 1 \\ 1 & -1 \end{bmatrix}$$ This gate converts $\ket{0}$ into $\ket{+} = \frac{1}{\sqrt{2}} \big(\ket{0} + \ket{1}\big)$ and $\ket{1}$ into $\ket{−} = \frac{1}{\sqrt{2}} \big(\ket{0} - \ket{1}\big)$. The first of these transformations is exactly the one you're looking for! -Hadamard gate is one of the built-in gates in Q#, available in the `Microsoft.Quantum.Intrinsic` namespace. -It's open in any Q# source files by default, so you can use it right away. +Hadamard gate is one of the built-in gates in Q#, available in the `Std.Intrinsic` namespace. +It's imported in any Q# source files by default, so you can use it right away. @[solution]({ "id": "preparing_states__plus_state_solution", diff --git a/katas/content/preparing_states/three_states_two_qubits/SolutionB.qs b/katas/content/preparing_states/three_states_two_qubits/SolutionB.qs index 07de3220eb..19d4107133 100644 --- a/katas/content/preparing_states/three_states_two_qubits/SolutionB.qs +++ b/katas/content/preparing_states/three_states_two_qubits/SolutionB.qs @@ -1,9 +1,9 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; - operation ThreeStates_TwoQubits (qs : Qubit[]) : Unit is Adj + Ctl { + operation ThreeStates_TwoQubits(qs : Qubit[]) : Unit is Adj + Ctl { let theta = ArcSin(1.0 / Sqrt(3.0)); Ry(2.0 * theta, qs[0]); - ApplyControlledOnInt(0, H,[qs[0]], qs[1]); + ApplyControlledOnInt(0, H, [qs[0]], qs[1]); } } diff --git a/katas/content/preparing_states/three_states_two_qubits/Verification.qs b/katas/content/preparing_states/three_states_two_qubits/Verification.qs index 7c6aae4d83..3e4e4aea94 100644 --- a/katas/content/preparing_states/three_states_two_qubits/Verification.qs +++ b/katas/content/preparing_states/three_states_two_qubits/Verification.qs @@ -1,12 +1,12 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; + import KatasUtils.*; + import Std.Math.*; // Reference solution that does not use measurements (to be adjointable) - operation ThreeStates_TwoQubits_Reference (qs : Qubit[]) : Unit is Adj + Ctl { + operation ThreeStates_TwoQubits_Reference(qs : Qubit[]) : Unit is Adj + Ctl { let theta = ArcSin(1.0 / Sqrt(3.0)); Ry(2.0 * theta, qs[0]); - ApplyControlledOnInt(0, H,[qs[0]], qs[1]); + ApplyControlledOnInt(0, H, [qs[0]], qs[1]); } @EntryPoint() @@ -14,6 +14,7 @@ namespace Kata.Verification { CheckOperationsEquivalenceOnZeroStateWithFeedback( Kata.ThreeStates_TwoQubits, ThreeStates_TwoQubits_Reference, - 2) + 2 + ) } } diff --git a/katas/content/preparing_states/three_states_two_qubits_phases/Placeholder.qs b/katas/content/preparing_states/three_states_two_qubits_phases/Placeholder.qs index a3d38f8f50..a1189f0aec 100644 --- a/katas/content/preparing_states/three_states_two_qubits_phases/Placeholder.qs +++ b/katas/content/preparing_states/three_states_two_qubits_phases/Placeholder.qs @@ -1,13 +1,13 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; - operation ThreeStates_TwoQubits_Phases (qs : Qubit[]) : Unit { + operation ThreeStates_TwoQubits_Phases(qs : Qubit[]) : Unit { // Implement your solution here... } // You might find this helper operation from an earlier task useful. - operation ThreeStates_TwoQubits (qs : Qubit[]) : Unit is Adj { + operation ThreeStates_TwoQubits(qs : Qubit[]) : Unit is Adj { let theta = ArcSin(1.0 / Sqrt(3.0)); Ry(2.0 * theta, qs[0]); ApplyControlledOnInt(0, H, [qs[0]], qs[1]); diff --git a/katas/content/preparing_states/three_states_two_qubits_phases/Solution.qs b/katas/content/preparing_states/three_states_two_qubits_phases/Solution.qs index df069e852b..bc9321d40a 100644 --- a/katas/content/preparing_states/three_states_two_qubits_phases/Solution.qs +++ b/katas/content/preparing_states/three_states_two_qubits_phases/Solution.qs @@ -1,7 +1,7 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; - operation ThreeStates_TwoQubits_Phases (qs : Qubit[]) : Unit { + operation ThreeStates_TwoQubits_Phases(qs : Qubit[]) : Unit { // First create (|00⟩ + |01⟩ + |10⟩) / sqrt(3) state ThreeStates_TwoQubits(qs); @@ -9,7 +9,7 @@ namespace Kata { R1(2.0 * PI() / 3.0, qs[1]); } - operation ThreeStates_TwoQubits (qs : Qubit[]) : Unit is Adj { + operation ThreeStates_TwoQubits(qs : Qubit[]) : Unit is Adj { let theta = ArcSin(1.0 / Sqrt(3.0)); Ry(2.0 * theta, qs[0]); ApplyControlledOnInt(0, H, [qs[0]], qs[1]); diff --git a/katas/content/preparing_states/three_states_two_qubits_phases/Verification.qs b/katas/content/preparing_states/three_states_two_qubits_phases/Verification.qs index e6b418a93c..5005beff0e 100644 --- a/katas/content/preparing_states/three_states_two_qubits_phases/Verification.qs +++ b/katas/content/preparing_states/three_states_two_qubits_phases/Verification.qs @@ -1,8 +1,8 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; + import KatasUtils.*; + import Std.Math.*; - operation ThreeStates_TwoQubits_Phases_Reference (qs : Qubit[]) : Unit is Adj { + operation ThreeStates_TwoQubits_Phases_Reference(qs : Qubit[]) : Unit is Adj { // First create (|00⟩ + |01⟩ + |10⟩) / sqrt(3) state ThreeStates_TwoQubits_Reference(qs); @@ -10,7 +10,7 @@ namespace Kata.Verification { R1(2.0 * PI() / 3.0, qs[1]); } - operation ThreeStates_TwoQubits_Reference (qs : Qubit[]) : Unit is Adj { + operation ThreeStates_TwoQubits_Reference(qs : Qubit[]) : Unit is Adj { let theta = ArcSin(1.0 / Sqrt(3.0)); Ry(2.0 * theta, qs[0]); ApplyControlledOnInt(0, H, [qs[0]], qs[1]); diff --git a/katas/content/preparing_states/two_bitstrings/Verification.qs b/katas/content/preparing_states/two_bitstrings/Verification.qs index d59842bccd..fc7b39af11 100644 --- a/katas/content/preparing_states/two_bitstrings/Verification.qs +++ b/katas/content/preparing_states/two_bitstrings/Verification.qs @@ -1,9 +1,9 @@ namespace Kata.Verification { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Katas; + import Std.Convert.*; + import KatasUtils.*; - function FindFirstDiff (bits1 : Bool[], bits2 : Bool[]) : Int { - for i in 0 .. Length(bits1) - 1 { + function FindFirstDiff(bits1 : Bool[], bits2 : Bool[]) : Int { + for i in 0..Length(bits1) - 1 { if bits1[i] != bits2[i] { return i; } @@ -11,7 +11,7 @@ namespace Kata.Verification { return -1; } - operation TwoBitstringSuperposition_Reference (qs : Qubit[], bits1 : Bool[], bits2 : Bool[]) : Unit is Adj + Ctl { + operation TwoBitstringSuperposition_Reference(qs : Qubit[], bits1 : Bool[], bits2 : Bool[]) : Unit is Adj + Ctl { // find the index of the first bit at which the bit strings are different let firstDiff = FindFirstDiff(bits1, bits2); @@ -19,7 +19,7 @@ namespace Kata.Verification { H(qs[firstDiff]); // iterate through the bit strings again setting the final state of qubits - for i in 0 .. Length(qs) - 1 { + for i in 0..Length(qs) - 1 { if bits1[i] == bits2[i] { // if two bits are the same, apply X or nothing if bits1[i] { @@ -35,7 +35,7 @@ namespace Kata.Verification { } } } - } + } @EntryPoint() operation CheckSolution() : Bool { @@ -59,14 +59,15 @@ namespace Kata.Verification { [true, false, true] ]; - for i in 0 .. Length(bitstrings_one) - 1 { + for i in 0..Length(bitstrings_one) - 1 { let bits1 = bitstrings_one[i]; let bits2 = bitstrings_two[i]; Message($"Testing for bits1 = {bits1} and bits2 = {bits2}..."); if not CheckOperationsEquivalenceOnZeroStateWithFeedback( Kata.TwoBitstringSuperposition(_, bits1, bits2), TwoBitstringSuperposition_Reference(_, bits1, bits2), - Length(bits1)) { + Length(bits1) + ) { return false; } } diff --git a/katas/content/preparing_states/unequal_superposition/Verification.qs b/katas/content/preparing_states/unequal_superposition/Verification.qs index 5123752053..e7f7cca28e 100644 --- a/katas/content/preparing_states/unequal_superposition/Verification.qs +++ b/katas/content/preparing_states/unequal_superposition/Verification.qs @@ -1,7 +1,7 @@ namespace Kata.Verification { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; + import Std.Convert.*; + import KatasUtils.*; + import Std.Math.*; operation UnequalSuperposition_Reference(q : Qubit, alpha : Double) : Unit is Adj + Ctl { Ry(2.0 * alpha, q); @@ -11,15 +11,16 @@ namespace Kata.Verification { operation CheckSolution() : Bool { let limit = 36; let precision = 3; - for i in 0 .. limit { + for i in 0..limit { let alpha = 2.0 * PI() * IntAsDouble(i) / IntAsDouble(limit); let solution = Kata.UnequalSuperposition(_, alpha); let reference = UnequalSuperposition_Reference(_, alpha); Message($"Testing for alpha = {DoubleAsStringWithPrecision(alpha, precision)}..."); if not CheckOperationsEquivalenceOnZeroStateWithFeedback( - qs => solution(qs[0]), + qs => solution(qs[0]), qs => reference(qs[0]), - 1) { + 1 + ) { return false; } } diff --git a/katas/content/preparing_states/wstate_arbitrary/SolutionA.qs b/katas/content/preparing_states/wstate_arbitrary/SolutionA.qs index 9227c5feab..fcdcaf9c8d 100644 --- a/katas/content/preparing_states/wstate_arbitrary/SolutionA.qs +++ b/katas/content/preparing_states/wstate_arbitrary/SolutionA.qs @@ -1,13 +1,17 @@ namespace Kata { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Math; + import Std.Convert.*; + import Std.Math.*; - operation WState_Arbitrary (qs : Qubit[]) : Unit is Adj + Ctl { + operation WState_Arbitrary(qs : Qubit[]) : Unit is Adj + Ctl { let N = Length(qs); Ry(2.0 * ArcSin(Sqrt(1.0 / IntAsDouble(N))), qs[0]); - for i in 1 .. N - 1 { - ApplyControlledOnInt(0, Ry(2.0 * ArcSin(Sqrt(1.0 / IntAsDouble(N - i))), _), - qs[0 .. i - 1], qs[i]); + for i in 1..N - 1 { + ApplyControlledOnInt( + 0, + Ry(2.0 * ArcSin(Sqrt(1.0 / IntAsDouble(N - i))), _), + qs[0..i - 1], + qs[i] + ); } } } diff --git a/katas/content/preparing_states/wstate_arbitrary/SolutionB.qs b/katas/content/preparing_states/wstate_arbitrary/SolutionB.qs index c4082a9b17..34fc7ed8dd 100644 --- a/katas/content/preparing_states/wstate_arbitrary/SolutionB.qs +++ b/katas/content/preparing_states/wstate_arbitrary/SolutionB.qs @@ -1,12 +1,12 @@ namespace Kata { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Math; + import Std.Convert.*; + import Std.Math.*; - operation WState_Arbitrary (qs : Qubit[]) : Unit is Adj + Ctl { + operation WState_Arbitrary(qs : Qubit[]) : Unit is Adj + Ctl { let N = Length(qs); Ry(2.0 * ArcSin(Sqrt(1.0 / IntAsDouble(N))), qs[0]); if N > 1 { - ApplyControlledOnInt(0, WState_Arbitrary, [qs[0]], qs[1 ...]); + ApplyControlledOnInt(0, WState_Arbitrary, [qs[0]], qs[1...]); } } } diff --git a/katas/content/preparing_states/wstate_arbitrary/Verification.qs b/katas/content/preparing_states/wstate_arbitrary/Verification.qs index ef1491496a..02951eefbe 100644 --- a/katas/content/preparing_states/wstate_arbitrary/Verification.qs +++ b/katas/content/preparing_states/wstate_arbitrary/Verification.qs @@ -1,24 +1,25 @@ namespace Kata.Verification { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; + import Std.Convert.*; + import KatasUtils.*; + import Std.Math.*; - operation WState_Arbitrary_Reference (qs : Qubit[]) : Unit is Adj + Ctl { + operation WState_Arbitrary_Reference(qs : Qubit[]) : Unit is Adj + Ctl { let N = Length(qs); - Ry(2.0 * ArcSin(Sqrt(1.0/IntAsDouble(N))), qs[0]); - for i in 1 .. N - 1 { - ApplyControlledOnInt(0, Ry(2.0 * ArcSin(Sqrt(1.0/IntAsDouble(N - i))), _), qs[0 .. i-1], qs[i]); + Ry(2.0 * ArcSin(Sqrt(1.0 / IntAsDouble(N))), qs[0]); + for i in 1..N - 1 { + ApplyControlledOnInt(0, Ry(2.0 * ArcSin(Sqrt(1.0 / IntAsDouble(N - i))), _), qs[0..i-1], qs[i]); } } @EntryPoint() operation CheckSolution() : Bool { - for n in 1 .. 6 { + for n in 1..6 { Message($"Testing for N = {n}..."); if not CheckOperationsEquivalenceOnZeroStateWithFeedback( Kata.WState_Arbitrary, WState_Arbitrary_Reference, - n) { + n + ) { return false; } } diff --git a/katas/content/preparing_states/wstate_power_of_two/Verification.qs b/katas/content/preparing_states/wstate_power_of_two/Verification.qs index a3463b5619..ff5b0660f4 100644 --- a/katas/content/preparing_states/wstate_power_of_two/Verification.qs +++ b/katas/content/preparing_states/wstate_power_of_two/Verification.qs @@ -1,13 +1,13 @@ namespace Kata.Verification { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; + import Std.Convert.*; + import KatasUtils.*; + import Std.Math.*; - operation WState_PowerOfTwo_Reference (qs : Qubit[]) : Unit is Adj + Ctl { + operation WState_PowerOfTwo_Reference(qs : Qubit[]) : Unit is Adj + Ctl { let N = Length(qs); - Ry(2.0 * ArcSin(Sqrt(1.0/IntAsDouble(N))), qs[0]); - for i in 1 .. N - 1 { - ApplyControlledOnInt(0, Ry(2.0 * ArcSin(Sqrt(1.0/IntAsDouble(N - i))), _), qs[0 .. i-1], qs[i]); + Ry(2.0 * ArcSin(Sqrt(1.0 / IntAsDouble(N))), qs[0]); + for i in 1..N - 1 { + ApplyControlledOnInt(0, Ry(2.0 * ArcSin(Sqrt(1.0 / IntAsDouble(N - i))), _), qs[0..i-1], qs[i]); } } @@ -18,7 +18,8 @@ namespace Kata.Verification { if not CheckOperationsEquivalenceOnZeroStateWithFeedback( Kata.WState_PowerOfTwo, WState_PowerOfTwo_Reference, - n) { + n + ) { return false; } } diff --git a/katas/content/preparing_states/zero_and_bitstring/Verification.qs b/katas/content/preparing_states/zero_and_bitstring/Verification.qs index dadee06727..83ace1d78f 100644 --- a/katas/content/preparing_states/zero_and_bitstring/Verification.qs +++ b/katas/content/preparing_states/zero_and_bitstring/Verification.qs @@ -1,11 +1,11 @@ namespace Kata.Verification { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Katas; + import Std.Convert.*; + import KatasUtils.*; - operation ZeroAndBitstringSuperposition_Reference (qs : Qubit[], bits : Bool[]) : Unit is Adj + Ctl { + operation ZeroAndBitstringSuperposition_Reference(qs : Qubit[], bits : Bool[]) : Unit is Adj + Ctl { H(qs[0]); - for i in 1 .. Length(qs) - 1 { + for i in 1..Length(qs) - 1 { if bits[i] { CNOT(qs[0], qs[i]); } @@ -29,7 +29,8 @@ namespace Kata.Verification { if not CheckOperationsEquivalenceOnZeroStateWithFeedback( Kata.ZeroAndBitstringSuperposition(_, bits), ZeroAndBitstringSuperposition_Reference(_, bits), - Length(bits)) { + Length(bits) + ) { return false; } } diff --git a/katas/content/qec_shor/Common.qs b/katas/content/qec_shor/Common.qs index f51bc01713..17c6f5c6c9 100644 --- a/katas/content/qec_shor/Common.qs +++ b/katas/content/qec_shor/Common.qs @@ -1,7 +1,7 @@ namespace Kata.Verification { - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Math; - open Microsoft.Quantum.Random; + import Std.Diagnostics.*; + import Std.Math.*; + import Std.Random.*; operation CheckErrorDetection( n : Int, @@ -9,8 +9,8 @@ namespace Kata.Verification { error : (Qubit => Unit is Adj), detect : (Qubit[] => Int) ) : Bool { - for err_ind in -1 .. n - 1 { - for _ in 1 .. 10 { + for err_ind in -1..n - 1 { + for _ in 1..10 { use qs = Qubit[n]; let theta = DrawRandomDouble(0.0, 1.0); within { diff --git a/katas/content/qec_shor/bitflip_detect/Verification.qs b/katas/content/qec_shor/bitflip_detect/Verification.qs index ec438bf4d1..0774368b4b 100644 --- a/katas/content/qec_shor/bitflip_detect/Verification.qs +++ b/katas/content/qec_shor/bitflip_detect/Verification.qs @@ -1,7 +1,7 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; - operation BitflipEncode (qs : Qubit[]) : Unit is Adj + Ctl { + operation BitflipEncode(qs : Qubit[]) : Unit is Adj + Ctl { CNOT(qs[0], qs[1]); CNOT(qs[0], qs[2]); } diff --git a/katas/content/qec_shor/bitflip_encode/Verification.qs b/katas/content/qec_shor/bitflip_encode/Verification.qs index ab4526d988..683b6d0564 100644 --- a/katas/content/qec_shor/bitflip_encode/Verification.qs +++ b/katas/content/qec_shor/bitflip_encode/Verification.qs @@ -1,10 +1,10 @@ namespace Kata.Verification { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; + import Std.Convert.*; + import Std.Diagnostics.*; + import KatasUtils.*; + import Std.Math.*; - operation BitflipEncode_Reference (qs : Qubit[]) : Unit is Adj + Ctl { + operation BitflipEncode_Reference(qs : Qubit[]) : Unit is Adj + Ctl { CNOT(qs[0], qs[1]); CNOT(qs[0], qs[2]); } @@ -13,14 +13,15 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { let range = 10; - for i in 0 .. range - 1 { + for i in 0..range - 1 { let angle = 2.0 * PI() * IntAsDouble(i) / IntAsDouble(range); let initialState = qs => Ry(2.0 * angle, qs[0]); let isCorrect = CheckOperationsEquivalenceOnInitialStateStrict( initialState, - Kata.BitflipEncode, - BitflipEncode_Reference, - 3); + Kata.BitflipEncode, + BitflipEncode_Reference, + 3 + ); if not isCorrect { Message("Incorrect"); Message($"Test fails for alpha = {Cos(angle)}, beta = {Sin(angle)}."); diff --git a/katas/content/qec_shor/examples/ShorCodeDemo.qs b/katas/content/qec_shor/examples/ShorCodeDemo.qs index c50579e040..9d82481fed 100644 --- a/katas/content/qec_shor/examples/ShorCodeDemo.qs +++ b/katas/content/qec_shor/examples/ShorCodeDemo.qs @@ -1,7 +1,7 @@ namespace Kata { - open Microsoft.Quantum.Arrays; - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Math; + import Std.Arrays.*; + import Std.Diagnostics.*; + import Std.Math.*; @EntryPoint() operation RunExample() : Unit { @@ -24,7 +24,7 @@ namespace Kata { } elif err == PauliY { Y(qs[ind]); } else { - ForEach(q => Z(q), qs[ind * 3 .. ind * 3 + 2]); + ForEach(q => Z(q), qs[ind * 3..ind * 3 + 2]); } } @@ -40,33 +40,33 @@ namespace Kata { } } - operation ShorEncode (qs : Qubit[]) : Unit is Adj + Ctl { - BitflipEncode(qs[0 .. 3 .. 8]); - ApplyToEachCA(H, qs[0 .. 3 .. 8]); - for i in 0 .. 2 { - BitflipEncode(qs[3 * i .. 3 * i + 2]); + operation ShorEncode(qs : Qubit[]) : Unit is Adj + Ctl { + BitflipEncode(qs[0..3..8]); + ApplyToEachCA(H, qs[0..3..8]); + for i in 0..2 { + BitflipEncode(qs[3 * i..3 * i + 2]); } } - operation BitflipEncode (qs : Qubit[]) : Unit is Adj + Ctl { + operation BitflipEncode(qs : Qubit[]) : Unit is Adj + Ctl { CNOT(qs[0], qs[1]); CNOT(qs[0], qs[2]); } - operation ShorDetectError (qs : Qubit[]) : (Int, Pauli) { + operation ShorDetectError(qs : Qubit[]) : (Int, Pauli) { // Detect X error first mutable x_ind = -1; - for i in 0 .. 2 { - let err_ind = BitflipDetectError(qs[3 * i .. 3 * i + 2]); + for i in 0..2 { + let err_ind = BitflipDetectError(qs[3 * i..3 * i + 2]); if err_ind > -1 { set x_ind = 3 * i + err_ind; } } - // Detect Z error + // Detect Z error mutable z_ind = -1; - let m1 = Measure([PauliX, size = 6], qs[0 .. 5]); - let m2 = Measure([PauliX, size = 6], qs[3 .. 8]); + let m1 = Measure([PauliX, size = 6], qs[0..5]); + let m2 = Measure([PauliX, size = 6], qs[3..8]); if m1 == Zero and m2 == Zero { set z_ind = -1; @@ -91,10 +91,10 @@ namespace Kata { return (z_ind, PauliZ); } - operation BitflipDetectError (qs : Qubit[]) : Int { - let m1 = Measure([PauliZ, PauliZ], qs[0 .. 1]); - let m2 = Measure([PauliZ, PauliZ], qs[1 .. 2]); - + operation BitflipDetectError(qs : Qubit[]) : Int { + let m1 = Measure([PauliZ, PauliZ], qs[0..1]); + let m2 = Measure([PauliZ, PauliZ], qs[1..2]); + if m1 == One and m2 == Zero { return 0; } elif m1 == One and m2 == One { diff --git a/katas/content/qec_shor/phaseflip_detect/Verification.qs b/katas/content/qec_shor/phaseflip_detect/Verification.qs index ac6eeba497..6cb7b738bd 100644 --- a/katas/content/qec_shor/phaseflip_detect/Verification.qs +++ b/katas/content/qec_shor/phaseflip_detect/Verification.qs @@ -1,7 +1,7 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; - operation PhaseflipEncode (qs : Qubit[]) : Unit is Adj + Ctl { + operation PhaseflipEncode(qs : Qubit[]) : Unit is Adj + Ctl { CNOT(qs[0], qs[1]); CNOT(qs[0], qs[2]); ApplyToEachCA(H, qs); diff --git a/katas/content/qec_shor/phaseflip_encode/Verification.qs b/katas/content/qec_shor/phaseflip_encode/Verification.qs index 3f41f2e67e..5b7b8f228a 100644 --- a/katas/content/qec_shor/phaseflip_encode/Verification.qs +++ b/katas/content/qec_shor/phaseflip_encode/Verification.qs @@ -1,10 +1,10 @@ namespace Kata.Verification { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; + import Std.Convert.*; + import Std.Diagnostics.*; + import KatasUtils.*; + import Std.Math.*; - operation PhaseflipEncode_Reference (qs : Qubit[]) : Unit is Adj + Ctl { + operation PhaseflipEncode_Reference(qs : Qubit[]) : Unit is Adj + Ctl { CNOT(qs[0], qs[1]); CNOT(qs[0], qs[2]); ApplyToEachCA(H, qs); @@ -14,14 +14,15 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { let range = 10; - for i in 0 .. range - 1 { + for i in 0..range - 1 { let angle = 2.0 * PI() * IntAsDouble(i) / IntAsDouble(range); let initialState = qs => Ry(2.0 * angle, qs[0]); let isCorrect = CheckOperationsEquivalenceOnInitialStateStrict( initialState, - Kata.PhaseflipEncode, - PhaseflipEncode_Reference, - 3); + Kata.PhaseflipEncode, + PhaseflipEncode_Reference, + 3 + ); if not isCorrect { Message("Incorrect"); Message($"Test fails for alpha = {Cos(angle)}, beta = {Sin(angle)}."); diff --git a/katas/content/qec_shor/shor_detect/Verification.qs b/katas/content/qec_shor/shor_detect/Verification.qs index 257f69ba97..4a809f4a05 100644 --- a/katas/content/qec_shor/shor_detect/Verification.qs +++ b/katas/content/qec_shor/shor_detect/Verification.qs @@ -1,18 +1,18 @@ namespace Kata.Verification { - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; - open Microsoft.Quantum.Random; + import Std.Diagnostics.*; + import KatasUtils.*; + import Std.Math.*; + import Std.Random.*; - operation ShorEncode (qs : Qubit[]) : Unit is Adj + Ctl { - BitflipEncode(qs[0 .. 3 .. 8]); - ApplyToEachCA(H, qs[0 .. 3 .. 8]); - for i in 0 .. 2 { - BitflipEncode(qs[3 * i .. 3 * i + 2]); + operation ShorEncode(qs : Qubit[]) : Unit is Adj + Ctl { + BitflipEncode(qs[0..3..8]); + ApplyToEachCA(H, qs[0..3..8]); + for i in 0..2 { + BitflipEncode(qs[3 * i..3 * i + 2]); } } - operation BitflipEncode (qs : Qubit[]) : Unit is Adj + Ctl { + operation BitflipEncode(qs : Qubit[]) : Unit is Adj + Ctl { CNOT(qs[0], qs[1]); CNOT(qs[0], qs[2]); } @@ -20,9 +20,9 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { - for err_ind in -1 .. 8 { + for err_ind in -1..8 { for err in [PauliX, PauliZ, PauliY] { - for _ in 1 .. 10 { + for _ in 1..10 { mutable correct = true; mutable msg = ""; use qs = Qubit[9]; diff --git a/katas/content/qec_shor/shor_encode/Verification.qs b/katas/content/qec_shor/shor_encode/Verification.qs index 6d445f3ef8..63b35505f9 100644 --- a/katas/content/qec_shor/shor_encode/Verification.qs +++ b/katas/content/qec_shor/shor_encode/Verification.qs @@ -1,18 +1,18 @@ namespace Kata.Verification { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; + import Std.Convert.*; + import Std.Diagnostics.*; + import KatasUtils.*; + import Std.Math.*; - operation ShorEncode_Reference (qs : Qubit[]) : Unit is Adj + Ctl { - BitflipEncode(qs[0 .. 3 .. 8]); - ApplyToEachCA(H, qs[0 .. 3 .. 8]); - for i in 0 .. 2 { - BitflipEncode(qs[3 * i .. 3 * i + 2]); + operation ShorEncode_Reference(qs : Qubit[]) : Unit is Adj + Ctl { + BitflipEncode(qs[0..3..8]); + ApplyToEachCA(H, qs[0..3..8]); + for i in 0..2 { + BitflipEncode(qs[3 * i..3 * i + 2]); } } - operation BitflipEncode (qs : Qubit[]) : Unit is Adj + Ctl { + operation BitflipEncode(qs : Qubit[]) : Unit is Adj + Ctl { CNOT(qs[0], qs[1]); CNOT(qs[0], qs[2]); } @@ -21,14 +21,15 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { let range = 10; - for i in 0 .. range - 1 { + for i in 0..range - 1 { let angle = 2.0 * PI() * IntAsDouble(i) / IntAsDouble(range); let initialState = qs => Ry(2.0 * angle, qs[0]); let isCorrect = CheckOperationsEquivalenceOnInitialStateStrict( initialState, - Kata.ShorEncode, - ShorEncode_Reference, - 9); + Kata.ShorEncode, + ShorEncode_Reference, + 9 + ); if not isCorrect { Message("Incorrect"); Message($"Test fails for alpha = {Cos(angle)}, beta = {Sin(angle)}."); diff --git a/katas/content/qec_shor/xx_measurement/Verification.qs b/katas/content/qec_shor/xx_measurement/Verification.qs index acf715dbab..f18babbc22 100644 --- a/katas/content/qec_shor/xx_measurement/Verification.qs +++ b/katas/content/qec_shor/xx_measurement/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; operation StatePrep_XXMeasurement(qs : Qubit[], state : Int, alpha : Double) : Unit is Adj { // prep cos(alpha) * |0..0⟩ + sin(alpha) * |1..1⟩ @@ -21,7 +21,8 @@ namespace Kata.Verification { StatePrep_XXMeasurement, Kata.XXMeasurement, true, - ["α|++⟩ + β|--⟩", "α|+-⟩ + β|-+⟩"]); + ["α|++⟩ + β|--⟩", "α|+-⟩ + β|-+⟩"] + ); if (isCorrect) { Message("Correct!"); diff --git a/katas/content/qec_shor/zz_measurement/Verification.qs b/katas/content/qec_shor/zz_measurement/Verification.qs index 248e0a3c0f..886a317c40 100644 --- a/katas/content/qec_shor/zz_measurement/Verification.qs +++ b/katas/content/qec_shor/zz_measurement/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; operation StatePrep_ZZMeasurement(qs : Qubit[], state : Int, alpha : Double) : Unit is Adj { // prep cos(alpha) * |0..0⟩ + sin(alpha) * |1..1⟩ @@ -19,7 +19,8 @@ namespace Kata.Verification { StatePrep_ZZMeasurement, Kata.ZZMeasurement, true, - ["α|00⟩ + β|11⟩", "α|01⟩ + β|10⟩"]); + ["α|00⟩ + β|11⟩", "α|01⟩ + β|10⟩"] + ); if (isCorrect) { Message("Correct!"); diff --git a/katas/content/qft/all_basis_vectors/Placeholder.qs b/katas/content/qft/all_basis_vectors/Placeholder.qs index a90df6b881..fed5d1da17 100644 --- a/katas/content/qft/all_basis_vectors/Placeholder.qs +++ b/katas/content/qft/all_basis_vectors/Placeholder.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Arrays; + import Std.Arrays.*; operation AllBasisVectors(qs : Qubit[]) : Unit is Adj + Ctl { // Implement your solution here... diff --git a/katas/content/qft/all_basis_vectors/Solution.qs b/katas/content/qft/all_basis_vectors/Solution.qs index 9f5a9e51ac..a7bfbfb102 100644 --- a/katas/content/qft/all_basis_vectors/Solution.qs +++ b/katas/content/qft/all_basis_vectors/Solution.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Arrays; + import Std.Arrays.*; operation AllBasisVectors(qs : Qubit[]) : Unit is Adj + Ctl { QFT(qs); diff --git a/katas/content/qft/all_basis_vectors/Verification.qs b/katas/content/qft/all_basis_vectors/Verification.qs index 849b58b2ec..2b16cbc171 100644 --- a/katas/content/qft/all_basis_vectors/Verification.qs +++ b/katas/content/qft/all_basis_vectors/Verification.qs @@ -1,7 +1,7 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; - operation AllBasisVectors_Reference (qs : Qubit[]) : Unit is Adj + Ctl { + operation AllBasisVectors_Reference(qs : Qubit[]) : Unit is Adj + Ctl { for q in qs { H(q); } @@ -9,7 +9,7 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { - for n in 1 .. 5 { + for n in 1..5 { let solution = Kata.AllBasisVectors; let reference = AllBasisVectors_Reference; if not CheckOperationsEquivalenceOnZeroState(solution, reference, n) { diff --git a/katas/content/qft/all_even_vectors/Placeholder.qs b/katas/content/qft/all_even_vectors/Placeholder.qs index ded143f350..e72d6bfd4a 100644 --- a/katas/content/qft/all_even_vectors/Placeholder.qs +++ b/katas/content/qft/all_even_vectors/Placeholder.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Arrays; + import Std.Arrays.*; operation AllEvenVectors(qs : Qubit[]) : Unit is Adj + Ctl { // Implement your solution here... diff --git a/katas/content/qft/all_even_vectors/Solution.qs b/katas/content/qft/all_even_vectors/Solution.qs index 5129bbb29f..31b8f9e0fc 100644 --- a/katas/content/qft/all_even_vectors/Solution.qs +++ b/katas/content/qft/all_even_vectors/Solution.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Arrays; + import Std.Arrays.*; operation AllEvenVectors(qs : Qubit[]) : Unit is Adj + Ctl { H(qs[0]); diff --git a/katas/content/qft/all_even_vectors/Verification.qs b/katas/content/qft/all_even_vectors/Verification.qs index 999dc0b004..78177da7d7 100644 --- a/katas/content/qft/all_even_vectors/Verification.qs +++ b/katas/content/qft/all_even_vectors/Verification.qs @@ -1,7 +1,7 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; - operation AllEvenVectors_Reference (qs : Qubit[]) : Unit is Adj + Ctl { + operation AllEvenVectors_Reference(qs : Qubit[]) : Unit is Adj + Ctl { for q in qs[...Length(qs) - 2] { H(q); } @@ -9,7 +9,7 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { - for n in 1 .. 5 { + for n in 1..5 { let solution = Kata.AllEvenVectors; let reference = AllEvenVectors_Reference; if not CheckOperationsEquivalenceOnZeroState(solution, reference, n) { diff --git a/katas/content/qft/alternating_amplitudes/Placeholder.qs b/katas/content/qft/alternating_amplitudes/Placeholder.qs index 8155987d26..000f380811 100644 --- a/katas/content/qft/alternating_amplitudes/Placeholder.qs +++ b/katas/content/qft/alternating_amplitudes/Placeholder.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Arrays; + import Std.Arrays.*; operation AlternatingAmplitudes(qs : Qubit[]) : Unit is Adj + Ctl { // Implement your solution here... diff --git a/katas/content/qft/alternating_amplitudes/Solution.qs b/katas/content/qft/alternating_amplitudes/Solution.qs index 34e0e677ed..69128040b8 100644 --- a/katas/content/qft/alternating_amplitudes/Solution.qs +++ b/katas/content/qft/alternating_amplitudes/Solution.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Arrays; + import Std.Arrays.*; operation AlternatingAmplitudes(qs : Qubit[]) : Unit is Adj + Ctl { X(qs[0]); diff --git a/katas/content/qft/alternating_amplitudes/Verification.qs b/katas/content/qft/alternating_amplitudes/Verification.qs index cf4b46dbcf..6cee7554bf 100644 --- a/katas/content/qft/alternating_amplitudes/Verification.qs +++ b/katas/content/qft/alternating_amplitudes/Verification.qs @@ -1,7 +1,7 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; - operation AlternatingAmplitudes_Reference (qs : Qubit[]) : Unit is Adj + Ctl { + operation AlternatingAmplitudes_Reference(qs : Qubit[]) : Unit is Adj + Ctl { for q in qs { H(q); } @@ -10,7 +10,7 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { - for n in 1 .. 5 { + for n in 1..5 { let solution = Kata.AlternatingAmplitudes; let reference = AlternatingAmplitudes_Reference; if not CheckOperationsEquivalenceOnZeroState(solution, reference, n) { diff --git a/katas/content/qft/binary_fraction_classical/SolutionB.qs b/katas/content/qft/binary_fraction_classical/SolutionB.qs index 91c055c5a0..ddbb1d2b34 100644 --- a/katas/content/qft/binary_fraction_classical/SolutionB.qs +++ b/katas/content/qft/binary_fraction_classical/SolutionB.qs @@ -1,11 +1,11 @@ namespace Kata { - open Microsoft.Quantum.Arrays; - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Math; + import Std.Arrays.*; + import Std.Convert.*; + import Std.Math.*; operation BinaryFractionClassical(q : Qubit, j : Bool[]) : Unit is Adj + Ctl { let n = Length(j); let jIntBE = BoolArrayAsInt(Reversed(j)); R1(2.0 * PI() * IntAsDouble(jIntBE) / IntAsDouble(1 <<< n), q); } -} \ No newline at end of file +} diff --git a/katas/content/qft/binary_fraction_classical/Verification.qs b/katas/content/qft/binary_fraction_classical/Verification.qs index 3b2cc2b970..c37298cdfd 100644 --- a/katas/content/qft/binary_fraction_classical/Verification.qs +++ b/katas/content/qft/binary_fraction_classical/Verification.qs @@ -1,18 +1,18 @@ namespace Kata.Verification { - open Microsoft.Quantum.Arrays; - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; + import Std.Arrays.*; + import Std.Convert.*; + import KatasUtils.*; + import Std.Math.*; - operation BinaryFractionClassical_Alternative (q : Qubit, j : Bool[]) : Unit is Adj+Ctl { + operation BinaryFractionClassical_Alternative(q : Qubit, j : Bool[]) : Unit is Adj + Ctl { // Convert the number to an integer and apply a single R1 rotation R1(2.0 * PI() * IntAsDouble(BoolArrayAsInt(Reversed(j))) / IntAsDouble(1 <<< Length(j)), q); } @EntryPoint() operation CheckSolution() : Bool { - for n in 1 .. 5 { - for exp in 0 .. (1 <<< n) - 1 { + for n in 1..5 { + for exp in 0..(1 <<< n) - 1 { let j = Reversed(IntAsBoolArray(exp, n)); let solution = qs => Kata.BinaryFractionClassical(qs[0], j); let reference = qs => BinaryFractionClassical_Alternative(qs[0], j); diff --git a/katas/content/qft/binary_fraction_inplace/Verification.qs b/katas/content/qft/binary_fraction_inplace/Verification.qs index e20e9bb0c4..a565fc4e2a 100644 --- a/katas/content/qft/binary_fraction_inplace/Verification.qs +++ b/katas/content/qft/binary_fraction_inplace/Verification.qs @@ -1,19 +1,19 @@ namespace Kata.Verification { - open Microsoft.Quantum.Arrays; - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; + import Std.Arrays.*; + import Std.Convert.*; + import KatasUtils.*; + import Std.Math.*; operation BinaryFractionQuantumInPlace_Reference(j : Qubit[]) : Unit is Adj + Ctl { H(j[0]); - for ind in 1 .. Length(j) - 1 { + for ind in 1..Length(j) - 1 { Controlled R1Frac([j[ind]], (2, ind + 1, j[0])); } } @EntryPoint() operation CheckSolution() : Bool { - for n in 1 .. 5 { + for n in 1..5 { if not CheckOperationsAreEqualStrict(n, Kata.BinaryFractionQuantumInPlace, BinaryFractionQuantumInPlace_Reference) { Message($"Incorrect for n = {n}."); return false; diff --git a/katas/content/qft/binary_fraction_quantum/Verification.qs b/katas/content/qft/binary_fraction_quantum/Verification.qs index 586319774c..4eab073e85 100644 --- a/katas/content/qft/binary_fraction_quantum/Verification.qs +++ b/katas/content/qft/binary_fraction_quantum/Verification.qs @@ -1,20 +1,20 @@ namespace Kata.Verification { - open Microsoft.Quantum.Arrays; - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; + import Std.Arrays.*; + import Std.Convert.*; + import KatasUtils.*; + import Std.Math.*; operation BinaryFractionQuantum_Reference(q : Qubit, j : Qubit[]) : Unit is Adj + Ctl { - for ind in 0 .. Length(j) - 1 { + for ind in 0..Length(j) - 1 { Controlled R1Frac([j[ind]], (2, ind + 1, q)); } } @EntryPoint() operation CheckSolution() : Bool { - for n in 1 .. 5 { - let solution = qs => Kata.BinaryFractionQuantum(qs[0], qs[1 ...]); - let reference = qs => BinaryFractionQuantum_Reference(qs[0], qs[1 ...]); + for n in 1..5 { + let solution = qs => Kata.BinaryFractionQuantum(qs[0], qs[1...]); + let reference = qs => BinaryFractionQuantum_Reference(qs[0], qs[1...]); if not CheckOperationsAreEqualStrict(n + 1, solution, reference) { Message($"Incorrect for n = {n}."); return false; diff --git a/katas/content/qft/periodic_state/Placeholder.qs b/katas/content/qft/periodic_state/Placeholder.qs index 9d136b95fb..44bd407382 100644 --- a/katas/content/qft/periodic_state/Placeholder.qs +++ b/katas/content/qft/periodic_state/Placeholder.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Arrays; + import Std.Arrays.*; operation PeriodicState(qs : Qubit[], F : Int) : Unit is Adj + Ctl { // Implement your solution here... diff --git a/katas/content/qft/periodic_state/Solution.qs b/katas/content/qft/periodic_state/Solution.qs index a6fe1b0a1f..180202440a 100644 --- a/katas/content/qft/periodic_state/Solution.qs +++ b/katas/content/qft/periodic_state/Solution.qs @@ -1,6 +1,6 @@ namespace Kata { - open Microsoft.Quantum.Arrays; - open Microsoft.Quantum.Convert; + import Std.Arrays.*; + import Std.Convert.*; operation PeriodicState(qs : Qubit[], F : Int) : Unit is Adj + Ctl { let bitsBE = Reversed(IntAsBoolArray(F, Length(qs))); diff --git a/katas/content/qft/periodic_state/Verification.qs b/katas/content/qft/periodic_state/Verification.qs index b1df526b0c..0cb8e3c08e 100644 --- a/katas/content/qft/periodic_state/Verification.qs +++ b/katas/content/qft/periodic_state/Verification.qs @@ -1,22 +1,23 @@ namespace Kata.Verification { - open Microsoft.Quantum.Arrays; - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; - open Microsoft.Quantum.Unstable.StatePreparation; + import Std.Arrays.*; + import Std.Convert.*; + import KatasUtils.*; + import Std.Math.*; + import Std.StatePreparation.*; - operation PeriodicState_Reference (qs : Qubit[], F : Int) : Unit is Adj + Ctl { + operation PeriodicState_Reference(qs : Qubit[], F : Int) : Unit is Adj + Ctl { let n = Length(qs); let amps = MappedOverRange( - k -> ComplexPolar(1.0, 2. * PI() * IntAsDouble(F * k) / IntAsDouble(2 ^ n)), - 0 .. 2 ^ n - 1); + k -> ComplexPolar(1.0, 2. * PI() * IntAsDouble(F * k) / IntAsDouble(2^n)), + 0..2^n - 1 + ); ApproximatelyPreparePureStateCP(0.0, amps, qs); } @EntryPoint() operation CheckSolution() : Bool { - for n in 1 .. 3 { - for F in 0 .. 2 ^ n - 1 { + for n in 1..3 { + for F in 0..2^n - 1 { let solution = Kata.PeriodicState(_, F); let reference = PeriodicState_Reference(_, F); if not CheckOperationsEquivalenceOnZeroState(solution, reference, n) { diff --git a/katas/content/qft/qft/Verification.qs b/katas/content/qft/qft/Verification.qs index 10541c3e97..bc62d2f3fa 100644 --- a/katas/content/qft/qft/Verification.qs +++ b/katas/content/qft/qft/Verification.qs @@ -1,7 +1,7 @@ namespace Kata.Verification { - open Microsoft.Quantum.Arrays; - open Microsoft.Quantum.Katas; - + import Std.Arrays.*; + import KatasUtils.*; + operation LibraryQFT(qs : Qubit[]) : Unit is Adj + Ctl { ApplyQFT(Reversed(qs)); SwapReverseRegister(qs); @@ -9,7 +9,7 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { - for n in 1 .. 5 { + for n in 1..5 { if not CheckOperationsAreEqualStrict(n, Kata.QuantumFourierTransform, LibraryQFT) { Message($"Incorrect for n = {n}."); return false; diff --git a/katas/content/qft/rotation_gate/Verification.qs b/katas/content/qft/rotation_gate/Verification.qs index 267e5b0a41..0ea2a58ea3 100644 --- a/katas/content/qft/rotation_gate/Verification.qs +++ b/katas/content/qft/rotation_gate/Verification.qs @@ -1,10 +1,10 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; + import KatasUtils.*; + import Std.Math.*; @EntryPoint() operation CheckSolution() : Bool { - for k in 0 .. 10 { + for k in 0..10 { let solution = qs => Kata.Rotation(qs[0], k); let reference = qs => R1Frac(2, k, qs[0]); if not CheckOperationsAreEqualStrict(1, solution, reference) { diff --git a/katas/content/qft/signal_frequency/Placeholder.qs b/katas/content/qft/signal_frequency/Placeholder.qs index 25ffc0b9f3..0d0b852b31 100644 --- a/katas/content/qft/signal_frequency/Placeholder.qs +++ b/katas/content/qft/signal_frequency/Placeholder.qs @@ -1,9 +1,9 @@ namespace Kata { - open Microsoft.Quantum.Arrays; + import Std.Arrays.*; operation SignalFrequency(qs : Qubit[]) : Int { // Implement your solution here... - + return -1; } diff --git a/katas/content/qft/signal_frequency/Solution.qs b/katas/content/qft/signal_frequency/Solution.qs index d4044d07be..7747b838f5 100644 --- a/katas/content/qft/signal_frequency/Solution.qs +++ b/katas/content/qft/signal_frequency/Solution.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Arrays; + import Std.Arrays.*; operation SignalFrequency(qs : Qubit[]) : Int { Adjoint QFT(qs); diff --git a/katas/content/qft/signal_frequency/Verification.qs b/katas/content/qft/signal_frequency/Verification.qs index 8dedb1efba..f91e13534a 100644 --- a/katas/content/qft/signal_frequency/Verification.qs +++ b/katas/content/qft/signal_frequency/Verification.qs @@ -1,7 +1,7 @@ namespace Kata.Verification { - open Microsoft.Quantum.Arrays; - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Katas; + import Std.Arrays.*; + import Std.Convert.*; + import KatasUtils.*; operation PreparePeriodicState(qs : Qubit[], F : Int) : Unit is Adj + Ctl { let bitsBE = Reversed(IntAsBoolArray(F, Length(qs))); @@ -12,9 +12,9 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { - for n in 2 .. 4 { + for n in 2..4 { use qs = Qubit[n]; - for F in 0 .. 2 ^ n - 1 { + for F in 0..2^n - 1 { PreparePeriodicState(qs, F); let fRes = Kata.SignalFrequency(qs); ResetAll(qs); diff --git a/katas/content/qft/single_qubit/Verification.qs b/katas/content/qft/single_qubit/Verification.qs index 60acd6208e..648a371114 100644 --- a/katas/content/qft/single_qubit/Verification.qs +++ b/katas/content/qft/single_qubit/Verification.qs @@ -1,6 +1,6 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; + import KatasUtils.*; + import Std.Math.*; @EntryPoint() operation CheckSolution() : Bool { diff --git a/katas/content/qft/square_wave/Placeholder.qs b/katas/content/qft/square_wave/Placeholder.qs index 7845798e3f..49333586d1 100644 --- a/katas/content/qft/square_wave/Placeholder.qs +++ b/katas/content/qft/square_wave/Placeholder.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Arrays; + import Std.Arrays.*; operation SquareWave(qs : Qubit[]) : Unit is Adj + Ctl { // Implement your solution here... diff --git a/katas/content/qft/square_wave/Solution.qs b/katas/content/qft/square_wave/Solution.qs index 92e2d46553..3496cb04a3 100644 --- a/katas/content/qft/square_wave/Solution.qs +++ b/katas/content/qft/square_wave/Solution.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Arrays; + import Std.Arrays.*; operation SquareWave(qs : Qubit[]) : Unit is Adj + Ctl { X(qs[1]); diff --git a/katas/content/qft/square_wave/Verification.qs b/katas/content/qft/square_wave/Verification.qs index a09585d263..72d491a4dc 100644 --- a/katas/content/qft/square_wave/Verification.qs +++ b/katas/content/qft/square_wave/Verification.qs @@ -1,7 +1,7 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; - operation SquareWave_Reference (qs : Qubit[]) : Unit is Adj + Ctl { + operation SquareWave_Reference(qs : Qubit[]) : Unit is Adj + Ctl { for q in qs { H(q); } @@ -10,7 +10,7 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { - for n in 2 .. 5 { + for n in 2..5 { let solution = Kata.SquareWave; let reference = SquareWave_Reference; if not CheckOperationsEquivalenceOnZeroState(solution, reference, n) { diff --git a/katas/content/qubit/examples/SingleQubitDumpMachineDemo.qs b/katas/content/qubit/examples/SingleQubitDumpMachineDemo.qs index 2a7f538d0e..2e4d4ea4cb 100644 --- a/katas/content/qubit/examples/SingleQubitDumpMachineDemo.qs +++ b/katas/content/qubit/examples/SingleQubitDumpMachineDemo.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Diagnostics; + import Std.Diagnostics.*; @EntryPoint() operation RunExample() : Unit { diff --git a/katas/content/qubit/index.md b/katas/content/qubit/index.md index c0bb5ee8c6..d92beeebf0 100644 --- a/katas/content/qubit/index.md +++ b/katas/content/qubit/index.md @@ -178,7 +178,7 @@ You would need to run the program repeatedly up to this point, perform a measure However, at the early stages of quantum program development the program typically runs on a simulator - a classical program which simulates the behavior of a small quantum system while having complete information about its internal state. You can take advantage of this to do some non-physical things, such as peeking at the internals of the quantum system to observe its exact state without disturbing it! -The `DumpMachine` function from the `Microsoft.Quantum.Diagnostics` namespace allows you to do exactly that. The output of `DumpMachine` is accurate up to a global phase, and remember that global phase does not have any physical meaning. When using `DumpMachine`, you may see that all probability amplitudes are multiplied by some complex number compared to the state you're expecting. +The `DumpMachine` function from the `Std.Diagnostics` namespace allows you to do exactly that. The output of `DumpMachine` is accurate up to a global phase, and remember that global phase does not have any physical meaning. When using `DumpMachine`, you may see that all probability amplitudes are multiplied by some complex number compared to the state you're expecting. ### Demo: DumpMachine For Single-Qubit Systems diff --git a/katas/content/qubit/learn_single_qubit_state/Solution.qs b/katas/content/qubit/learn_single_qubit_state/Solution.qs index b334bee7e6..6c208316fc 100644 --- a/katas/content/qubit/learn_single_qubit_state/Solution.qs +++ b/katas/content/qubit/learn_single_qubit_state/Solution.qs @@ -1,7 +1,7 @@ -namespace Kata { - open Microsoft.Quantum.Diagnostics; +namespace Kata { + import Std.Diagnostics.*; - operation LearnSingleQubitState (q : Qubit) : (Double, Double) { + operation LearnSingleQubitState(q : Qubit) : (Double, Double) { DumpMachine(); // Only used to learn the amplitudes. return (0.9689, 0.2474); } diff --git a/katas/content/qubit/learn_single_qubit_state/Verification.qs b/katas/content/qubit/learn_single_qubit_state/Verification.qs index b492ec6c60..30282e3277 100644 --- a/katas/content/qubit/learn_single_qubit_state/Verification.qs +++ b/katas/content/qubit/learn_single_qubit_state/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Math; + import Std.Math.*; @EntryPoint() operation CheckSolution() : Bool { diff --git a/katas/content/random_numbers/Common.qs b/katas/content/random_numbers/Common.qs index ee06b50aa6..9e8238b1a0 100644 --- a/katas/content/random_numbers/Common.qs +++ b/katas/content/random_numbers/Common.qs @@ -1,8 +1,8 @@ namespace Kata.Verification { - open Microsoft.Quantum.Arrays; - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Math; + import Std.Arrays.*; + import Std.Diagnostics.*; + import Std.Convert.*; + import Std.Math.*; /// # Summary /// Helper operation that checks that the given RNG operation generates a uniform distribution. @@ -22,12 +22,12 @@ namespace Kata.Verification { /// 0x2 if the average of the distribution is outside the expected range. /// 0x3 if the median of the distribution is outside the expected range. /// 0x4 if the minimum count requirements were not met. - operation CheckUniformDistribution ( + operation CheckUniformDistribution( randomGenerator : (Unit => Int), min : Int, max : Int, - nRuns : Int) - : Int { + nRuns : Int + ) : Int { let idealMean = 0.5 * IntAsDouble(max + min); let rangeDividedByTwo = 0.5 * IntAsDouble(max - min); // Variance = a*(a+1)/3, where a = (max-min)/2 @@ -41,7 +41,7 @@ namespace Kata.Verification { let lowRange = idealMean - 3.0 * standardDeviation; let highRange = idealMean + 3.0 * standardDeviation; - let idealCopiesGenerated = IntAsDouble(nRuns) / IntAsDouble(max-min+1); + let idealCopiesGenerated = IntAsDouble(nRuns) / IntAsDouble(max-min + 1); let minimumCopiesGenerated = (0.8 * idealCopiesGenerated > 40.0) ? 0.8 * idealCopiesGenerated | 0.0; mutable counts = [0, size = max + 1]; @@ -62,7 +62,7 @@ namespace Kata.Verification { return 0x2; } - let median = FindMedian (counts, max+1, nRuns); + let median = FindMedian(counts, max + 1, nRuns); if (median < Floor(lowRange) or median > Ceiling(highRange)) { Message($"Unexpected median of generated numbers. Expected between {Floor(lowRange)} and {Ceiling(highRange)}, got {median}."); return 0x3; @@ -77,9 +77,9 @@ namespace Kata.Verification { return 0x0; } - operation FindMedian (counts : Int[], arrSize : Int, sampleSize : Int) : Int { + operation FindMedian(counts : Int[], arrSize : Int, sampleSize : Int) : Int { mutable totalCount = 0; - for i in 0 .. arrSize - 1 { + for i in 0..arrSize - 1 { set totalCount = totalCount + counts[i]; if totalCount >= sampleSize / 2 { return i; diff --git a/katas/content/random_numbers/random_number/Solution.qs b/katas/content/random_numbers/random_number/Solution.qs index 4a59ceea01..c2ab01d20e 100644 --- a/katas/content/random_numbers/random_number/Solution.qs +++ b/katas/content/random_numbers/random_number/Solution.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; operation RandomNumberInRange(min : Int, max : Int) : Int { let nBits = BitSizeI(max - min); @@ -12,7 +12,7 @@ namespace Kata { operation RandomNBits(N : Int) : Int { mutable result = 0; - for i in 0 .. N - 1 { + for i in 0..N - 1 { set result = result * 2 + RandomBit(); } return result; diff --git a/katas/content/random_numbers/random_number/index.md b/katas/content/random_numbers/random_number/index.md index 9da603bd37..0d24514690 100644 --- a/katas/content/random_numbers/random_number/index.md +++ b/katas/content/random_numbers/random_number/index.md @@ -5,4 +5,4 @@ Two integers $min$ and $max$ ($0 \leq min \leq max \leq 2^{10}-1$). **Goal:** Generate a random number in the range $[min, max]$ with an equal probability of getting each of the numbers in this range. -> Q# namespace `Microsoft.Quantum.Math` includes useful function `BitSizeI` that calculates the number of bits in the binary representation of the given number. +> Q# namespace `Std.Math` includes useful function `BitSizeI` that calculates the number of bits in the binary representation of the given number. diff --git a/katas/content/random_numbers/weighted_random_bit/Solution.qs b/katas/content/random_numbers/weighted_random_bit/Solution.qs index a52a23459f..e63a6cac32 100644 --- a/katas/content/random_numbers/weighted_random_bit/Solution.qs +++ b/katas/content/random_numbers/weighted_random_bit/Solution.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; operation WeightedRandomBit(x : Double) : Int { let theta = 2.0 * ArcCos(Sqrt(x)); // or 2.0 * ArcSin(Sqrt(1.0 - x)); diff --git a/katas/content/random_numbers/weighted_random_bit/Verification.qs b/katas/content/random_numbers/weighted_random_bit/Verification.qs index 993147dd3e..6d2897434d 100644 --- a/katas/content/random_numbers/weighted_random_bit/Verification.qs +++ b/katas/content/random_numbers/weighted_random_bit/Verification.qs @@ -1,11 +1,11 @@ namespace Kata.Verification { - open Microsoft.Quantum.Math; - open Microsoft.Quantum.Convert; + import Std.Math.*; + import Std.Convert.*; @EntryPoint() operation CheckSolution() : Bool { for x in [0.0, 0.25, 0.5, 0.75, 1.0] { - Message($"Testing generating zero with {x*100.0}% probability..."); + Message($"Testing generating zero with {x * 100.0}% probability..."); let randomnessVerifier = () => CheckXPercentZero(() => Kata.WeightedRandomBit(x), x); let isCorrect = IsSufficientlyRandom(randomnessVerifier); if not isCorrect { @@ -23,7 +23,7 @@ namespace Kata.Verification { /// Random number generation operation to be tested. /// ## x /// Probability of generating zero - operation CheckXPercentZero (op : (Unit => Int), x : Double) : Int { + operation CheckXPercentZero(op : (Unit => Int), x : Double) : Int { mutable oneCount = 0; let nRuns = 1000; for N in 1..nRuns { diff --git a/katas/content/random_numbers/weighted_random_bit/index.md b/katas/content/random_numbers/weighted_random_bit/index.md index 319613e251..d8f586ad8b 100644 --- a/katas/content/random_numbers/weighted_random_bit/index.md +++ b/katas/content/random_numbers/weighted_random_bit/index.md @@ -7,4 +7,4 @@ A floating-point number $x$, $0 \le x \le 1$. **Goal:** Generate $0$ or $1$ with probability of $0$ equal to $x$ and probability of $1$ equal to $1 - x$. -> Q# namespace `Microsoft.Quantum.Math` includes useful functions `Sqrt`, `ArcCos`, and `ArcSin`. +> Q# namespace `Std.Math` includes useful functions `Sqrt`, `ArcCos`, and `ArcSin`. diff --git a/katas/content/single_qubit_gates/amplitude_change/Verification.qs b/katas/content/single_qubit_gates/amplitude_change/Verification.qs index 9c188af79f..3c4126aa0a 100644 --- a/katas/content/single_qubit_gates/amplitude_change/Verification.qs +++ b/katas/content/single_qubit_gates/amplitude_change/Verification.qs @@ -1,14 +1,14 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; - open Microsoft.Quantum.Convert; + import KatasUtils.*; + import Std.Math.*; + import Std.Convert.*; - operation AmplitudeChange (alpha : Double, q : Qubit) : Unit is Adj+Ctl { + operation AmplitudeChange(alpha : Double, q : Qubit) : Unit is Adj + Ctl { Ry(2.0 * alpha, q); } operation CheckSolution() : Bool { - for i in 0 .. 36 { + for i in 0..36 { let alpha = ((2.0 * PI()) * IntAsDouble(i)) / 36.0; let solution = register => Kata.AmplitudeChange(alpha, register[0]); let reference = register => AmplitudeChange(alpha, register[0]); @@ -18,7 +18,7 @@ namespace Kata.Verification { Message("Incorrect."); Message($"The solution was incorrect for the test case alpha = {DoubleAsStringWithPrecision(alpha, precision)}."); Message("Hint: examine the effect your solution has on the state 0.6|0〉 + 0.8|1〉 and compare it with the effect it " + - "is expected to have."); + "is expected to have."); ShowQuantumStateComparison(1, qs => Ry(ArcTan2(0.8, 0.6) * 2.0, qs[0]), solution, reference); return false; } diff --git a/katas/content/single_qubit_gates/basis_change/Verification.qs b/katas/content/single_qubit_gates/basis_change/Verification.qs index fd059b496f..528ac5c1b5 100644 --- a/katas/content/single_qubit_gates/basis_change/Verification.qs +++ b/katas/content/single_qubit_gates/basis_change/Verification.qs @@ -1,6 +1,6 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; + import KatasUtils.*; + import Std.Math.*; operation BasisChange(q : Qubit) : Unit is Adj + Ctl { H(q); diff --git a/katas/content/single_qubit_gates/complex_phase/Verification.qs b/katas/content/single_qubit_gates/complex_phase/Verification.qs index 605d6cfb8d..c637082a80 100644 --- a/katas/content/single_qubit_gates/complex_phase/Verification.qs +++ b/katas/content/single_qubit_gates/complex_phase/Verification.qs @@ -1,14 +1,14 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; - open Microsoft.Quantum.Convert; + import KatasUtils.*; + import Std.Math.*; + import Std.Convert.*; - operation PhaseChange (alpha : Double, q : Qubit) : Unit is Adj+Ctl { + operation PhaseChange(alpha : Double, q : Qubit) : Unit is Adj + Ctl { R1(alpha, q); } operation CheckSolution() : Bool { - for i in 0 .. 36 { + for i in 0..36 { let alpha = ((2.0 * PI()) * IntAsDouble(i)) / 36.0; let solution = register => Kata.PhaseChange(alpha, register[0]); let reference = register => PhaseChange(alpha, register[0]); @@ -18,7 +18,7 @@ namespace Kata.Verification { Message("Incorrect."); Message($"The solution was incorrect for the test case alpha = {DoubleAsStringWithPrecision(alpha, precision)}."); Message("Hint: examine the effect your solution has on the state 0.6|0〉 + 0.8|1〉 and compare it with the effect it " + - "is expected to have."); + "is expected to have."); ShowQuantumStateComparison(1, qs => Ry(ArcTan2(0.8, 0.6) * 2.0, qs[0]), solution, reference); return false; } @@ -27,4 +27,4 @@ namespace Kata.Verification { Message("Correct!"); true } -} \ No newline at end of file +} diff --git a/katas/content/single_qubit_gates/examples/PauliGates.qs b/katas/content/single_qubit_gates/examples/PauliGates.qs index 6f3082bdad..592cacd40b 100644 --- a/katas/content/single_qubit_gates/examples/PauliGates.qs +++ b/katas/content/single_qubit_gates/examples/PauliGates.qs @@ -1,10 +1,10 @@ namespace Demo { - // To use elements from a namespace, you need to use the `open` keyword to + // To use elements from a namespace, you need to use the `import` keyword to // access them. - open Microsoft.Quantum.Diagnostics; + import Std.Diagnostics.*; @EntryPoint() - operation PauliGatesUsage () : Unit { + operation PauliGatesUsage() : Unit { // This allocates a qubit for us to work with. use q = Qubit(); diff --git a/katas/content/single_qubit_gates/global_phase_i/Verification.qs b/katas/content/single_qubit_gates/global_phase_i/Verification.qs index dcce1d444a..9a2669676a 100644 --- a/katas/content/single_qubit_gates/global_phase_i/Verification.qs +++ b/katas/content/single_qubit_gates/global_phase_i/Verification.qs @@ -1,6 +1,6 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; + import KatasUtils.*; + import Std.Math.*; operation GlobalPhaseI(q : Qubit) : Unit is Adj + Ctl { X(q); diff --git a/katas/content/single_qubit_gates/global_phase_minusone/Verification.qs b/katas/content/single_qubit_gates/global_phase_minusone/Verification.qs index f0847017ec..ab3c6f250d 100644 --- a/katas/content/single_qubit_gates/global_phase_minusone/Verification.qs +++ b/katas/content/single_qubit_gates/global_phase_minusone/Verification.qs @@ -1,10 +1,10 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; - open Microsoft.Quantum.Convert; + import KatasUtils.*; + import Std.Math.*; + import Std.Convert.*; - operation GlobalPhaseChange (q : Qubit) : Unit is Adj + Ctl { + operation GlobalPhaseChange(q : Qubit) : Unit is Adj + Ctl { Z(q); X(q); Z(q); diff --git a/katas/content/single_qubit_gates/phase_i/SolutionB.qs b/katas/content/single_qubit_gates/phase_i/SolutionB.qs index d87e676c0a..24f1e25959 100644 --- a/katas/content/single_qubit_gates/phase_i/SolutionB.qs +++ b/katas/content/single_qubit_gates/phase_i/SolutionB.qs @@ -1,6 +1,6 @@ namespace Kata { - operation PhaseFlip (q : Qubit) : Unit is Adj + Ctl { - open Microsoft.Quantum.Math; + operation PhaseFlip(q : Qubit) : Unit is Adj + Ctl { + import Std.Math.*; R1(0.5 * PI(), q); } -} \ No newline at end of file +} diff --git a/katas/content/single_qubit_gates/phase_i/Verification.qs b/katas/content/single_qubit_gates/phase_i/Verification.qs index c3372666c4..e4a17995e4 100644 --- a/katas/content/single_qubit_gates/phase_i/Verification.qs +++ b/katas/content/single_qubit_gates/phase_i/Verification.qs @@ -1,9 +1,9 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; - open Microsoft.Quantum.Convert; + import KatasUtils.*; + import Std.Math.*; + import Std.Convert.*; - operation PhaseFlip (q : Qubit) : Unit is Adj + Ctl { + operation PhaseFlip(q : Qubit) : Unit is Adj + Ctl { S(q); } diff --git a/katas/content/single_qubit_gates/prepare_arbitrary_state/Placeholder.qs b/katas/content/single_qubit_gates/prepare_arbitrary_state/Placeholder.qs index 5cb92af1f8..799d79a928 100644 --- a/katas/content/single_qubit_gates/prepare_arbitrary_state/Placeholder.qs +++ b/katas/content/single_qubit_gates/prepare_arbitrary_state/Placeholder.qs @@ -1,9 +1,12 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; operation PrepareArbitraryState( - alpha : Double,beta : Double, theta : Double, q : Qubit) - : Unit is Adj+Ctl { + alpha : Double, + beta : Double, + theta : Double, + q : Qubit + ) : Unit is Adj + Ctl { // Implement your solution here... } diff --git a/katas/content/single_qubit_gates/prepare_arbitrary_state/Solution.qs b/katas/content/single_qubit_gates/prepare_arbitrary_state/Solution.qs index e97bcc56b4..24713486b9 100644 --- a/katas/content/single_qubit_gates/prepare_arbitrary_state/Solution.qs +++ b/katas/content/single_qubit_gates/prepare_arbitrary_state/Solution.qs @@ -1,7 +1,7 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; - operation PrepareArbitraryState (alpha : Double, beta : Double, theta : Double, q : Qubit) : Unit is Adj+Ctl { + operation PrepareArbitraryState(alpha : Double, beta : Double, theta : Double, q : Qubit) : Unit is Adj + Ctl { let phi = ArcTan2(beta, alpha); Ry(2.0 * phi, q); R1(theta, q); diff --git a/katas/content/single_qubit_gates/prepare_arbitrary_state/Verification.qs b/katas/content/single_qubit_gates/prepare_arbitrary_state/Verification.qs index fb020ef51d..94864860c9 100644 --- a/katas/content/single_qubit_gates/prepare_arbitrary_state/Verification.qs +++ b/katas/content/single_qubit_gates/prepare_arbitrary_state/Verification.qs @@ -1,16 +1,16 @@ namespace Kata.Verification { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; + import Std.Convert.*; + import KatasUtils.*; + import Std.Math.*; - operation PrepareArbitraryState (alpha : Double, beta : Double, theta : Double, q : Qubit) : Unit is Adj+Ctl { + operation PrepareArbitraryState(alpha : Double, beta : Double, theta : Double, q : Qubit) : Unit is Adj + Ctl { let phi = ArcTan2(beta, alpha); Ry(2.0 * phi, q); R1(theta, q); } operation CheckSolution() : Bool { - for i in 0 .. 10 { + for i in 0..10 { let i = IntAsDouble(i); let alpha = Cos(i); let beta = Sin(i); diff --git a/katas/content/single_qubit_gates/prepare_minus/Verification.qs b/katas/content/single_qubit_gates/prepare_minus/Verification.qs index a6f46732a1..ee76ba695a 100644 --- a/katas/content/single_qubit_gates/prepare_minus/Verification.qs +++ b/katas/content/single_qubit_gates/prepare_minus/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; operation PrepareMinus(q : Qubit) : Unit is Adj + Ctl { X(q); diff --git a/katas/content/single_qubit_gates/prepare_rotated_state/Placeholder.qs b/katas/content/single_qubit_gates/prepare_rotated_state/Placeholder.qs index c6c92aeb3d..c8239055c4 100644 --- a/katas/content/single_qubit_gates/prepare_rotated_state/Placeholder.qs +++ b/katas/content/single_qubit_gates/prepare_rotated_state/Placeholder.qs @@ -1,8 +1,7 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; - operation PrepareRotatedState(alpha : Double, beta : Double, q : Qubit) - : Unit is Adj + Ctl { + operation PrepareRotatedState(alpha : Double, beta : Double, q : Qubit) : Unit is Adj + Ctl { // Implement your solution here... } diff --git a/katas/content/single_qubit_gates/prepare_rotated_state/Solution.qs b/katas/content/single_qubit_gates/prepare_rotated_state/Solution.qs index 9f987a77c7..e19408a344 100644 --- a/katas/content/single_qubit_gates/prepare_rotated_state/Solution.qs +++ b/katas/content/single_qubit_gates/prepare_rotated_state/Solution.qs @@ -1,7 +1,7 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; - operation PrepareRotatedState (alpha : Double, beta : Double, q : Qubit) : Unit is Adj+Ctl { + operation PrepareRotatedState(alpha : Double, beta : Double, q : Qubit) : Unit is Adj + Ctl { let phi = ArcTan2(beta, alpha); Rx(2.0 * phi, q); } diff --git a/katas/content/single_qubit_gates/prepare_rotated_state/Verification.qs b/katas/content/single_qubit_gates/prepare_rotated_state/Verification.qs index d79ac988a0..454a9ede9d 100644 --- a/katas/content/single_qubit_gates/prepare_rotated_state/Verification.qs +++ b/katas/content/single_qubit_gates/prepare_rotated_state/Verification.qs @@ -1,15 +1,15 @@ namespace Kata.Verification { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; + import Std.Convert.*; + import KatasUtils.*; + import Std.Math.*; - operation PrepareRotatedState (alpha : Double, beta : Double, q : Qubit) : Unit is Adj+Ctl { + operation PrepareRotatedState(alpha : Double, beta : Double, q : Qubit) : Unit is Adj + Ctl { let phi = ArcTan2(beta, alpha); Rx(2.0 * phi, q); } operation CheckSolution() : Bool { - for i in 0 .. 10 { + for i in 0..10 { let i = IntAsDouble(i); let alpha = Cos(i); let beta = Sin(i); diff --git a/katas/content/single_qubit_gates/prepare_rotated_state/index.md b/katas/content/single_qubit_gates/prepare_rotated_state/index.md index d68844cfe6..503728dbbe 100644 --- a/katas/content/single_qubit_gates/prepare_rotated_state/index.md +++ b/katas/content/single_qubit_gates/prepare_rotated_state/index.md @@ -5,6 +5,6 @@ **Goal:** Use a rotation gate to transform the qubit into state $\alpha\ket{0} -i\beta\ket{1}$. -> You'll probably need functions from the `Microsoft.Quantum.Math` namespace, specifically ArcTan2. +> You'll probably need functions from the `Std.Math` namespace, specifically ArcTan2. > > You can assign variables in Q# by using the `let` keyword: `let num = 3;` or `let result = Function(input);` diff --git a/katas/content/single_qubit_gates/prepare_rotated_state/solution.md b/katas/content/single_qubit_gates/prepare_rotated_state/solution.md index a04c31b536..dfc800dbae 100644 --- a/katas/content/single_qubit_gates/prepare_rotated_state/solution.md +++ b/katas/content/single_qubit_gates/prepare_rotated_state/solution.md @@ -3,7 +3,7 @@ This is similar to the state you need. You just need to find an angle $\theta$ s Hence the required gate is $R_x(2\arctan\frac{\beta}{\alpha})$, which in matrix form is $\begin{bmatrix} \alpha & -i\beta \\ -i\beta & \alpha \end{bmatrix}$. This gate turns $\ket{0} = \begin{bmatrix} 1 \\ 0\end{bmatrix}$ into $\begin{bmatrix} \alpha & -i\beta \\ -i\beta & \alpha \end{bmatrix} \begin{bmatrix} 1 \\ 0\end{bmatrix} = \begin{bmatrix} \alpha \\ -i\beta \end{bmatrix} = \alpha\ket{0} -i\beta\ket{1}$. -> Trigonometric functions are available in Q# via the `Microsoft.Quantum.Math` namespace. In this case, you'll need ArcTan2. +> Trigonometric functions are available in Q# via the `Std.Math` namespace. In this case, you'll need ArcTan2. @[solution]({ "id": "single_qubit_gates__prepare_rotated_state_solution", diff --git a/katas/content/single_qubit_gates/sign_flip/Verification.qs b/katas/content/single_qubit_gates/sign_flip/Verification.qs index bbaa1c80f5..14a22db198 100644 --- a/katas/content/single_qubit_gates/sign_flip/Verification.qs +++ b/katas/content/single_qubit_gates/sign_flip/Verification.qs @@ -1,6 +1,6 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; + import KatasUtils.*; + import Std.Math.*; operation SignFlip(q : Qubit) : Unit is Adj + Ctl { Z(q); diff --git a/katas/content/single_qubit_gates/sign_flip_on_zero/Verification.qs b/katas/content/single_qubit_gates/sign_flip_on_zero/Verification.qs index 9fad5a7efd..432ed1c5a9 100644 --- a/katas/content/single_qubit_gates/sign_flip_on_zero/Verification.qs +++ b/katas/content/single_qubit_gates/sign_flip_on_zero/Verification.qs @@ -1,6 +1,6 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; + import KatasUtils.*; + import Std.Math.*; operation SignFlipOnZero(q : Qubit) : Unit is Adj + Ctl { X(q); diff --git a/katas/content/single_qubit_gates/state_flip/Verification.qs b/katas/content/single_qubit_gates/state_flip/Verification.qs index 065703f3a1..958bc2f1fa 100644 --- a/katas/content/single_qubit_gates/state_flip/Verification.qs +++ b/katas/content/single_qubit_gates/state_flip/Verification.qs @@ -1,6 +1,6 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; + import KatasUtils.*; + import Std.Math.*; operation StateFlip(q : Qubit) : Unit is Adj + Ctl { X(q); @@ -22,4 +22,4 @@ namespace Kata.Verification { } isCorrect } -} \ No newline at end of file +} diff --git a/katas/content/single_qubit_gates/three_quarters_pi_phase/Verification.qs b/katas/content/single_qubit_gates/three_quarters_pi_phase/Verification.qs index 8ba8fe35a3..b2f420e114 100644 --- a/katas/content/single_qubit_gates/three_quarters_pi_phase/Verification.qs +++ b/katas/content/single_qubit_gates/three_quarters_pi_phase/Verification.qs @@ -1,6 +1,6 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; + import KatasUtils.*; + import Std.Math.*; operation ThreeQuartersPiPhase(q : Qubit) : Unit is Adj + Ctl { S(q); diff --git a/katas/content/single_qubit_gates/y_gate/Verification.qs b/katas/content/single_qubit_gates/y_gate/Verification.qs index 7bb17f8862..198e1f0a31 100644 --- a/katas/content/single_qubit_gates/y_gate/Verification.qs +++ b/katas/content/single_qubit_gates/y_gate/Verification.qs @@ -1,6 +1,6 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Math; + import KatasUtils.*; + import Std.Math.*; operation ApplyY(q : Qubit) : Unit is Adj + Ctl { Y(q); diff --git a/katas/content/single_qubit_measurements/a_b_basis_measurements/Verification.qs b/katas/content/single_qubit_measurements/a_b_basis_measurements/Verification.qs index 4678230500..db3a816cdc 100644 --- a/katas/content/single_qubit_measurements/a_b_basis_measurements/Verification.qs +++ b/katas/content/single_qubit_measurements/a_b_basis_measurements/Verification.qs @@ -1,12 +1,12 @@ namespace Kata.Verification { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Math; - open Microsoft.Quantum.Katas; + import Std.Convert.*; + import Std.Math.*; + import KatasUtils.*; // Measure state in {|A❭, |B❭} basis // |A⟩ = cos(alpha) * |0⟩ - i sin(alpha) * |1⟩, // |B⟩ = - i sin(alpha) * |0⟩ + cos(alpha) * |1⟩. - operation StatePrep_IsQubitA (alpha : Double, q : Qubit, state : Int) : Unit is Adj { + operation StatePrep_IsQubitA(alpha : Double, q : Qubit, state : Int) : Unit is Adj { if state == 0 { // convert |0⟩ to |B⟩ X(q); @@ -19,13 +19,14 @@ namespace Kata.Verification { // We can use the StatePrep_IsQubitA operation for the testing operation CheckSolution() : Bool { - for i in 0 .. 10 { + for i in 0..10 { let alpha = (PI() * IntAsDouble(i)) / 10.0; let isCorrect = DistinguishTwoStates_SingleQubit( StatePrep_IsQubitA(alpha, _, _), q => Kata.MeasureInABBasis(alpha, q) == Zero, [$"|B⟩=(-i sin({i}π/10)|0⟩ + cos({i}π/10)|1⟩)", $"|A⟩=(cos({i}π/10)|0⟩ + i sin({i}π/10)|1⟩)"], - true); + true + ); if not isCorrect { let precision = 3; Message($"Test fails for alpha={DoubleAsStringWithPrecision(alpha, precision)}"); diff --git a/katas/content/single_qubit_measurements/distinguish_0_and_1/Verification.qs b/katas/content/single_qubit_measurements/distinguish_0_and_1/Verification.qs index ebb1b59fe8..97727f747f 100644 --- a/katas/content/single_qubit_measurements/distinguish_0_and_1/Verification.qs +++ b/katas/content/single_qubit_measurements/distinguish_0_and_1/Verification.qs @@ -1,8 +1,8 @@ namespace Kata.Verification { - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Katas; + import Std.Diagnostics.*; + import KatasUtils.*; - operation StatePrep_IsQubitZero (q : Qubit, state : Int) : Unit is Adj { + operation StatePrep_IsQubitZero(q : Qubit, state : Int) : Unit is Adj { if state == 0 { // convert |0⟩ to |1⟩ X(q); @@ -15,7 +15,8 @@ namespace Kata.Verification { StatePrep_IsQubitZero, Kata.IsQubitZero, ["|1⟩", "|0⟩"], - false); + false + ); if isCorrect { Message("Correct!"); } else { diff --git a/katas/content/single_qubit_measurements/distinguish_orthogonal_states_1/Placeholder.qs b/katas/content/single_qubit_measurements/distinguish_orthogonal_states_1/Placeholder.qs index 4b654d6e4a..69ec3ba2f1 100644 --- a/katas/content/single_qubit_measurements/distinguish_orthogonal_states_1/Placeholder.qs +++ b/katas/content/single_qubit_measurements/distinguish_orthogonal_states_1/Placeholder.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; operation IsQubitPsiPlus(q : Qubit) : Bool { // Implement your solution here... diff --git a/katas/content/single_qubit_measurements/distinguish_orthogonal_states_1/Solution.qs b/katas/content/single_qubit_measurements/distinguish_orthogonal_states_1/Solution.qs index 5ed24fdb54..c10c506bbf 100644 --- a/katas/content/single_qubit_measurements/distinguish_orthogonal_states_1/Solution.qs +++ b/katas/content/single_qubit_measurements/distinguish_orthogonal_states_1/Solution.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Math; + import Std.Math.*; operation IsQubitPsiPlus(q : Qubit) : Bool { Ry(-2.0 * ArcTan2(0.8, 0.6), q); diff --git a/katas/content/single_qubit_measurements/distinguish_orthogonal_states_1/Verification.qs b/katas/content/single_qubit_measurements/distinguish_orthogonal_states_1/Verification.qs index a3c3102fdf..7fda4670d5 100644 --- a/katas/content/single_qubit_measurements/distinguish_orthogonal_states_1/Verification.qs +++ b/katas/content/single_qubit_measurements/distinguish_orthogonal_states_1/Verification.qs @@ -1,6 +1,6 @@ namespace Kata.Verification { - open Microsoft.Quantum.Math; - open Microsoft.Quantum.Katas; + import Std.Math.*; + import KatasUtils.*; // Distinguish specific orthogonal states // |ψ₊⟩ = 0.6 * |0⟩ + 0.8 * |1⟩, @@ -21,7 +21,8 @@ namespace Kata.Verification { StatePrep_IsQubitPsiPlus, Kata.IsQubitPsiPlus, ["|ψ₋⟩", "|ψ₊⟩"], - false); + false + ); if isCorrect { Message("Correct!"); } else { diff --git a/katas/content/single_qubit_measurements/distinguish_orthogonal_states_2/Verification.qs b/katas/content/single_qubit_measurements/distinguish_orthogonal_states_2/Verification.qs index 536b9654ee..ae0744b38d 100644 --- a/katas/content/single_qubit_measurements/distinguish_orthogonal_states_2/Verification.qs +++ b/katas/content/single_qubit_measurements/distinguish_orthogonal_states_2/Verification.qs @@ -1,7 +1,7 @@ namespace Kata.Verification { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Math; - open Microsoft.Quantum.Katas; + import Std.Convert.*; + import Std.Math.*; + import KatasUtils.*; // Distinguish states |A❭ and |B❭ // |A⟩ = cos(alpha) * |0⟩ - i sin(alpha) * |1⟩, @@ -19,13 +19,14 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { - for i in 0 .. 10 { + for i in 0..10 { let alpha = (PI() * IntAsDouble(i)) / 10.0; let isCorrect = DistinguishTwoStates_SingleQubit( StatePrep_IsQubitA(alpha, _, _), Kata.IsQubitA(alpha, _), [$"|B⟩ = -i sin({i}π/10)|0⟩ + cos({i}π/10)|1⟩", $"|A⟩ = cos({i}π/10)|0⟩ + i sin({i}π/10)|1⟩"], - false); + false + ); if not isCorrect { Message("Incorrect."); return false; diff --git a/katas/content/single_qubit_measurements/distinguish_plus_and_minus/Verification.qs b/katas/content/single_qubit_measurements/distinguish_plus_and_minus/Verification.qs index 5939a5ceb7..0cae67b239 100644 --- a/katas/content/single_qubit_measurements/distinguish_plus_and_minus/Verification.qs +++ b/katas/content/single_qubit_measurements/distinguish_plus_and_minus/Verification.qs @@ -1,8 +1,8 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; // Distinguish |+❭ and |-❭ using Measure operation - operation StatePrep_IsQubitMinus (q : Qubit, state : Int) : Unit is Adj { + operation StatePrep_IsQubitMinus(q : Qubit, state : Int) : Unit is Adj { if state == 1 { // convert |0⟩ to |-⟩ X(q); @@ -19,7 +19,8 @@ namespace Kata.Verification { StatePrep_IsQubitMinus, Kata.IsQubitMinus, ["|+⟩", "|-⟩"], - false); + false + ); if isCorrect { Message("Correct!"); } else { diff --git a/katas/content/single_qubit_measurements/implementing_measurement/Example.qs b/katas/content/single_qubit_measurements/implementing_measurement/Example.qs index dfe425c7ef..bd9837f367 100644 --- a/katas/content/single_qubit_measurements/implementing_measurement/Example.qs +++ b/katas/content/single_qubit_measurements/implementing_measurement/Example.qs @@ -1,6 +1,6 @@ namespace Kata { - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Math; + import Std.Diagnostics.*; + import Std.Math.*; @EntryPoint() operation SimpleMeasurementDemo() : Unit { diff --git a/katas/content/single_qubit_measurements/measurement_statistics/Example.qs b/katas/content/single_qubit_measurements/measurement_statistics/Example.qs index 310accbe44..20ddd491ac 100644 --- a/katas/content/single_qubit_measurements/measurement_statistics/Example.qs +++ b/katas/content/single_qubit_measurements/measurement_statistics/Example.qs @@ -1,13 +1,13 @@ namespace Kata { - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Math; + import Std.Diagnostics.*; + import Std.Math.*; @EntryPoint() operation MeasumentStatisticsDemo() : Unit { mutable countZero = 0; let numRuns = 100; use q = Qubit(); - for i in 1 .. numRuns { + for i in 1..numRuns { // Prepare the qubit in the superposition state |𝜓❭ = 0.6 |0❭ + 0.8 |1❭ Ry(2.0 * ArcTan2(0.8, 0.6), q); diff --git a/katas/content/solving_graph_coloring/Common.qs b/katas/content/solving_graph_coloring/Common.qs index d49f0dc0db..e6a29f85c1 100644 --- a/katas/content/solving_graph_coloring/Common.qs +++ b/katas/content/solving_graph_coloring/Common.qs @@ -1,8 +1,8 @@ namespace Kata.Verification { - open Microsoft.Quantum.Arrays; - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Katas; + import Std.Arrays.*; + import Std.Convert.*; + import Std.Diagnostics.*; + import KatasUtils.*; // Hardcoded graphs used for testing the vertex coloring problem: // - trivial graph with zero edges @@ -12,18 +12,20 @@ namespace Kata.Verification { // - regular-ish graph with 5 vertices (3-colorable, as shown at https://en.wikipedia.org/wiki/File:3-coloringEx.svg without one vertex) // - 6-vertex graph from https://en.wikipedia.org/wiki/File:3-coloringEx.svg function ExampleGraphs() : (Int, (Int, Int)[])[] { - return [(3, []), - (4, [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]), - (5, [(4, 0), (2, 1), (3, 1), (3, 2)]), - (5, [(0, 1), (1, 2), (1, 3), (3, 2), (4, 2), (3, 4)]), - (5, [(0, 1), (0, 2), (0, 4), (1, 2), (1, 3), (2, 3), (2, 4), (3, 4)]), - (6, [(0, 1), (0, 2), (0, 4), (0, 5), (1, 2), (1, 3), (1, 5), (2, 3), (2, 4), (3, 4), (3, 5), (4, 5)])]; - // Graphs with 6+ vertices can take several minutes to be processed; + return [ + (3, []), + (4, [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]), + (5, [(4, 0), (2, 1), (3, 1), (3, 2)]), + (5, [(0, 1), (1, 2), (1, 3), (3, 2), (4, 2), (3, 4)]), + (5, [(0, 1), (0, 2), (0, 4), (1, 2), (1, 3), (2, 3), (2, 4), (3, 4)]), + (6, [(0, 1), (0, 2), (0, 4), (0, 5), (1, 2), (1, 3), (1, 5), (2, 3), (2, 4), (3, 4), (3, 5), (4, 5)]) + ]; + // Graphs with 6+ vertices can take several minutes to be processed; // in the interest of keeping test runtime reasonable we're limiting most of the testing to graphs with 5 vertices or fewer. } - function IsVertexColoringValid_Reference (V : Int, edges: (Int, Int)[], colors: Int[]) : Bool { + function IsVertexColoringValid_Reference(V : Int, edges : (Int, Int)[], colors : Int[]) : Bool { for (start, end) in edges { if colors[start] == colors[end] { return false; @@ -41,10 +43,10 @@ namespace Kata.Verification { // Helper function specific to Graph Coloring kata. - operation CheckOracleRecognizesColoring ( + operation CheckOracleRecognizesColoring( V : Int, edges : (Int, Int)[], - oracle : (Int, (Int, Int)[],Qubit[], Qubit) => Unit, + oracle : (Int, (Int, Int)[], Qubit[], Qubit) => Unit, classicalFunction : (Int, (Int, Int)[], Int[]) -> Bool ) : Bool { // Message($"Testing V = {V}, edges = {edges}"); @@ -52,7 +54,7 @@ namespace Kata.Verification { use (coloringRegister, target) = (Qubit[N], Qubit()); // Try all possible colorings of 4 colors on V vertices and check if they are calculated correctly. // Hack: fix the color of the first vertex, since all colorings are agnostic to the specific colors used. - for k in 0 .. (1 <<< (N - 2)) - 1 { + for k in 0..(1 <<< (N - 2)) - 1 { // Prepare k-th coloring let binary = [false, false] + IntAsBoolArray(k, N - 2); ApplyPauliFromBitString(PauliX, true, binary, coloringRegister); @@ -87,7 +89,7 @@ namespace Kata.Verification { true } - function IsWeakColoringValid_OneVertex_Reference (V : Int, edges: (Int, Int)[], colors: Int[], vertex : Int) : Bool { + function IsWeakColoringValid_OneVertex_Reference(V : Int, edges : (Int, Int)[], colors : Int[], vertex : Int) : Bool { mutable neighborCount = 0; mutable hasDifferentNeighbor = false; @@ -103,8 +105,8 @@ namespace Kata.Verification { return neighborCount == 0 or hasDifferentNeighbor; } - function IsWeakColoringValid_Reference (V : Int, edges: (Int, Int)[], colors: Int[]) : Bool { - for v in 0 .. V - 1 { + function IsWeakColoringValid_Reference(V : Int, edges : (Int, Int)[], colors : Int[]) : Bool { + for v in 0..V - 1 { if not IsWeakColoringValid_OneVertex_Reference(V, edges, colors, v) { return false; } @@ -113,4 +115,4 @@ namespace Kata.Verification { return true; } -} \ No newline at end of file +} diff --git a/katas/content/solving_graph_coloring/color_equality/Verification.qs b/katas/content/solving_graph_coloring/color_equality/Verification.qs index 57fe04370f..eaeb8032de 100644 --- a/katas/content/solving_graph_coloring/color_equality/Verification.qs +++ b/katas/content/solving_graph_coloring/color_equality/Verification.qs @@ -1,6 +1,6 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Arrays; + import KatasUtils.*; + import Std.Arrays.*; function F_ColorEquality(args : Bool[]) : Bool { // Check that the first half equals the second half diff --git a/katas/content/solving_graph_coloring/examples/SolvingGraphColoringWithGroverDemo.qs b/katas/content/solving_graph_coloring/examples/SolvingGraphColoringWithGroverDemo.qs index 41d08ffd7a..803ea2be88 100644 --- a/katas/content/solving_graph_coloring/examples/SolvingGraphColoringWithGroverDemo.qs +++ b/katas/content/solving_graph_coloring/examples/SolvingGraphColoringWithGroverDemo.qs @@ -1,8 +1,8 @@ namespace Kata { - open Microsoft.Quantum.Arrays; - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Math; + import Std.Arrays.*; + import Std.Convert.*; + import Std.Diagnostics.*; + import Std.Math.*; @EntryPoint() operation SolvingGraphColoringWithGroverDemo() : Unit { @@ -11,9 +11,9 @@ namespace Kata { // The 0 -- 1 -- 2 graph from the examples let edges = [(0, 1), (1, 2)]; let markingOracle = Oracle_VertexColoring(V, edges, _, _); - for iterations in 0 .. 9 { + for iterations in 0..9 { mutable success = 0; - for _ in 1 .. 100 { + for _ in 1..100 { let res = GroversSearch(2 * V, markingOracle, iterations); // Convert measurement results to integers let colorPartitions = Chunks(2, res); @@ -28,7 +28,7 @@ namespace Kata { operation GroversSearch( n : Int, - markingOracle : (Qubit[], Qubit) => Unit is Adj + Ctl, + markingOracle : (Qubit[], Qubit) => Unit is Adj + Ctl, iterations : Int ) : Bool[] { use qs = Qubit[n]; @@ -43,7 +43,7 @@ namespace Kata { meanStatePrep(qs); // Do Grover's iterations. - for _ in 1 .. iterations { + for _ in 1..iterations { // Apply the phase oracle. phaseOracle(qs); @@ -57,8 +57,8 @@ namespace Kata { operation ApplyMarkingOracleAsPhaseOracle( markingOracle : (Qubit[], Qubit) => Unit is Adj + Ctl, - qubits : Qubit[]) - : Unit is Adj + Ctl { + qubits : Qubit[] + ) : Unit is Adj + Ctl { use minus = Qubit(); within { X(minus); @@ -70,8 +70,8 @@ namespace Kata { operation ReflectionAboutState( qs : Qubit[], - statePrep : Qubit[] => Unit is Adj + Ctl) - : Unit is Adj + Ctl { + statePrep : Qubit[] => Unit is Adj + Ctl + ) : Unit is Adj + Ctl { within { Adjoint statePrep(qs); } apply { @@ -83,19 +83,22 @@ namespace Kata { within { ApplyToEachA(X, qs); } apply { - Controlled Z(qs[1 ...], qs[0]); + Controlled Z(qs[1...], qs[0]); } R(PauliI, 2.0 * PI(), qs[0]); } - operation Oracle_VertexColoring(V : Int, edges: (Int, Int)[], x : Qubit[], y : Qubit) : Unit is Adj + Ctl { + operation Oracle_VertexColoring(V : Int, edges : (Int, Int)[], x : Qubit[], y : Qubit) : Unit is Adj + Ctl { let edgesNumber = Length(edges); use conflicts = Qubit[edgesNumber]; within { - for i in 0 .. edgesNumber - 1 { + for i in 0..edgesNumber - 1 { let (v0, v1) = edges[i]; - Oracle_ColorEquality(x[2 * v0 .. 2 * v0 + 1], - x[2 * v1 .. 2 * v1 + 1], conflicts[i]); + Oracle_ColorEquality( + x[2 * v0 .. 2 * v0 + 1], + x[2 * v1 .. 2 * v1 + 1], + conflicts[i] + ); } } apply { ApplyControlledOnInt(0, X, conflicts, y); @@ -112,7 +115,7 @@ namespace Kata { } } - function IsVertexColoringValid(V : Int, edges: (Int, Int)[], colors: Int[]) : Bool { + function IsVertexColoringValid(V : Int, edges : (Int, Int)[], colors : Int[]) : Bool { for (v0, v1) in edges { if colors[v0] == colors[v1] { return false; @@ -120,4 +123,4 @@ namespace Kata { } return true; } -} \ No newline at end of file +} diff --git a/katas/content/solving_graph_coloring/read_coloring/Solution.qs b/katas/content/solving_graph_coloring/read_coloring/Solution.qs index 2989bc3371..ebc28c4d30 100644 --- a/katas/content/solving_graph_coloring/read_coloring/Solution.qs +++ b/katas/content/solving_graph_coloring/read_coloring/Solution.qs @@ -1,6 +1,6 @@ namespace Kata { - open Microsoft.Quantum.Arrays; - open Microsoft.Quantum.Convert; + import Std.Arrays.*; + import Std.Convert.*; operation ReadColoring(nBits : Int, qs : Qubit[]) : Int[] { let colorPartitions = Chunks(nBits, qs); diff --git a/katas/content/solving_graph_coloring/read_coloring/Verification.qs b/katas/content/solving_graph_coloring/read_coloring/Verification.qs index d460bb15c3..703850ebb5 100644 --- a/katas/content/solving_graph_coloring/read_coloring/Verification.qs +++ b/katas/content/solving_graph_coloring/read_coloring/Verification.qs @@ -1,8 +1,8 @@ namespace Kata.Verification { - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Arrays; - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Katas; + import Std.Diagnostics.*; + import Std.Arrays.*; + import Std.Convert.*; + import KatasUtils.*; @EntryPoint() operation CheckSolution() : Bool { @@ -38,7 +38,7 @@ namespace Kata.Verification { } for (expected, actual) in Zipped(expectedColors, result) { if expected != actual { - Message($"Unexpected colors for V = {V}, nBits = {nBits}, " + + Message($"Unexpected colors for V = {V}, nBits = {nBits}, " + $"state = {BoolArrayAsKetState(binaryState)} : expected {expectedColors}, got {result}"); return false; } diff --git a/katas/content/solving_graph_coloring/vertex_coloring/Verification.qs b/katas/content/solving_graph_coloring/vertex_coloring/Verification.qs index f80c7aa6fb..6c5167ff44 100644 --- a/katas/content/solving_graph_coloring/vertex_coloring/Verification.qs +++ b/katas/content/solving_graph_coloring/vertex_coloring/Verification.qs @@ -1,6 +1,6 @@ namespace Kata.Verification { - open Microsoft.Quantum.Arrays; - open Microsoft.Quantum.Katas; + import Std.Arrays.*; + import KatasUtils.*; @EntryPoint() operation CheckSolution() : Bool { diff --git a/katas/content/solving_graph_coloring/vertex_coloring_classical/Verification.qs b/katas/content/solving_graph_coloring/vertex_coloring_classical/Verification.qs index 6f68606224..f4d6d52e73 100644 --- a/katas/content/solving_graph_coloring/vertex_coloring_classical/Verification.qs +++ b/katas/content/solving_graph_coloring/vertex_coloring_classical/Verification.qs @@ -1,10 +1,10 @@ namespace Kata.Verification { - open Microsoft.Quantum.Arrays; - open Microsoft.Quantum.Katas; + import Std.Arrays.*; + import KatasUtils.*; @EntryPoint() operation CheckSolution() : Bool { - let testGraphs = ExampleGraphs()[0 .. 4]; + let testGraphs = ExampleGraphs()[0..4]; let testColorings = [ [([0, 0, 0], true), ([2, 1, 3], true)], [([0, 2, 1, 3], true), ([3, 0, 1, 2], true), ([0, 2, 1, 0], false)], diff --git a/katas/content/solving_graph_coloring/weak_coloring/Placeholder.qs b/katas/content/solving_graph_coloring/weak_coloring/Placeholder.qs index 89fdd56464..519e208fad 100644 --- a/katas/content/solving_graph_coloring/weak_coloring/Placeholder.qs +++ b/katas/content/solving_graph_coloring/weak_coloring/Placeholder.qs @@ -1,8 +1,11 @@ namespace Kata { - open Microsoft.Quantum.Arrays; + import Std.Arrays.*; operation Oracle_WeakColoring( - V : Int, edges: (Int, Int)[], x : Qubit[], y : Qubit + V : Int, + edges : (Int, Int)[], + x : Qubit[], + y : Qubit ) : Unit is Adj + Ctl { // Implement your solution here... @@ -10,16 +13,22 @@ namespace Kata { // You might find these helper operations from earlier tasks useful. operation Oracle_WeakColoring_OneVertex( - V : Int, edges: (Int, Int)[], x : Qubit[], y : Qubit, vertex : Int + V : Int, + edges : (Int, Int)[], + x : Qubit[], + y : Qubit, + vertex : Int ) : Unit is Adj + Ctl { let neighborEdges = Filtered((a, b) -> a == vertex or b == vertex, edges); let nNeighbors = Length(neighborEdges); use sameColorChecks = Qubit[nNeighbors]; within { for ((a, b), checkQubit) in Zipped(neighborEdges, sameColorChecks) { - Oracle_ColorEquality(x[a * 2 .. a * 2 + 1], - x[b * 2 .. b * 2 + 1], - checkQubit); + Oracle_ColorEquality( + x[a * 2 .. a * 2 + 1], + x[b * 2 .. b * 2 + 1], + checkQubit + ); } } apply { X(y); diff --git a/katas/content/solving_graph_coloring/weak_coloring/Solution.qs b/katas/content/solving_graph_coloring/weak_coloring/Solution.qs index ac203c86db..6c4906e5ba 100644 --- a/katas/content/solving_graph_coloring/weak_coloring/Solution.qs +++ b/katas/content/solving_graph_coloring/weak_coloring/Solution.qs @@ -1,12 +1,15 @@ namespace Kata { - open Microsoft.Quantum.Arrays; + import Std.Arrays.*; operation Oracle_WeakColoring( - V : Int, edges: (Int, Int)[], x : Qubit[], y : Qubit + V : Int, + edges : (Int, Int)[], + x : Qubit[], + y : Qubit ) : Unit is Adj + Ctl { use vertexQubits = Qubit[V]; within { - for v in 0 .. V - 1 { + for v in 0..V - 1 { Oracle_WeakColoring_OneVertex(V, edges, x, vertexQubits[v], v); } } apply { @@ -16,16 +19,22 @@ namespace Kata { // You might find these helper operations from earlier tasks useful. operation Oracle_WeakColoring_OneVertex( - V : Int, edges: (Int, Int)[], x : Qubit[], y : Qubit, vertex : Int + V : Int, + edges : (Int, Int)[], + x : Qubit[], + y : Qubit, + vertex : Int ) : Unit is Adj + Ctl { let neighborEdges = Filtered((a, b) -> a == vertex or b == vertex, edges); let nNeighbors = Length(neighborEdges); use sameColorChecks = Qubit[nNeighbors]; within { for ((a, b), checkQubit) in Zipped(neighborEdges, sameColorChecks) { - Oracle_ColorEquality(x[a * 2 .. a * 2 + 1], - x[b * 2 .. b * 2 + 1], - checkQubit); + Oracle_ColorEquality( + x[a * 2 .. a * 2 + 1], + x[b * 2 .. b * 2 + 1], + checkQubit + ); } } apply { X(y); diff --git a/katas/content/solving_graph_coloring/weak_coloring/Verification.qs b/katas/content/solving_graph_coloring/weak_coloring/Verification.qs index 1861edf2e9..1a3977bf91 100644 --- a/katas/content/solving_graph_coloring/weak_coloring/Verification.qs +++ b/katas/content/solving_graph_coloring/weak_coloring/Verification.qs @@ -1,13 +1,11 @@ namespace Kata.Verification { - open Microsoft.Quantum.Arrays; - open Microsoft.Quantum.Katas; + import Std.Arrays.*; + import KatasUtils.*; @EntryPoint() operation CheckSolution() : Bool { for (V, edges) in Most(ExampleGraphs()) { - if not CheckOracleRecognizesColoring(V, edges, - Kata.Oracle_WeakColoring, IsWeakColoringValid_Reference - ) { + if not CheckOracleRecognizesColoring(V, edges, Kata.Oracle_WeakColoring, IsWeakColoringValid_Reference) { return false; } } diff --git a/katas/content/solving_graph_coloring/weak_coloring_classical/Verification.qs b/katas/content/solving_graph_coloring/weak_coloring_classical/Verification.qs index c68d4e7a40..f86da756a6 100644 --- a/katas/content/solving_graph_coloring/weak_coloring_classical/Verification.qs +++ b/katas/content/solving_graph_coloring/weak_coloring_classical/Verification.qs @@ -1,10 +1,10 @@ namespace Kata.Verification { - open Microsoft.Quantum.Arrays; - open Microsoft.Quantum.Katas; + import Std.Arrays.*; + import KatasUtils.*; @EntryPoint() operation CheckSolution() : Bool { - let testGraphs = ExampleGraphs()[0 .. 4]; + let testGraphs = ExampleGraphs()[0..4]; let testColorings = [ // Every coloring would pass on a disconnected graph of 3 vertices [([0, 0, 0], true), ([2, 1, 3], true)], diff --git a/katas/content/solving_graph_coloring/weak_coloring_one_vertex/Solution.qs b/katas/content/solving_graph_coloring/weak_coloring_one_vertex/Solution.qs index a801a73552..65a477ce08 100644 --- a/katas/content/solving_graph_coloring/weak_coloring_one_vertex/Solution.qs +++ b/katas/content/solving_graph_coloring/weak_coloring_one_vertex/Solution.qs @@ -1,17 +1,23 @@ namespace Kata { - open Microsoft.Quantum.Arrays; + import Std.Arrays.*; operation Oracle_WeakColoring_OneVertex( - V : Int, edges: (Int, Int)[], x : Qubit[], y : Qubit, vertex : Int + V : Int, + edges : (Int, Int)[], + x : Qubit[], + y : Qubit, + vertex : Int ) : Unit is Adj + Ctl { let neighborEdges = Filtered((a, b) -> a == vertex or b == vertex, edges); let nNeighbors = Length(neighborEdges); use sameColorChecks = Qubit[nNeighbors]; within { for ((a, b), checkQubit) in Zipped(neighborEdges, sameColorChecks) { - Oracle_ColorEquality(x[a * 2 .. a * 2 + 1], - x[b * 2 .. b * 2 + 1], - checkQubit); + Oracle_ColorEquality( + x[a * 2 .. a * 2 + 1], + x[b * 2 .. b * 2 + 1], + checkQubit + ); } } apply { X(y); diff --git a/katas/content/solving_graph_coloring/weak_coloring_one_vertex/Verification.qs b/katas/content/solving_graph_coloring/weak_coloring_one_vertex/Verification.qs index ca06b21f95..9284beec13 100644 --- a/katas/content/solving_graph_coloring/weak_coloring_one_vertex/Verification.qs +++ b/katas/content/solving_graph_coloring/weak_coloring_one_vertex/Verification.qs @@ -1,13 +1,15 @@ namespace Kata.Verification { - open Microsoft.Quantum.Arrays; - open Microsoft.Quantum.Katas; + import Std.Arrays.*; + import KatasUtils.*; @EntryPoint() operation CheckSolution() : Bool { for (V, edges) in Most(ExampleGraphs()) { - for vertex in 0 .. V - 1 { - if not CheckOracleRecognizesColoring(V, edges, - Kata.Oracle_WeakColoring_OneVertex(_, _, _, _, vertex), + for vertex in 0..V - 1 { + if not CheckOracleRecognizesColoring( + V, + edges, + Kata.Oracle_WeakColoring_OneVertex(_, _, _, _, vertex), IsWeakColoringValid_OneVertex_Reference(_, _, _, vertex) ) { Message($"Testing vertex {vertex}"); diff --git a/katas/content/solving_sat/Common.qs b/katas/content/solving_sat/Common.qs index bfd49a81cf..863513cf62 100644 --- a/katas/content/solving_sat/Common.qs +++ b/katas/content/solving_sat/Common.qs @@ -1,42 +1,42 @@ namespace Kata.Verification { - open Microsoft.Quantum.Random; + import Std.Random.*; // Helper functions to pretty-print SAT formulas - function SATVariableAsString (var : (Int, Bool)) : String { + function SATVariableAsString(var : (Int, Bool)) : String { let (index, positive) = var; return (positive ? "" | "¬") + $"x{index}"; } - function SATClauseAsString (clause : (Int, Bool)[]) : String { + function SATClauseAsString(clause : (Int, Bool)[]) : String { mutable ret = SATVariableAsString(clause[0]); - for ind in 1 .. Length(clause) - 1 { + for ind in 1..Length(clause) - 1 { set ret = ret + " ∨ " + SATVariableAsString(clause[ind]); } return ret; } - function SATFormulaAsString (formula : (Int, Bool)[][]) : String { + function SATFormulaAsString(formula : (Int, Bool)[][]) : String { mutable ret = "(" + SATClauseAsString(formula[0]) + ")"; - for ind in 1 .. Length(formula) - 1 { + for ind in 1..Length(formula) - 1 { set ret = ret + " ∧ (" + SATClauseAsString(formula[ind]) + ")"; } return ret; } // Helper operations to generate random SAT formulas - operation Generate_SAT_Clause (nVar : Int, nTerms : Int) : (Int, Bool)[] { + operation Generate_SAT_Clause(nVar : Int, nTerms : Int) : (Int, Bool)[] { // number of terms in clause is either given or (if nTerms <= 0) chosen randomly mutable nVarInClause = (nTerms > 0) ? nTerms | DrawRandomInt(1, 4); if nVarInClause > nVar { set nVarInClause = nVar; } - + mutable clause = [(0, false), size = nVarInClause]; mutable usedVariables = [false, size = nVar]; // Make sure variables in the clause are distinct - for k in 0 .. nVarInClause - 1 { + for k in 0..nVarInClause - 1 { mutable nextInd = -1; - repeat { + repeat { set nextInd = DrawRandomInt(0, nVar - 1); } until (not usedVariables[nextInd]) fixup {} @@ -46,12 +46,12 @@ namespace Kata.Verification { return clause; } - operation GenerateSATInstance (nVar : Int, nClause : Int, nTerms : Int) : (Int, Bool)[][] { + operation GenerateSATInstance(nVar : Int, nClause : Int, nTerms : Int) : (Int, Bool)[][] { mutable problem = [[(0, false), size = 0], size = nClause]; - for j in 0 .. nClause - 1 { + for j in 0..nClause - 1 { set problem w/= j <- Generate_SAT_Clause(nVar, nTerms); } return problem; } -} \ No newline at end of file +} diff --git a/katas/content/solving_sat/and/Verification.qs b/katas/content/solving_sat/and/Verification.qs index a3ae468fb8..7dc9c11178 100644 --- a/katas/content/solving_sat/and/Verification.qs +++ b/katas/content/solving_sat/and/Verification.qs @@ -1,6 +1,6 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Arrays; + import KatasUtils.*; + import Std.Arrays.*; function F_And(args : Bool[]) : Bool { return Count(x -> not x, args) == 0; diff --git a/katas/content/solving_sat/exactly_one_one/Verification.qs b/katas/content/solving_sat/exactly_one_one/Verification.qs index 63df0e74ef..d38af86b00 100644 --- a/katas/content/solving_sat/exactly_one_one/Verification.qs +++ b/katas/content/solving_sat/exactly_one_one/Verification.qs @@ -1,8 +1,8 @@ namespace Kata.Verification { - open Microsoft.Quantum.Arrays; - open Microsoft.Quantum.Katas; + import Std.Arrays.*; + import KatasUtils.*; - function F_Exactly1One (args : Bool[]) : Bool { + function F_Exactly1One(args : Bool[]) : Bool { return Count(x -> x, args) == 1; } diff --git a/katas/content/solving_sat/exactly_one_one_formula/Placeholder.qs b/katas/content/solving_sat/exactly_one_one_formula/Placeholder.qs index 70d13b1c18..1c84b0e561 100644 --- a/katas/content/solving_sat/exactly_one_one_formula/Placeholder.qs +++ b/katas/content/solving_sat/exactly_one_one_formula/Placeholder.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Arrays; + import Std.Arrays.*; operation Oracle_Exactly13SATFormula(x : Qubit[], y : Qubit, formula : (Int, Bool)[][]) : Unit is Adj + Ctl { // Implement your solution here... @@ -14,12 +14,12 @@ namespace Kata { // You might find these helper operations from earlier tasks useful. operation Oracle_Exactly1One(x : Qubit[], y : Qubit) : Unit is Adj + Ctl { - for i in 0 .. Length(x) - 1 { - ApplyControlledOnInt(2 ^ i, X, x, y); + for i in 0..Length(x) - 1 { + ApplyControlledOnInt(2^i, X, x, y); } - } + } operation Oracle_And(x : Qubit[], y : Qubit) : Unit is Adj + Ctl { Controlled X(x, y); - } + } } diff --git a/katas/content/solving_sat/exactly_one_one_formula/Solution.qs b/katas/content/solving_sat/exactly_one_one_formula/Solution.qs index f7a5078a06..260b8dd5f0 100644 --- a/katas/content/solving_sat/exactly_one_one_formula/Solution.qs +++ b/katas/content/solving_sat/exactly_one_one_formula/Solution.qs @@ -1,10 +1,10 @@ namespace Kata { - open Microsoft.Quantum.Arrays; + import Std.Arrays.*; operation Oracle_Exactly13SATFormula(x : Qubit[], y : Qubit, formula : (Int, Bool)[][]) : Unit is Adj + Ctl { use aux = Qubit[Length(formula)]; within { - for i in 0 .. Length(formula) - 1 { + for i in 0..Length(formula) - 1 { Oracle_Exactly13SATClause(x, aux[i], formula[i]); } } apply { @@ -28,12 +28,12 @@ namespace Kata { // You might find these helper operations from earlier tasks useful. operation Oracle_Exactly1One(x : Qubit[], y : Qubit) : Unit is Adj + Ctl { - for i in 0 .. Length(x) - 1 { - ApplyControlledOnInt(2 ^ i, X, x, y); + for i in 0..Length(x) - 1 { + ApplyControlledOnInt(2^i, X, x, y); } - } + } operation Oracle_And(x : Qubit[], y : Qubit) : Unit is Adj + Ctl { Controlled X(x, y); - } + } } diff --git a/katas/content/solving_sat/exactly_one_one_formula/Verification.qs b/katas/content/solving_sat/exactly_one_one_formula/Verification.qs index 3ada1e7db3..5c9b063b6b 100644 --- a/katas/content/solving_sat/exactly_one_one_formula/Verification.qs +++ b/katas/content/solving_sat/exactly_one_one_formula/Verification.qs @@ -1,8 +1,8 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Random; + import KatasUtils.*; + import Std.Random.*; - function F_Exactly1SATClause (args : Bool[], clause : (Int, Bool)[]) : Bool { + function F_Exactly1SATClause(args : Bool[], clause : (Int, Bool)[]) : Bool { mutable nOnes = 0; for (index, isTrue) in clause { if isTrue == args[index] { @@ -12,7 +12,7 @@ namespace Kata.Verification { return nOnes == 1; } - function F_Exactly1SATFormula (args : Bool[], formula : (Int, Bool)[][]) : Bool { + function F_Exactly1SATFormula(args : Bool[], formula : (Int, Bool)[][]) : Bool { for clause in formula { if not F_Exactly1SATClause(args, clause) { return false; @@ -23,10 +23,10 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { - for nVar in 3 .. 6 { - for _ in 1 .. 3 { + for nVar in 3..6 { + for _ in 1..3 { let formula = GenerateSATInstance(nVar, nVar - 1, 3); - + if not CheckOracleImplementsFunction(nVar, Kata.Oracle_Exactly13SATFormula(_, _, formula), F_Exactly1SATFormula(_, formula)) { Message($"Test failed for SAT formula {SATFormulaAsString(formula)}"); return false; diff --git a/katas/content/solving_sat/examples/SolvingSATWithGroverDemo.qs b/katas/content/solving_sat/examples/SolvingSATWithGroverDemo.qs index 7017e8e48c..cdea8189cf 100644 --- a/katas/content/solving_sat/examples/SolvingSATWithGroverDemo.qs +++ b/katas/content/solving_sat/examples/SolvingSATWithGroverDemo.qs @@ -1,8 +1,8 @@ namespace Kata { - open Microsoft.Quantum.Arrays; - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Math; + import Std.Arrays.*; + import Std.Convert.*; + import Std.Diagnostics.*; + import Std.Math.*; @EntryPoint() operation SolvingSATWithGroverDemo() : Unit { @@ -11,9 +11,9 @@ namespace Kata { // (x₀ ∨ x₁) ∧ (¬x₀ ∨ ¬x₁) ∧ ¬x₂ let formula = [[(0, true), (1, true)], [(0, false), (1, false)], [(2, false)]]; let markingOracle = Oracle_SATFormula(_, _, formula); - for iterations in 0 .. 9 { + for iterations in 0..9 { mutable success = 0; - for _ in 1 .. 100 { + for _ in 1..100 { let res = GroversSearch(n, markingOracle, iterations); if F_SATFormula(res, formula) { set success += 1; @@ -25,7 +25,7 @@ namespace Kata { operation GroversSearch( n : Int, - markingOracle : (Qubit[], Qubit) => Unit is Adj + Ctl, + markingOracle : (Qubit[], Qubit) => Unit is Adj + Ctl, iterations : Int ) : Bool[] { use qs = Qubit[n]; @@ -40,7 +40,7 @@ namespace Kata { meanStatePrep(qs); // Do Grover's iterations. - for _ in 1 .. iterations { + for _ in 1..iterations { // Apply the phase oracle. phaseOracle(qs); @@ -54,8 +54,8 @@ namespace Kata { operation ApplyMarkingOracleAsPhaseOracle( markingOracle : (Qubit[], Qubit) => Unit is Adj + Ctl, - qubits : Qubit[]) - : Unit is Adj + Ctl { + qubits : Qubit[] + ) : Unit is Adj + Ctl { use minus = Qubit(); within { X(minus); @@ -67,8 +67,8 @@ namespace Kata { operation ReflectionAboutState( qs : Qubit[], - statePrep : Qubit[] => Unit is Adj + Ctl) - : Unit is Adj + Ctl { + statePrep : Qubit[] => Unit is Adj + Ctl + ) : Unit is Adj + Ctl { within { Adjoint statePrep(qs); } apply { @@ -80,7 +80,7 @@ namespace Kata { within { ApplyToEachA(X, qs); } apply { - Controlled Z(qs[1 ...], qs[0]); + Controlled Z(qs[1...], qs[0]); } R(PauliI, 2.0 * PI(), qs[0]); } @@ -88,7 +88,7 @@ namespace Kata { operation Oracle_SATFormula(x : Qubit[], y : Qubit, formula : (Int, Bool)[][]) : Unit is Adj + Ctl { use aux = Qubit[Length(formula)]; within { - for i in 0 .. Length(formula) - 1 { + for i in 0..Length(formula) - 1 { Oracle_SATClause(x, aux[i], formula[i]); } } apply { @@ -112,7 +112,7 @@ namespace Kata { operation Oracle_Or(x : Qubit[], y : Qubit) : Unit is Adj + Ctl { ApplyControlledOnInt(0, X, x, y); X(y); - } + } operation Oracle_And(x : Qubit[], y : Qubit) : Unit is Adj + Ctl { Controlled X(x, y); @@ -138,4 +138,4 @@ namespace Kata { } return true; } -} \ No newline at end of file +} diff --git a/katas/content/solving_sat/or/Verification.qs b/katas/content/solving_sat/or/Verification.qs index 5dca4d5200..52e1888d36 100644 --- a/katas/content/solving_sat/or/Verification.qs +++ b/katas/content/solving_sat/or/Verification.qs @@ -1,6 +1,6 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Arrays; + import KatasUtils.*; + import Std.Arrays.*; function F_Or(args : Bool[]) : Bool { return Count(x -> x, args) > 0; diff --git a/katas/content/solving_sat/sat_clause/Solution.qs b/katas/content/solving_sat/sat_clause/Solution.qs index b4c0dce9a0..2f673b8435 100644 --- a/katas/content/solving_sat/sat_clause/Solution.qs +++ b/katas/content/solving_sat/sat_clause/Solution.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Arrays; + import Std.Arrays.*; operation Oracle_SATClause(x : Qubit[], y : Qubit, clause : (Int, Bool)[]) : Unit is Adj + Ctl { let clauseQubits = Mapped((ind, _) -> x[ind], clause); within { @@ -16,5 +16,5 @@ namespace Kata { operation Oracle_Or(x : Qubit[], y : Qubit) : Unit is Adj + Ctl { ApplyControlledOnInt(0, X, x, y); X(y); - } + } } diff --git a/katas/content/solving_sat/sat_clause/Verification.qs b/katas/content/solving_sat/sat_clause/Verification.qs index 156e0c067f..c70b284b05 100644 --- a/katas/content/solving_sat/sat_clause/Verification.qs +++ b/katas/content/solving_sat/sat_clause/Verification.qs @@ -1,6 +1,6 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Random; + import KatasUtils.*; + import Std.Random.*; function F_SATClause(args : Bool[], clause : (Int, Bool)[]) : Bool { for (index, positive) in clause { @@ -15,10 +15,10 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { - for i in 1 .. 6 { + for i in 1..6 { let nVar = DrawRandomInt(3, 7); let clause = Generate_SAT_Clause(nVar, i); - + if not CheckOracleImplementsFunction(nVar, Kata.Oracle_SATClause(_, _, clause), F_SATClause(_, clause)) { Message($"Test failed for SAT clause {SATClauseAsString(clause)}"); return false; diff --git a/katas/content/solving_sat/sat_formula/Placeholder.qs b/katas/content/solving_sat/sat_formula/Placeholder.qs index ebc0b8db6d..a999888749 100644 --- a/katas/content/solving_sat/sat_formula/Placeholder.qs +++ b/katas/content/solving_sat/sat_formula/Placeholder.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Arrays; + import Std.Arrays.*; operation Oracle_SATFormula(x : Qubit[], y : Qubit, formula : (Int, Bool)[][]) : Unit is Adj + Ctl { // Implement your solution here... @@ -23,9 +23,9 @@ namespace Kata { operation Oracle_Or(x : Qubit[], y : Qubit) : Unit is Adj + Ctl { ApplyControlledOnInt(0, X, x, y); X(y); - } + } operation Oracle_And(x : Qubit[], y : Qubit) : Unit is Adj + Ctl { Controlled X(x, y); - } + } } diff --git a/katas/content/solving_sat/sat_formula/Solution.qs b/katas/content/solving_sat/sat_formula/Solution.qs index 122c6b91a0..92f7262374 100644 --- a/katas/content/solving_sat/sat_formula/Solution.qs +++ b/katas/content/solving_sat/sat_formula/Solution.qs @@ -1,10 +1,10 @@ namespace Kata { - open Microsoft.Quantum.Arrays; + import Std.Arrays.*; operation Oracle_SATFormula(x : Qubit[], y : Qubit, formula : (Int, Bool)[][]) : Unit is Adj + Ctl { use aux = Qubit[Length(formula)]; within { - for i in 0 .. Length(formula) - 1 { + for i in 0..Length(formula) - 1 { Oracle_SATClause(x, aux[i], formula[i]); } } apply { @@ -28,9 +28,9 @@ namespace Kata { operation Oracle_Or(x : Qubit[], y : Qubit) : Unit is Adj + Ctl { ApplyControlledOnInt(0, X, x, y); X(y); - } + } operation Oracle_And(x : Qubit[], y : Qubit) : Unit is Adj + Ctl { Controlled X(x, y); - } + } } diff --git a/katas/content/solving_sat/sat_formula/Verification.qs b/katas/content/solving_sat/sat_formula/Verification.qs index 798ca8b70f..f436b72c3b 100644 --- a/katas/content/solving_sat/sat_formula/Verification.qs +++ b/katas/content/solving_sat/sat_formula/Verification.qs @@ -1,6 +1,6 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - open Microsoft.Quantum.Random; + import KatasUtils.*; + import Std.Random.*; function F_SATClause(args : Bool[], clause : (Int, Bool)[]) : Bool { for (index, positive) in clause { @@ -25,10 +25,10 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { - for nVar in 2 .. 6 { - for _ in 1 .. 3 { + for nVar in 2..6 { + for _ in 1..3 { let formula = GenerateSATInstance(nVar, nVar - 1, -1); - + if not CheckOracleImplementsFunction(nVar, Kata.Oracle_SATFormula(_, _, formula), F_SATFormula(_, formula)) { Message($"Test failed for SAT formula {SATFormulaAsString(formula)}"); return false; diff --git a/katas/content/superdense_coding/entangled_pair/Verification.qs b/katas/content/superdense_coding/entangled_pair/Verification.qs index 9d9623320a..d5d7532ed9 100644 --- a/katas/content/superdense_coding/entangled_pair/Verification.qs +++ b/katas/content/superdense_coding/entangled_pair/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; operation CreateEntangledPair_Wrapper(qs : Qubit[]) : Unit is Adj { Kata.CreateEntangledPair(qs[0], qs[1]); diff --git a/katas/content/teleportation/Common.qs b/katas/content/teleportation/Common.qs index e3d63a06e7..b68115d837 100644 --- a/katas/content/teleportation/Common.qs +++ b/katas/content/teleportation/Common.qs @@ -1,6 +1,6 @@ namespace Kata.Verification { - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Math; + import Std.Diagnostics.*; + import Std.Math.*; operation EntangleWrapper_Reference(qs : Qubit[]) : Unit is Adj + Ctl { let (qAlice, qBob) = (qs[0], qs[1]); @@ -17,13 +17,13 @@ namespace Kata.Verification { operation StatePrep_BellState(q1 : Qubit, q2 : Qubit, state : Int) : Unit { H(q1); CNOT(q1, q2); - + // now we have |00⟩ + |11⟩ - modify it based on state arg if state % 2 == 1 { // negative phase Z(q2); } - + if state / 2 == 1 { X(q2); } @@ -33,22 +33,23 @@ namespace Kata.Verification { // Helper operation that run teleportation using the given operations to prepare the message qubit // and the entangled pair, and to run sender and receiver parts of the protocol. operation ComposeTeleportation( - bellPrepOp : ((Qubit, Qubit) => Unit), - getDescriptionOp : ((Qubit, Qubit) => (Bool, Bool)), + bellPrepOp : ((Qubit, Qubit) => Unit), + getDescriptionOp : ((Qubit, Qubit) => (Bool, Bool)), reconstructOp : ((Qubit, (Bool, Bool)) => Unit), - qAlice : Qubit, - qBob : Qubit, - qMessage : Qubit) : Unit { + qAlice : Qubit, + qBob : Qubit, + qMessage : Qubit + ) : Unit { bellPrepOp(qAlice, qBob); let classicalBits = getDescriptionOp(qAlice, qMessage); - + // Alice sends the classical bits to Bob. // Bob uses these bits to transform his part of the entangled pair into the message. reconstructOp(qBob, classicalBits); } - - operation SendMessage_Reference(qAlice: Qubit, qMessage: Qubit) : (Bool, Bool) { + + operation SendMessage_Reference(qAlice : Qubit, qMessage : Qubit) : (Bool, Bool) { CNOT(qMessage, qAlice); H(qMessage); return (M(qMessage) == One, M(qAlice) == One); @@ -70,17 +71,18 @@ namespace Kata.Verification { // Specifying the state to teleport through an operation allows to get the inverse // which makes testing easier. operation TeleportTestHelper( - teleportOp : ((Qubit, Qubit, Qubit) => Unit), + teleportOp : ((Qubit, Qubit, Qubit) => Unit), setupPsiOp : (Qubit => Unit is Adj), - psiName: String) : Bool { - + psiName : String + ) : Bool { + use (qMessage, qAlice, qBob) = (Qubit(), Qubit(), Qubit()); setupPsiOp(qMessage); - + // This should modify qBob to be identical to the state // of qMessage before the function call. teleportOp(qAlice, qBob, qMessage); - + // Applying the inverse of the setup operation to qBob // should make it Zero. Adjoint setupPsiOp(qBob); @@ -106,14 +108,14 @@ namespace Kata.Verification { // Define setup operations for the message qubit // on which to test teleportation: |0⟩, |1⟩, |0⟩ + |1⟩, unequal superposition. let setupPsiOps = [(I, "|0⟩"), (X, "|1⟩"), (H, "|+⟩"), (Ry(ArcCos(0.6) * 2.0, _), "0.6|0⟩ + 0.8|1⟩")]; - + // As part of teleportation Alice runs some measurements // with nondeterministic outcome. // Depending on the outcomes different paths are taken on Bob's side. // We repeat each test run several times to ensure that all paths are checked. let numRepetitions = 100; for (psiOp, psiName) in setupPsiOps { - for j in 1 .. numRepetitions { + for j in 1..numRepetitions { if not TeleportTestHelper(teleportOp, psiOp, psiName) { return false; } @@ -151,20 +153,22 @@ namespace Kata.Verification { // code is expected to take different paths each time since // measurements done by Alice are not deterministic. operation TeleportPreparedStateTestLoop( - prepareAndSendMessageOp : ((Qubit, Pauli, Result) => (Bool, Bool)), + prepareAndSendMessageOp : ((Qubit, Pauli, Result) => (Bool, Bool)), reconstructAndMeasureMessageOp : ((Qubit, (Bool, Bool), Pauli) => Result) - ) : Bool { - - let messages = [(PauliX, Zero, "|+⟩"), - (PauliX, One, "|-⟩"), - (PauliY, Zero, "|i⟩"), - (PauliY, One, "|-i⟩"), - (PauliZ, Zero, "|0⟩"), - (PauliZ, One, "|1⟩")]; + ) : Bool { + + let messages = [ + (PauliX, Zero, "|+⟩"), + (PauliX, One, "|-⟩"), + (PauliY, Zero, "|i⟩"), + (PauliY, One, "|-i⟩"), + (PauliZ, Zero, "|0⟩"), + (PauliZ, One, "|1⟩") + ]; let numRepetitions = 100; use (qAlice, qBob) = (Qubit(), Qubit()); for (basis, sentState, stateName) in messages { - for j in 1 .. numRepetitions { + for j in 1..numRepetitions { StatePrep_BellState(qAlice, qBob, 0); let classicalBits = prepareAndSendMessageOp(qAlice, basis, sentState); let receivedState = reconstructAndMeasureMessageOp(qBob, classicalBits, basis); @@ -192,4 +196,4 @@ namespace Kata.Verification { CNOT(qAlice, qCharlie); // Final state: 1/2 (|000⟩ + |011⟩ + |101⟩ + |110⟩) } -} \ No newline at end of file +} diff --git a/katas/content/teleportation/entangled_pair/Verification.qs b/katas/content/teleportation/entangled_pair/Verification.qs index df6b55a864..7a71ade5f6 100644 --- a/katas/content/teleportation/entangled_pair/Verification.qs +++ b/katas/content/teleportation/entangled_pair/Verification.qs @@ -1,19 +1,19 @@ namespace Kata.Verification { - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Katas; + import Std.Diagnostics.*; + import KatasUtils.*; - operation Entangle_Wrapper (qs : Qubit[]) : Unit is Adj { + operation Entangle_Wrapper(qs : Qubit[]) : Unit is Adj { Kata.Entangle(qs[0], qs[1]); } @EntryPoint() operation CheckSolution() : Bool { - + return CheckOperationsEquivalenceOnZeroStateWithFeedback( Entangle_Wrapper, EntangleWrapper_Reference, 2 ); - + } } diff --git a/katas/content/teleportation/entangled_trio/Verification.qs b/katas/content/teleportation/entangled_trio/Verification.qs index ccda459f06..4182864853 100644 --- a/katas/content/teleportation/entangled_trio/Verification.qs +++ b/katas/content/teleportation/entangled_trio/Verification.qs @@ -1,6 +1,6 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; - + import KatasUtils.*; + operation EntangleThreeQubits_Wrapper(qs : Qubit[]) : Unit is Adj { Kata.EntangleThreeQubits(qs[0], qs[1], qs[2]); } @@ -12,6 +12,6 @@ namespace Kata.Verification { EntangleThreeQubitsWrapper_Reference, 3 ); - + } -} \ No newline at end of file +} diff --git a/katas/content/teleportation/entanglement_swapping/Solution.qs b/katas/content/teleportation/entanglement_swapping/Solution.qs index a67d16d5f3..8515e0bf4b 100644 --- a/katas/content/teleportation/entanglement_swapping/Solution.qs +++ b/katas/content/teleportation/entanglement_swapping/Solution.qs @@ -1,5 +1,5 @@ namespace Kata { - open Microsoft.Quantum.Convert; + import Std.Convert.*; operation EntanglementSwapping() : ((Qubit, Qubit) => Int, (Qubit, Int) => Unit) { return (SendMessageCharlie, ReconstructMessageBob); @@ -8,14 +8,14 @@ namespace Kata { operation SendMessageCharlie(qAlice1 : Qubit, qBob1 : Qubit) : Int { let (c1, c2) = SendMessage(qAlice1, qBob1); return BoolArrayAsInt([c1, c2]); - } + } operation ReconstructMessageBob(qBob2 : Qubit, resultCharlie : Int) : Unit { - let classicalBits = IntAsBoolArray(resultCharlie, 2); + let classicalBits = IntAsBoolArray(resultCharlie, 2); ReconstructMessage(qBob2, (classicalBits[0], classicalBits[1])); } - operation SendMessage(qAlice: Qubit, qMessage: Qubit) : (Bool, Bool) { + operation SendMessage(qAlice : Qubit, qMessage : Qubit) : (Bool, Bool) { CNOT(qMessage, qAlice); H(qMessage); return (M(qMessage) == One, M(qAlice) == One); @@ -29,4 +29,4 @@ namespace Kata { X(qBob); } } -} \ No newline at end of file +} diff --git a/katas/content/teleportation/entanglement_swapping/Verification.qs b/katas/content/teleportation/entanglement_swapping/Verification.qs index 6e32594f1f..1be9a49465 100644 --- a/katas/content/teleportation/entanglement_swapping/Verification.qs +++ b/katas/content/teleportation/entanglement_swapping/Verification.qs @@ -1,20 +1,20 @@ namespace Kata.Verification { - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Katas; + import Std.Diagnostics.*; + import KatasUtils.*; operation TeleportEntanglementSwappingTestLoop( entanglementSwapping : ((Qubit, Qubit) => Int, (Qubit, Int) => Unit) ) : Bool { - - for i in 1 .. 15 { + + for i in 1..15 { use (qAlice1, qAlice2) = (Qubit(), Qubit()); EntangleWrapper_Reference([qAlice1, qAlice2]); - + use (qBob1, qBob2) = (Qubit(), Qubit()); EntangleWrapper_Reference([qBob1, qBob2]); - + let (teleportOp, adjustOp) = entanglementSwapping; - // Apply the operations returned by the solution: + // Apply the operations returned by the solution: // first Charlie's side, then Bob's side. let result = teleportOp(qAlice1, qBob1); adjustOp(qBob2, result); @@ -23,7 +23,7 @@ namespace Kata.Verification { // if the state of Alice's and Bob's qubits was |Φ⁺⟩, // their state should become |00⟩ now. Adjoint EntangleWrapper_Reference([qAlice2, qBob2]); - + // Assert that Alice's and Bob's qubits end up in |0⟩ state. if not CheckAllZero([qAlice2, qBob2]) { Message($"Incorrect."); @@ -34,7 +34,7 @@ namespace Kata.Verification { ResetAll([qAlice1, qAlice2, qBob1, qBob2]); return false; } - + Message($"Correct."); ResetAll([qAlice1, qAlice2, qBob1, qBob2]); return true; @@ -45,4 +45,4 @@ namespace Kata.Verification { operation CheckSolution() : Bool { return TeleportEntanglementSwappingTestLoop(Kata.EntanglementSwapping()); } -} \ No newline at end of file +} diff --git a/katas/content/teleportation/examples/TestingStandardTeleportation.qs b/katas/content/teleportation/examples/TestingStandardTeleportation.qs index 43a4f27395..c875a05f4d 100644 --- a/katas/content/teleportation/examples/TestingStandardTeleportation.qs +++ b/katas/content/teleportation/examples/TestingStandardTeleportation.qs @@ -1,16 +1,18 @@ namespace Kata { - open Microsoft.Quantum.Diagnostics; + import Std.Diagnostics.*; @EntryPoint() operation TestTeleportation() : Unit { // To define the different states, let us make use of PauliX, PauliY and PauliZ basis - let messages = [(PauliX, Zero, "|+⟩"), - (PauliX, One, "|-⟩"), - (PauliY, Zero, "|i⟩"), - (PauliY, One, "|-i⟩"), - (PauliZ, Zero, "|0⟩"), - (PauliZ, One, "|1⟩")]; + let messages = [ + (PauliX, Zero, "|+⟩"), + (PauliX, One, "|-⟩"), + (PauliY, Zero, "|i⟩"), + (PauliY, One, "|-i⟩"), + (PauliZ, Zero, "|0⟩"), + (PauliZ, One, "|1⟩") + ]; // To effectively test the solution, experiment needs to be repeated multiple times let numRepetitions = 100; @@ -19,10 +21,10 @@ namespace Kata { for (basis, sentState, stateName) in messages { // Loop through multiple iterations for each state - for j in 1 .. numRepetitions { + for j in 1..numRepetitions { // 1. Initialize qubits for Alice and Bob // .. - + // 2. Prepare the entangled state between Alice and Bob // .. @@ -60,7 +62,7 @@ namespace Kata { Reset(qMessage); return classicalBits; } - + operation ReconstructAndMeasureMessage(qBob : Qubit, (b1 : Bool, b2 : Bool), basis : Pauli) : Result { ReconstructMessage(qBob, (b1, b2)); return Measure([basis], [qBob]); @@ -71,7 +73,7 @@ namespace Kata { CNOT(qAlice, qBob); } - operation SendMessage(qAlice: Qubit, qMessage: Qubit) : (Bool, Bool) { + operation SendMessage(qAlice : Qubit, qMessage : Qubit) : (Bool, Bool) { CNOT(qMessage, qAlice); H(qMessage); return (M(qMessage) == One, M(qAlice) == One); @@ -85,4 +87,4 @@ namespace Kata { X(qBob); } } -} \ No newline at end of file +} diff --git a/katas/content/teleportation/measurement_free_teleportation/Verification.qs b/katas/content/teleportation/measurement_free_teleportation/Verification.qs index 2cd3719a29..556deb4894 100644 --- a/katas/content/teleportation/measurement_free_teleportation/Verification.qs +++ b/katas/content/teleportation/measurement_free_teleportation/Verification.qs @@ -1,15 +1,15 @@ namespace Kata.Verification { - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Math; - + import Std.Diagnostics.*; + import Std.Math.*; + operation MeasurementFreeTeleportTestLoop( measurementFreeTeleport : (Qubit, Qubit, Qubit) => Unit ) : Bool { let setupPsiOps = [(I, "|0⟩"), (X, "|1⟩"), (H, "|+⟩"), (Ry(ArcCos(0.6) * 2.0, _), "0.6|0⟩ + 0.8|1⟩")]; let numRepetitions = 100; - + for (psiOp, psiName) in setupPsiOps { - for j in 1 .. numRepetitions { + for j in 1..numRepetitions { use (qMessage, qAlice, qBob) = (Qubit(), Qubit(), Qubit()); psiOp(qMessage); StatePrep_BellState(qAlice, qBob, 0); @@ -22,7 +22,7 @@ namespace Kata.Verification { DumpMachine(); ResetAll([qMessage, qAlice, qBob]); return false; - } + } ResetAll([qMessage, qAlice, qBob]); } } @@ -33,6 +33,6 @@ namespace Kata.Verification { @EntryPoint() operation CheckSolution() : Bool { - return MeasurementFreeTeleportTestLoop(Kata.MeasurementFreeTeleport); + return MeasurementFreeTeleportTestLoop(Kata.MeasurementFreeTeleport); } -} \ No newline at end of file +} diff --git a/katas/content/teleportation/prepare_and_send_message/Verification.qs b/katas/content/teleportation/prepare_and_send_message/Verification.qs index ace7f53efb..f798bc75aa 100644 --- a/katas/content/teleportation/prepare_and_send_message/Verification.qs +++ b/katas/content/teleportation/prepare_and_send_message/Verification.qs @@ -1,9 +1,9 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; @EntryPoint() operation CheckSolution() : Bool { return TeleportPreparedStateTestLoop(Kata.PrepareAndSendMessage, ReconstructAndMeasureMessage_Reference); } -} \ No newline at end of file +} diff --git a/katas/content/teleportation/reconstruct_and_measure_message/Verification.qs b/katas/content/teleportation/reconstruct_and_measure_message/Verification.qs index f5b490cbc6..acc85a6b98 100644 --- a/katas/content/teleportation/reconstruct_and_measure_message/Verification.qs +++ b/katas/content/teleportation/reconstruct_and_measure_message/Verification.qs @@ -1,9 +1,9 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; @EntryPoint() operation CheckSolution() : Bool { return TeleportPreparedStateTestLoop(PrepareAndSendMessage_Reference, Kata.ReconstructAndMeasureMessage); } -} \ No newline at end of file +} diff --git a/katas/content/teleportation/reconstruct_message/Verification.qs b/katas/content/teleportation/reconstruct_message/Verification.qs index 4296ee87e0..ccace826e6 100644 --- a/katas/content/teleportation/reconstruct_message/Verification.qs +++ b/katas/content/teleportation/reconstruct_message/Verification.qs @@ -1,10 +1,10 @@ namespace Kata.Verification { - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Katas; + import Std.Diagnostics.*; + import KatasUtils.*; @EntryPoint() operation CheckSolution() : Bool { let teleport = ComposeTeleportation(StatePrep_BellState(_, _, 0), SendMessage_Reference, Kata.ReconstructMessage, _, _, _); - return TeleportTestLoop(teleport); + return TeleportTestLoop(teleport); } -} \ No newline at end of file +} diff --git a/katas/content/teleportation/reconstruct_message_charlie/Verification.qs b/katas/content/teleportation/reconstruct_message_charlie/Verification.qs index 89b95e5aa2..9dafa33a25 100644 --- a/katas/content/teleportation/reconstruct_message_charlie/Verification.qs +++ b/katas/content/teleportation/reconstruct_message_charlie/Verification.qs @@ -1,18 +1,18 @@ namespace Kata.Verification { - open Microsoft.Quantum.Convert; - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Math; - open Microsoft.Quantum.Katas; - + import Std.Convert.*; + import Std.Diagnostics.*; + import Std.Math.*; + import KatasUtils.*; + operation ReconstructMessageWhenThreeEntangledQubitsTestLoop( reconstructMessage : (Qubit, (Bool, Bool), Bool) => Unit ) : Bool { - + let setupPsiOps = [(I, "|0⟩"), (X, "|1⟩"), (H, "|+⟩"), (Ry(ArcCos(0.6) * 2.0, _), "0.6|0⟩ + 0.8|1⟩")]; let numRepetitions = 100; - + for (psiOp, psiName) in setupPsiOps { - for j in 1 .. numRepetitions { + for j in 1..numRepetitions { use (qMessage, qAlice, qBob, qCharlie) = (Qubit(), Qubit(), Qubit(), Qubit()); psiOp(qMessage); EntangleThreeQubitsWrapper_Reference([qAlice, qBob, qCharlie]); @@ -39,4 +39,4 @@ namespace Kata.Verification { operation CheckSolution() : Bool { return ReconstructMessageWhenThreeEntangledQubitsTestLoop(Kata.ReconstructMessageWhenThreeEntangledQubits); } -} \ No newline at end of file +} diff --git a/katas/content/teleportation/reconstruct_message_phi_minus/Verification.qs b/katas/content/teleportation/reconstruct_message_phi_minus/Verification.qs index be908d7384..c5cc2a229b 100644 --- a/katas/content/teleportation/reconstruct_message_phi_minus/Verification.qs +++ b/katas/content/teleportation/reconstruct_message_phi_minus/Verification.qs @@ -1,10 +1,10 @@ namespace Kata.Verification { - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Katas; + import Std.Diagnostics.*; + import KatasUtils.*; @EntryPoint() operation CheckSolution() : Bool { let teleport = ComposeTeleportation(StatePrep_BellState(_, _, 1), SendMessage_Reference, Kata.ReconstructMessage_PhiMinus, _, _, _); - return TeleportTestLoop(teleport); + return TeleportTestLoop(teleport); } -} \ No newline at end of file +} diff --git a/katas/content/teleportation/reconstruct_message_psi_minus/Verification.qs b/katas/content/teleportation/reconstruct_message_psi_minus/Verification.qs index 04e278b6af..2bca57434c 100644 --- a/katas/content/teleportation/reconstruct_message_psi_minus/Verification.qs +++ b/katas/content/teleportation/reconstruct_message_psi_minus/Verification.qs @@ -1,10 +1,10 @@ namespace Kata.Verification { - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Katas; + import Std.Diagnostics.*; + import KatasUtils.*; @EntryPoint() operation CheckSolution() : Bool { let teleport = ComposeTeleportation(StatePrep_BellState(_, _, 3), SendMessage_Reference, Kata.ReconstructMessage_PsiMinus, _, _, _); - return TeleportTestLoop(teleport); + return TeleportTestLoop(teleport); } -} \ No newline at end of file +} diff --git a/katas/content/teleportation/reconstruct_message_psi_plus/Verification.qs b/katas/content/teleportation/reconstruct_message_psi_plus/Verification.qs index 6f8b0bd444..87a2be05bc 100644 --- a/katas/content/teleportation/reconstruct_message_psi_plus/Verification.qs +++ b/katas/content/teleportation/reconstruct_message_psi_plus/Verification.qs @@ -1,10 +1,10 @@ namespace Kata.Verification { - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Katas; + import Std.Diagnostics.*; + import KatasUtils.*; @EntryPoint() operation CheckSolution() : Bool { let teleport = ComposeTeleportation(StatePrep_BellState(_, _, 2), SendMessage_Reference, Kata.ReconstructMessage_PsiPlus, _, _, _); - return TeleportTestLoop(teleport); + return TeleportTestLoop(teleport); } -} \ No newline at end of file +} diff --git a/katas/content/teleportation/send_message/Verification.qs b/katas/content/teleportation/send_message/Verification.qs index e60a8f0bbb..795a3bb596 100644 --- a/katas/content/teleportation/send_message/Verification.qs +++ b/katas/content/teleportation/send_message/Verification.qs @@ -1,10 +1,10 @@ namespace Kata.Verification { - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Katas; + import Std.Diagnostics.*; + import KatasUtils.*; @EntryPoint() - operation CheckSolution() : Bool { + operation CheckSolution() : Bool { let teleport = ComposeTeleportation(StatePrep_BellState(_, _, 0), Kata.SendMessage, ReconstructMessage_Reference, _, _, _); - return TeleportTestLoop(teleport); + return TeleportTestLoop(teleport); } -} \ No newline at end of file +} diff --git a/katas/content/teleportation/standard_teleportation_protocol/Verification.qs b/katas/content/teleportation/standard_teleportation_protocol/Verification.qs index bae6a02ecb..8470f9e08e 100644 --- a/katas/content/teleportation/standard_teleportation_protocol/Verification.qs +++ b/katas/content/teleportation/standard_teleportation_protocol/Verification.qs @@ -1,5 +1,5 @@ namespace Kata.Verification { - open Microsoft.Quantum.Katas; + import KatasUtils.*; @EntryPoint() operation CheckSolution() : Bool { @@ -7,4 +7,4 @@ namespace Kata.Verification { return TeleportTestLoop(teleport); } -} \ No newline at end of file +} diff --git a/katas/test_cases/apply_x/Correct.qs b/katas/test_cases/apply_x/Correct.qs index da6fe2c416..b852c328a6 100644 --- a/katas/test_cases/apply_x/Correct.qs +++ b/katas/test_cases/apply_x/Correct.qs @@ -2,9 +2,7 @@ // Licensed under the MIT License. namespace Kata { - open Microsoft.Quantum.Intrinsic; - operation ApplyX(q : Qubit) : Unit is Adj + Ctl { X(q); } -} \ No newline at end of file +} diff --git a/katas/test_cases/apply_x/Incorrect.qs b/katas/test_cases/apply_x/Incorrect.qs index 7f81d6d133..cb46bb0133 100644 --- a/katas/test_cases/apply_x/Incorrect.qs +++ b/katas/test_cases/apply_x/Incorrect.qs @@ -2,9 +2,7 @@ // Licensed under the MIT License. namespace Kata { - open Microsoft.Quantum.Intrinsic; - operation ApplyX(q : Qubit) : Unit is Adj + Ctl { // Do nothing. } -} \ No newline at end of file +} diff --git a/katas/test_cases/apply_x/Verification.qs b/katas/test_cases/apply_x/Verification.qs index bc0afc5294..1ae21d1ce9 100644 --- a/katas/test_cases/apply_x/Verification.qs +++ b/katas/test_cases/apply_x/Verification.qs @@ -2,8 +2,7 @@ // Licensed under the MIT License. namespace Kata.Verification { - open Microsoft.Quantum.Diagnostics; - open Microsoft.Quantum.Intrinsic; + import Std.Diagnostics.*; operation CheckSolution() : Bool { VerifySingleQubitOperation(Kata.ApplyX, ApplyX) @@ -15,13 +14,12 @@ namespace Kata.Verification { operation VerifySingleQubitOperation( op : (Qubit => Unit is Adj + Ctl), - reference : (Qubit => Unit is Adj + Ctl)) - : Bool { + reference : (Qubit => Unit is Adj + Ctl) + ) : Bool { use (control, target) = (Qubit(), Qubit()); within { H(control); - } - apply { + } apply { Controlled op([control], target); Adjoint Controlled reference([control], target); } @@ -30,4 +28,4 @@ namespace Kata.Verification { isCorrect } -} \ No newline at end of file +} diff --git a/language_service/src/definition.rs b/language_service/src/definition.rs index a32d611d44..a3ca15a334 100644 --- a/language_service/src/definition.rs +++ b/language_service/src/definition.rs @@ -42,6 +42,10 @@ struct DefinitionFinder<'a> { } impl<'a> Handler<'a> for DefinitionFinder<'a> { + fn at_attr_ref(&mut self, _: &'a ast::Ident) { + // We don't support goto def for attributes. + } + fn at_callable_def( &mut self, _: &LocatorContext<'a>, diff --git a/language_service/src/hover.rs b/language_service/src/hover.rs index 8e9de3f68c..954a4faa33 100644 --- a/language_service/src/hover.rs +++ b/language_service/src/hover.rs @@ -10,10 +10,12 @@ use crate::protocol::Hover; use crate::qsc_utils::into_range; use qsc::ast::visit::Visitor; use qsc::display::{parse_doc_for_param, parse_doc_for_summary, CodeDisplay, Lookup}; +use qsc::hir::Attr; use qsc::line_column::{Encoding, Position, Range}; use qsc::{ast, hir, Span}; use std::fmt::Display; use std::rc::Rc; +use std::str::FromStr; pub(crate) fn get_hover( compilation: &Compilation, @@ -43,6 +45,7 @@ enum LocalKind { LambdaParam, Local, } + struct HoverGenerator<'a> { position_encoding: Encoding, hover: Option, @@ -51,6 +54,18 @@ struct HoverGenerator<'a> { } impl<'a> Handler<'a> for HoverGenerator<'a> { + fn at_attr_ref(&mut self, name: &'a ast::Ident) { + let description = match Attr::from_str(&name.name) { + Ok(attr) => attr.description(), + Err(()) => return, // No hover information for unsupported attributes. + }; + + self.hover = Some(Hover { + contents: format!("attribute ```{}```\n\n{}", name.name, description), + span: self.range(name.span), + }); + } + fn at_callable_def( &mut self, context: &LocatorContext<'a>, diff --git a/language_service/src/hover/tests.rs b/language_service/src/hover/tests.rs index faa281bb73..361d0f124a 100644 --- a/language_service/src/hover/tests.rs +++ b/language_service/src/hover/tests.rs @@ -43,6 +43,42 @@ fn check_notebook_none(cells_with_markers: &[(&str, &str)]) { assert!(actual.is_none()); } +#[test] +fn attr() { + check( + indoc! {r#" + namespace Test { + @◉Entr↘yPoint◉() + operation Bar() : Unit {} + } + "#}, + &expect![[r#" + attribute ```EntryPoint``` + + Indicates that the callable is the entry point to a program."#]], + ); +} + +#[test] +fn attr_with_arg() { + check( + indoc! {r#" + namespace Test { + @◉Con↘fig◉(BackwardsBranching) + operation Bar() : Unit {} + } + "#}, + &expect![[r#" + attribute ```Config``` + + Provides pre-processing information about when an item should be included in compilation. + + Valid arguments are `Base`, `Adaptive`, `IntegerComputations`, `FloatingPointComputations`, `BackwardsBranching`, `HigherLevelConstructs`, `QubitReset`, and `Unrestricted`. + + The `not` operator is also supported to negate the attribute, e.g. `not Adaptive`."#]], + ); +} + #[test] fn callable_unit_types() { check( diff --git a/language_service/src/name_locator.rs b/language_service/src/name_locator.rs index 22d3a8f2cd..5243b56f1f 100644 --- a/language_service/src/name_locator.rs +++ b/language_service/src/name_locator.rs @@ -5,19 +5,23 @@ use std::mem::replace; use std::rc::Rc; use crate::compilation::Compilation; -use qsc::ast::visit::{walk_expr, walk_namespace, walk_pat, walk_ty, walk_ty_def, Visitor}; +use qsc::ast::visit::{ + walk_attr, walk_expr, walk_namespace, walk_pat, walk_ty, walk_ty_def, Visitor, +}; use qsc::ast::{FieldAccess, Idents, PathKind}; use qsc::display::Lookup; use qsc::{ast, hir, resolve}; -#[allow(unused_variables)] pub(crate) trait Handler<'package> { + fn at_attr_ref(&mut self, name: &'package ast::Ident); + fn at_callable_def( &mut self, context: &LocatorContext<'package>, name: &'package ast::Ident, decl: &'package ast::CallableDecl, ); + fn at_callable_ref( &mut self, path: &'package ast::Path, @@ -166,6 +170,13 @@ impl<'inner, 'package, T: Handler<'package>> Locator<'inner, 'package, T> { } impl<'inner, 'package, T: Handler<'package>> Visitor<'package> for Locator<'inner, 'package, T> { + fn visit_attr(&mut self, attr: &'package ast::Attr) { + if attr.name.span.contains(self.offset) { + self.inner.at_attr_ref(&attr.name); + } + walk_attr(self, attr); + } + fn visit_namespace(&mut self, namespace: &'package ast::Namespace) { if namespace.span.contains(self.offset) { self.context.current_namespace = namespace.name.full_name(); @@ -177,6 +188,7 @@ impl<'inner, 'package, T: Handler<'package>> Visitor<'package> for Locator<'inne fn visit_item(&mut self, item: &'package ast::Item) { if item.span.contains(self.offset) { let context = replace(&mut self.context.current_item_doc, item.doc.clone()); + item.attrs.iter().for_each(|a| self.visit_attr(a)); match &*item.kind { ast::ItemKind::Callable(decl) => { if decl.name.span.touches(self.offset) { diff --git a/language_service/src/references.rs b/language_service/src/references.rs index 59026da5b3..4f7bc4cfc6 100644 --- a/language_service/src/references.rs +++ b/language_service/src/references.rs @@ -52,6 +52,10 @@ struct NameHandler<'a> { } impl<'a> Handler<'a> for NameHandler<'a> { + fn at_attr_ref(&mut self, _: &'a ast::Ident) { + // We don't support find all refs for attributes. + } + fn at_callable_def( &mut self, _: &LocatorContext<'a>, diff --git a/language_service/src/rename.rs b/language_service/src/rename.rs index 5df6aa82c9..8a963816fb 100644 --- a/language_service/src/rename.rs +++ b/language_service/src/rename.rs @@ -152,6 +152,10 @@ impl<'a> Rename<'a> { } impl<'a> Handler<'a> for Rename<'a> { + fn at_attr_ref(&mut self, _: &'a ast::Ident) { + // We don't support renaming attributes. + } + fn at_callable_def( &mut self, _: &LocatorContext<'a>, diff --git a/library/fixed_point/qsharp.json b/library/fixed_point/qsharp.json index 899e462aa5..976c27aa25 100644 --- a/library/fixed_point/qsharp.json +++ b/library/fixed_point/qsharp.json @@ -9,14 +9,6 @@ "ref": "3195043", "path": "library/signed" } - }, - "Unstable": { - "github": { - "owner": "Microsoft", - "repo": "qsharp", - "ref": "3195043", - "path": "library/unstable" - } } }, "files": [ diff --git a/library/fixed_point/src/Operations.qs b/library/fixed_point/src/Operations.qs index 436b7625d2..fdce658a96 100644 --- a/library/fixed_point/src/Operations.qs +++ b/library/fixed_point/src/Operations.qs @@ -6,7 +6,7 @@ import Init.PrepareFxP; import Facts.AssertPointPositionsIdenticalFxP, Facts.AssertFormatsAreIdenticalFxP, Facts.AssertAllZeroFxP; import Signed.Operations.Invert2sSI, Signed.Operations.MultiplySI, Signed.Operations.SquareSI; import Std.Arrays.Zipped; -import Unstable.Arithmetic.RippleCarryTTKIncByLE; +import Std.Arithmetic.RippleCarryTTKIncByLE; /// # Summary /// Adds a classical constant to a quantum fixed-point number. diff --git a/library/qtest/src/Functions.qs b/library/qtest/src/Functions.qs index 8c9a1a1f99..c5cf1d0bcc 100644 --- a/library/qtest/src/Functions.qs +++ b/library/qtest/src/Functions.qs @@ -12,7 +12,7 @@ import Std.Arrays.Mapped, Std.Arrays.All; /// test results instead of printing out to output. /// /// # Input -/// Takes a list of test cases. A test case is a tuple of `(String, () -> T, 'T)`, where +/// Takes a list of test cases. A test case is a tuple of `(String, () -> 'T, 'T)`, where /// the first String is the name of the test, the function is the test case itself, and the /// final element of the tuple is the expected return value from the test case. /// @@ -33,7 +33,7 @@ function CheckAllTestCases<'T : Eq + Show>(test_cases : (String, () -> 'T, 'T)[] /// This is a good alternative to `CheckAllTestCases` when you want custom output based on the results of your tests, /// or more control over how test results are rendered. /// # Input -/// Takes a list of test cases. A test case is a tuple of `(String, () -> T, 'T)`, where +/// Takes a list of test cases. A test case is a tuple of `(String, () -> 'T, 'T)`, where /// the first String is the name of the test, the function is the test case itself, and the /// final element of the tuple is the expected return value from the test case. /// diff --git a/library/qtest/src/Operations.qs b/library/qtest/src/Operations.qs index b1246c177d..c559b8ce66 100644 --- a/library/qtest/src/Operations.qs +++ b/library/qtest/src/Operations.qs @@ -12,15 +12,16 @@ import Std.Arrays.Mapped, Std.Arrays.All; /// test results instead of printing out to output. /// /// # Input -/// Takes a list of test cases. A test case is a tuple of `(String, () -> T, 'T)`, where -/// the first String is the name of the test, the function is the test case itself, and the +/// Takes a list of test cases. A test case is a tuple of `(String, Int, Qubit[] => Unit, Qubit[] => 'T, 'T)`, where +/// the first String is the name of the test, the int is the number of qubits to allocate for this test, +/// the first function is a qubit state prep function to be run before the test, the second function is the test case itself, and the /// final element of the tuple is the expected return value from the test case. /// /// # Example /// ```qsharp -/// CheckAllTestCases([("Should return 42", () -> 42, 42)]); +/// CheckAllTestCases([("0b0001 == 1", 4, (qs) => X(qs[0]), (qs) => MeasureSignedInteger(qs, 4), 1)]); /// ``` -operation CheckAllTestCases<'T : Eq + Show>(test_cases : (String, Int, (Qubit[]) => (), (Qubit[]) => 'T, 'T)[]) : Bool { +operation CheckAllTestCases<'T : Eq + Show>(test_cases : (String, Int, Qubit[] => (), Qubit[] => 'T, 'T)[]) : Bool { let test_results = RunAllTestCases(test_cases); OutputMessage(test_results); @@ -35,13 +36,13 @@ operation CheckAllTestCases<'T : Eq + Show>(test_cases : (String, Int, (Qubit[]) /// This is a good alternative to `CheckAllTestCases` when you want custom output based on the results of your tests, /// or more control over how test results are rendered. /// # Input -/// Takes a list of test cases. A test case is a tuple of `(String, () -> T, 'T)`, where +/// Takes a list of test cases. A test case is a tuple of `(String, () => 'T, 'T)`, where /// the first String is the name of the test, the function is the test case itself, and the /// final element of the tuple is the expected return value from the test case. /// /// # Example /// ```qsharp -/// RunAllTestCases([("Should return 42", () -> 42, 42)]); +/// RunAllTestCases([("0b0001 == 1", 4, (qs) => X(qs[0]), (qs) => MeasureSignedInteger(qs, 4), 1)]); /// ``` operation RunAllTestCases<'T : Eq + Show>(test_cases : (String, Int, (Qubit[]) => (), (Qubit[]) => 'T, 'T)[]) : TestCaseResult[] { let num_tests = Length(test_cases); diff --git a/library/rotations/README.md b/library/rotations/README.md new file mode 100644 index 0000000000..bacdec2029 --- /dev/null +++ b/library/rotations/README.md @@ -0,0 +1,4 @@ +# Rotations + +The `rotations` library defines operations for applying rotations to qubits and +registers. diff --git a/library/rotations/qsharp.json b/library/rotations/qsharp.json new file mode 100644 index 0000000000..363d2739ee --- /dev/null +++ b/library/rotations/qsharp.json @@ -0,0 +1,9 @@ +{ + "author": "Microsoft", + "license": "MIT", + "files": [ + "src/HammingWeightPhasing.qs", + "src/Main.qs", + "src/Tests.qs" + ] +} diff --git a/library/rotations/src/HammingWeightPhasing.qs b/library/rotations/src/HammingWeightPhasing.qs new file mode 100644 index 0000000000..ee4ac4c9d3 --- /dev/null +++ b/library/rotations/src/HammingWeightPhasing.qs @@ -0,0 +1,102 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +import Std.Arrays.Enumerated, Std.Arrays.Most, Std.Arrays.Partitioned, Std.Arrays.Tail; +import Std.Convert.IntAsDouble; +import Std.Diagnostics.Fact; +import Std.Math.BitSizeI, Std.Math.Floor, Std.Math.Lg, Std.Math.MaxI, Std.Math.MinI; + +/// # Summary +/// Applies a Z-rotation (`Rz`) with given angle to each qubit in qs. +/// +/// # Description +/// This implementation is based on Hamming-weight phasing to reduce the number +/// of rotation gates. The technique was first presented in [1], and further +/// improved in [2] based on results in [3, 4]. Note, that the reduction of +/// rotation gates comes at a cost of additional qubits and additional quantum +/// operations to compute the Hamming-weight. +/// +/// # Reference +/// - [1](https://arxiv.org/abs/1709.06648) "Halving the cost of quantum +/// addition", Craig Gidney. +/// - [2](https://arxiv.org/abs/2012.09238) "Early fault-tolerant simulations of +/// the Hubbard model", Earl T. Campbell. +/// - [3](https://cpsc.yale.edu/sites/default/files/files/tr1260.pdf) "The exact +/// multiplicative complexity of the Hamming weight function", Joan Boyar and +/// René Peralta. +/// - [4](https://arxiv.org/abs/1908.01609) "The role of multiplicative +/// complexity in compiling low T-count oracle circuits", Giulia Meuli, +/// Mathias Soeken, Earl Campbell, Martin Roetteler, Giovanni De Micheli. +operation HammingWeightPhasing(angle : Double, qs : Qubit[]) : Unit { + WithHammingWeight(qs, (sum) => { + for (i, sumQubit) in Enumerated(sum) { + Rz(IntAsDouble(2^i) * angle, sumQubit); + } + }); +} + +internal operation WithHammingWeight(qs : Qubit[], action : Qubit[] => Unit) : Unit { + let n = Length(qs); + + if n <= 1 { + action(qs); + } elif n == 2 { + use sum = Qubit(); + + within { + AND(qs[0], qs[1], sum); + CNOT(qs[0], qs[1]); + } apply { + action([qs[1], sum]); + } + } elif n == 3 { + WithSum(qs[0], qs[1..1], qs[2..2], action); + } else { + let splitSize = 2^(BitSizeI(n - 1) - 1); + let (leftLen, rightLen) = (n - splitSize, splitSize - 1); + // handle corner case if n is power of 2; in that case the first + // partition is longer than the second one, and we want to avoid that. + let split = Partitioned([MinI(leftLen, rightLen), MaxI(leftLen, rightLen)], qs); + Fact(Length(split) == 3 and Length(split[2]) == 1, $"Unexpected split for n = {n}"); + + WithHammingWeight(split[0], (leftHW) => { + WithHammingWeight(split[1], (rightHW) => { + WithSum(split[2][0], leftHW, rightHW, action); + }); + }); + } +} + +internal operation Carry(carryIn : Qubit, x : Qubit, y : Qubit, carryOut : Qubit) : Unit is Adj { + CNOT(carryIn, x); + CNOT(carryIn, y); + AND(x, y, carryOut); + CNOT(carryIn, x); + CNOT(x, y); + CNOT(carryIn, carryOut); +} + +internal operation WithSum(carry : Qubit, xs : Qubit[], ys : Qubit[], action : Qubit[] => Unit) : Unit { + let n = Length(ys); + Fact(Length(xs) <= n, "Length of xs must be less or equal to length of ys"); + Fact(n > 0, "Length must be at least 1"); + + use carryOut = Qubit[n]; + let carryIn = [carry] + Most(carryOut); + + within { + for i in 0..n-1 { + if i < Length(xs) { + Carry(carryIn[i], xs[i], ys[i], carryOut[i]); + } else { + // there is no corresponding bit in xs; this is a version of + // Carry in which x == 0. + CNOT(carryIn[i], ys[i]); + AND(carryIn[i], ys[i], carryOut[i]); + CNOT(carryIn[i], carryOut[i]); + } + } + } apply { + action(ys + [Tail(carryOut)]); + } +} diff --git a/library/rotations/src/Main.qs b/library/rotations/src/Main.qs new file mode 100644 index 0000000000..d0c6a31b6a --- /dev/null +++ b/library/rotations/src/Main.qs @@ -0,0 +1,4 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +export HammingWeightPhasing.HammingWeightPhasing; diff --git a/library/rotations/src/Tests.qs b/library/rotations/src/Tests.qs new file mode 100644 index 0000000000..0d9267e52c --- /dev/null +++ b/library/rotations/src/Tests.qs @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +import Std.Diagnostics.CheckOperationsAreEqual, Std.Diagnostics.Fact; +import Std.Math.HammingWeightI, Std.Math.PI; + +import HammingWeightPhasing.HammingWeightPhasing, HammingWeightPhasing.WithHammingWeight; + +operation Main() : Unit { + TestHammingWeight(); + TestPhasing(); +} + +operation TestHammingWeight() : Unit { + // exhaustive + use qs = Qubit[4]; + + for x in 0..2^Length(qs) - 1 { + ApplyXorInPlace(x, qs); + WithHammingWeight(qs, sum => { + Fact(MeasureInteger(sum) == HammingWeightI(x), $"wrong Hamming weight computed for x = {x}"); + }); + ResetAll(qs); + } + + // some explicit cases + for (width, number) in [ + (1, 1), + (2, 0), + (2, 3), + (8, 10), + (7, 99) + ] { + use qs = Qubit[width]; + + ApplyXorInPlace(number, qs); + WithHammingWeight(qs, sum => { + Fact(MeasureInteger(sum) == HammingWeightI(number), $"wrong Hamming weight computed for number = {number}"); + }); + ResetAll(qs); + } +} + +operation TestPhasing() : Unit { + for theta in [1.0, 2.0, 0.0, -0.5, 5.0 * PI()] { + for numQubits in 1..6 { + Fact(CheckOperationsAreEqual(numQubits, qs => HammingWeightPhasing(theta, qs), qs => ApplyToEachA(Rz(theta, _), qs)), "Operations are not equal"); + } + } +} diff --git a/library/signed/qsharp.json b/library/signed/qsharp.json index b2f24b1e73..c8c3b80f5a 100644 --- a/library/signed/qsharp.json +++ b/library/signed/qsharp.json @@ -2,14 +2,6 @@ "author": "Microsoft", "license": "MIT", "dependencies": { - "Unstable": { - "github": { - "owner": "Microsoft", - "repo": "qsharp", - "ref": "3195043", - "path": "library/unstable" - } - }, "Qtest": { "github": { "owner": "Microsoft", diff --git a/library/signed/src/Comparison.qs b/library/signed/src/Comparison.qs index 7246acdd5a..49a16ad2d6 100644 --- a/library/signed/src/Comparison.qs +++ b/library/signed/src/Comparison.qs @@ -3,7 +3,7 @@ import Std.Arrays.Tail, Std.Arrays.Zipped, Std.Arrays.Most, Std.Arrays.Rest; import Std.Diagnostics.Fact; -import Unstable.Arithmetic.ApplyIfGreaterLE; +import Std.Arithmetic.ApplyIfGreaterLE; /// # Summary /// Wrapper for signed integer comparison: `result = xs > ys`. diff --git a/library/signed/src/Operations.qs b/library/signed/src/Operations.qs index f2d4d6da8a..929e4779eb 100644 --- a/library/signed/src/Operations.qs +++ b/library/signed/src/Operations.qs @@ -3,9 +3,8 @@ import Std.Arrays.Tail, Std.Arrays.Most, Std.Arrays.Enumerated; import Utils.AndLadder; -import Unstable.Arithmetic.RippleCarryTTKIncByLE; +import Std.Arithmetic.RippleCarryTTKIncByLE, Std.Arithmetic.ApplyIfGreaterLE; import Std.Diagnostics.Fact; -import Unstable.Arithmetic.ApplyIfGreaterLE; /// # Summary /// Square signed integer `xs` and store diff --git a/library/src/tests.rs b/library/src/tests.rs index 0d801d5c78..ec5aaf503a 100644 --- a/library/src/tests.rs +++ b/library/src/tests.rs @@ -16,7 +16,7 @@ mod table_lookup; use indoc::indoc; use qsc::{ - interpret::{GenericReceiver, Interpreter, Result, Value}, + interpret::{self, GenericReceiver, Interpreter, Result, Value}, target::Profile, Backend, LanguageFeatures, PackageType, SourceMap, SparseSim, }; @@ -30,6 +30,15 @@ pub fn test_expression(expr: &str, expected: &Value) -> String { test_expression_with_lib(expr, "", expected) } +pub fn test_expression_fails(expr: &str) -> String { + test_expression_fails_with_lib_and_profile_and_sim( + expr, + "", + Profile::Unrestricted, + &mut SparseSim::default(), + ) +} + pub fn test_expression_with_lib(expr: &str, lib: &str, expected: &Value) -> String { test_expression_with_lib_and_profile(expr, lib, Profile::Unrestricted, expected) } @@ -93,6 +102,45 @@ pub fn test_expression_with_lib_and_profile_and_sim( String::from_utf8(stdout).expect("stdout should be valid utf8") } +pub fn test_expression_fails_with_lib_and_profile_and_sim( + expr: &str, + lib: &str, + profile: Profile, + sim: &mut impl Backend>, +) -> String { + let mut stdout = vec![]; + let mut out = GenericReceiver::new(&mut stdout); + + let sources = SourceMap::new([("test".into(), lib.into())], Some(expr.into())); + + let (std_id, store) = qsc::compile::package_store_with_stdlib(profile.into()); + + let mut interpreter = Interpreter::new( + sources, + PackageType::Exe, + profile.into(), + LanguageFeatures::default(), + store, + &[(std_id, None)], + ) + .expect("test should compile"); + + let result = interpreter + .eval_entry_with_sim(sim, &mut out) + .expect_err("test should run successfully"); + + assert!( + result.len() == 1, + "Expected a single error, got {:?}", + result.len() + ); + let interpret::Error::Eval(err) = &result[0] else { + panic!("Expected an Eval error, got {:?}", result[0]); + }; + + err.error().error().to_string() +} + /// # Panics /// /// Will panic if f64 values are significantly different. diff --git a/library/src/tests/intrinsic.rs b/library/src/tests/intrinsic.rs index c9ff5effa5..f58223c883 100644 --- a/library/src/tests/intrinsic.rs +++ b/library/src/tests/intrinsic.rs @@ -7,7 +7,7 @@ use expect_test::expect; use indoc::indoc; use qsc::{interpret::Value, target::Profile, SparseSim}; -use super::{test_expression, test_expression_with_lib_and_profile_and_sim}; +use super::{test_expression, test_expression_fails, test_expression_with_lib_and_profile_and_sim}; // These tests verify multi-controlled decomposition logic for gate operations. Each test // manually allocates 2N qubits, performs the decomposed operation from the library on the first N, @@ -3008,3 +3008,142 @@ fn test_exp() { "#]] .assert_eq(&dump); } + +#[test] +fn test_apply_unitary_with_h_matrix() { + let dump = test_expression( + indoc! {" + { + open Std.Math; + open Std.Diagnostics; + use q = Qubit(); + let one_sqrt_2 = new Complex { Real = 1.0 / Sqrt(2.0), Imag = 0.0 }; + ApplyUnitary( + [ + [one_sqrt_2, one_sqrt_2], + [one_sqrt_2, NegationC(one_sqrt_2)] + ], + [q] + ); + DumpMachine(); + Reset(q); + } + "}, + &Value::unit(), + ); + + expect![[r#" + STATE: + |0⟩: 0.7071+0.0000𝑖 + |1⟩: 0.7071+0.0000𝑖 + "#]] + .assert_eq(&dump); +} + +#[test] +fn test_apply_unitary_with_swap_matrix() { + let dump = test_expression( + indoc! {" + { + open Std.Math; + open Std.Diagnostics; + use qs = Qubit[2]; + H(qs[0]); + DumpMachine(); + let one = new Complex { Real = 1.0, Imag = 0.0 }; + let zero = new Complex { Real = 0.0, Imag = 0.0 }; + ApplyUnitary( + [ + [one, zero, zero, zero], + [zero, zero, one, zero], + [zero, one, zero, zero], + [zero, zero, zero, one] + ], + qs + ); + DumpMachine(); + ResetAll(qs); + } + "}, + &Value::unit(), + ); + + expect![[r#" + STATE: + |00⟩: 0.7071+0.0000𝑖 + |10⟩: 0.7071+0.0000𝑖 + STATE: + |00⟩: 0.7071+0.0000𝑖 + |01⟩: 0.7071+0.0000𝑖 + "#]] + .assert_eq(&dump); +} + +#[test] +fn test_apply_unitary_fails_when_matrix_not_square() { + let err = test_expression_fails(indoc! {" + { + open Std.Math; + open Std.Diagnostics; + use q = Qubit(); + ApplyUnitary( + [ + [new Complex { Real = 1.0, Imag = 0.0 }], + [new Complex { Real = 0.0, Imag = 0.0 }] + ], + [q] + ); + DumpMachine(); + Reset(q); + } + "}); + + expect!["program failed: matrix passed to ApplyUnitary must be square."].assert_eq(&err); +} + +#[test] +fn test_apply_unitary_fails_when_matrix_wrong_size() { + let err = test_expression_fails(indoc! {" + { + open Std.Math; + open Std.Diagnostics; + use qs = Qubit[2]; + let one_sqrt_2 = new Complex { Real = 1.0 / Sqrt(2.0), Imag = 0.0 }; + ApplyUnitary( + [ + [one_sqrt_2, one_sqrt_2], + [one_sqrt_2, NegationC(one_sqrt_2)] + ], + qs + ); + DumpMachine(); + ResetAll(qs); + } + "}); + + expect!["program failed: matrix passed to ApplyUnitary must have dimensions 2^Length(qubits)."] + .assert_eq(&err); +} + +#[test] +fn test_apply_unitary_fails_when_matrix_not_unitary() { + let err = test_expression_fails(indoc! {" + { + open Std.Math; + open Std.Diagnostics; + use q = Qubit(); + let zero = new Complex { Real = 0.0, Imag = 0.0 }; + ApplyUnitary( + [ + [zero, zero], + [zero, zero] + ], + [q] + ); + DumpMachine(); + Reset(q); + } + "}); + + expect!["intrinsic callable `Apply` failed: matrix is not unitary"].assert_eq(&err); +} diff --git a/library/src/tests/resources/src/add_le.qs b/library/src/tests/resources/src/add_le.qs index 766ebfb785..1e54735cb0 100644 --- a/library/src/tests/resources/src/add_le.qs +++ b/library/src/tests/resources/src/add_le.qs @@ -1,5 +1,5 @@ namespace Test { - import Microsoft.Quantum.Unstable.Arithmetic.*; + import Std.Arithmetic.*; import Std.Convert.*; import Std.Diagnostics.*; diff --git a/library/src/tests/resources/src/compare.qs b/library/src/tests/resources/src/compare.qs index 09bc3a205e..17e37f0ddd 100644 --- a/library/src/tests/resources/src/compare.qs +++ b/library/src/tests/resources/src/compare.qs @@ -1,5 +1,5 @@ namespace Test { - import Microsoft.Quantum.Unstable.Arithmetic.*; + import Std.Arithmetic.*; import Std.Convert.*; import Std.Diagnostics.*; diff --git a/library/src/tests/resources/src/inc_by_le.qs b/library/src/tests/resources/src/inc_by_le.qs index 0a0ddf453f..1a25f13a3c 100644 --- a/library/src/tests/resources/src/inc_by_le.qs +++ b/library/src/tests/resources/src/inc_by_le.qs @@ -1,5 +1,5 @@ namespace Test { - import Microsoft.Quantum.Unstable.Arithmetic.*; + import Std.Arithmetic.*; import Std.Convert.*; import Std.Diagnostics.*; diff --git a/library/src/tests/resources/src/select.qs b/library/src/tests/resources/src/select.qs index 7d70a523ea..af3a48bc36 100644 --- a/library/src/tests/resources/src/select.qs +++ b/library/src/tests/resources/src/select.qs @@ -3,7 +3,7 @@ namespace Test { import Std.Convert.*; import Std.Diagnostics.*; import Std.Random.*; - import Microsoft.Quantum.Unstable.TableLookup.*; + import Std.TableLookup.*; internal operation TestSelect(addressBits : Int, dataBits : Int) : Unit { use addressRegister = Qubit[addressBits]; diff --git a/library/src/tests/resources/src/state_preparation.qs b/library/src/tests/resources/src/state_preparation.qs index b9400f3b06..9b2e30d03e 100644 --- a/library/src/tests/resources/src/state_preparation.qs +++ b/library/src/tests/resources/src/state_preparation.qs @@ -3,7 +3,7 @@ namespace Test { import Std.Math.*; import Std.Diagnostics.*; import Std.Arrays.*; - import Microsoft.Quantum.Unstable.StatePreparation.*; + import Std.StatePreparation.*; import QIR.Intrinsic.*; diff --git a/library/std/README.md b/library/std/README.md index 23dce7d6ed..d693899a47 100644 --- a/library/std/README.md +++ b/library/std/README.md @@ -12,11 +12,9 @@ Files in the library match the contained namespace. This makes it easier to find Unless otherwise noted, callables that are defined as `body intrinsic` are generated into external declarations in QIR with exact callable name and signature matches. The containing namespace is not included in the generated name. This simplifies QIR code generation and makes correlating Q# declaration to the resulting QIR program easier. Body intrinsic callables should avoid using generics and aggregate types if possible to keep the corresponding LLVM signatures simple and increase the likelihood of hardware compatibility. -One notable exception to this is the `Microsoft.Quantum.Core.Length` function, which is both `body intrinsic` and generic across the array type. As a result, it needs special handling during monomorphization and code generation to correlate it to the right pattern for extracting length from the array structure. Open question: should this be transitioned to an operator or some other form that avoid such a prominent counterexample? - ### QIR Quantum Gate Instructions -The library includes a set of one- and two-qubit gates represented as `__quantum__qis__*__body` or `__quantum__qis__*__adj` QIR declarations. The expectation is that these gates form a common QIR API surface that Q# is compiled into. Any target would either need to support these quantum gate instructions natively or provide a QIR definition of that gate instruction in terms of supported native gates. These definitions can then be linked with the QIR program via LLVM tools and resolve to the target specific gate set. This approach provides broader compatibility at the QIR level and avoids the need for front end language targetting; as a result, this Q# library design is not expected to require any target packages or operation substitution. +The library includes a set of one- and two-qubit gates represented as `__quantum__qis__*__body` or `__quantum__qis__*__adj` QIR declarations. The expectation is that these gates form a common QIR API surface that Q# is compiled into. Any target would either need to support these quantum gate instructions natively or provide a QIR definition of that gate instruction in terms of supported native gates. These definitions can then be linked with the QIR program via LLVM tools and resolve to the target specific gate set. This approach provides broader compatibility at the QIR level and avoids the need for front end language targeting; as a result, this Q# library design is not expected to require any target packages or operation substitution. To avoid using any opaque array types in the quantum gate instruction set, the library utilizes decomposition strategies to express the Q# controlled specialization (which allows an arbitrary number of controls) in terms of singly- and doubly-controlled gates. While this makes simulation somewhat more expensive in terms of allocating extra controls and performing more operations, it more closely matches the patterns used by hardware and provides better API surface for QIR programs to have hardware compatibility. diff --git a/library/std/src/Std/Arrays.qs b/library/std/src/Std/Arrays.qs index ff577e0ff3..b335926d36 100644 --- a/library/std/src/Std/Arrays.qs +++ b/library/std/src/Std/Arrays.qs @@ -171,8 +171,8 @@ function CircularlyShifted<'T>(stepCount : Int, array : 'T[]) : 'T[] { /// ``` /// /// # See Also -/// - Microsoft.Quantum.Arrays.Transposed -/// - Microsoft.Quantum.Arrays.Diagonal +/// - [Std.Arrays.Transposed](xref:Qdk.Std.Arrays.Transposed) +/// - [Std.Arrays.Diagonal](xref:Qdk.Std.Arrays.Diagonal) function ColumnAt<'T>(column : Int, matrix : 'T[][]) : 'T[] { Fact(IsRectangularArray(matrix), "`matrix` is not a rectangular array"); mutable columnValues = []; @@ -238,7 +238,7 @@ function Count<'T>(predicate : ('T -> Bool), array : 'T[]) : Int { /// ``` /// /// # See Also -/// - Microsoft.Quantum.Arrays.Transposed +/// - [Std.Arrays.Transposed](xref:Qdk.Std.Arrays.Transposed) function Diagonal<'T>(matrix : 'T[][]) : 'T[] { Fact(IsRectangularArray(matrix), "`matrix` is not a rectangular array"); let rows = Length(matrix); @@ -274,7 +274,7 @@ function Diagonal<'T>(matrix : 'T[][]) : 'T[] { /// The following samples an alternating array of results. /// ```qsharp /// use qubit = Qubit(); -/// let results = Microsoft.Quantum.Arrays.DrawMany(q => {X(q); M(q)}, 3, qubit); +/// let results = Std.Arrays.DrawMany(q => {X(q); M(q)}, 3, qubit); /// ``` operation DrawMany<'TInput, 'TOutput>(op : ('TInput => 'TOutput), nSamples : Int, input : 'TInput) : 'TOutput[] { mutable outputs = []; @@ -505,7 +505,7 @@ function Fold<'State, 'T>(folder : (('State, 'T) -> 'State), state : 'State, arr /// An array `'U[]` of elements that are mapped by the `action` operation. /// /// # See Also -/// - Microsoft.Quantum.Arrays.Mapped +/// - [Std.Arrays.Mapped](xref:Qdk.Std.Arrays.Mapped) operation ForEach<'T, 'U>(action : ('T => 'U), array : 'T[]) : 'U[] { mutable output = []; for element in array { @@ -686,7 +686,7 @@ function IsEmpty<'T>(array : 'T[]) : Bool { /// ``` /// /// # See Also -/// - Microsoft.Quantum.Arrays.IsSquareArray +/// - [Std.Arrays.IsSquareArray](xref:Qdk.Std.Arrays.IsSquareArray) function IsRectangularArray<'T>(array : 'T[][]) : Bool { if (Length(array) > 0) { let columnCount = Length(Head(array)); @@ -754,7 +754,7 @@ function IsSorted<'T>(comparison : (('T, 'T) -> Bool), array : 'T[]) : Bool { /// `true` if the array is square, `false` otherwise. /// /// # See Also -/// - Microsoft.Quantum.Arrays.IsRectangularArray +/// - [Std.Arrays.IsRectangularArray](xref:Qdk.Std.Arrays.IsRectangularArray) function IsSquareArray<'T>(array : 'T[][]) : Bool { if (Length(array) > 0) { let columnCount = Length(array); @@ -789,7 +789,7 @@ function IsSquareArray<'T>(array : 'T[][]) : Bool { /// An array `'U[]` of elements that are mapped by the `mapper` function. /// /// # See Also -/// - Microsoft.Quantum.Arrays.ForEach +/// - [Std.Arrays.ForEach](xref:Qdk.Std.Arrays.ForEach) function Mapped<'T, 'U>(mapper : ('T -> 'U), array : 'T[]) : 'U[] { mutable mapped = []; for element in array { @@ -830,7 +830,7 @@ function Mapped<'T, 'U>(mapper : ('T -> 'U), array : 'T[]) : 'U[] { /// ``` /// /// # See Also -/// - Microsoft.Quantum.Arrays.Mapped +/// - [Std.Arrays.Mapped](xref:Qdk.Std.Arrays.Mapped) function MappedByIndex<'T, 'U>(mapper : ((Int, 'T) -> 'U), array : 'T[]) : 'U[] { mutable mapped = []; for index in 0..Length(array) - 1 { @@ -865,7 +865,7 @@ function MappedByIndex<'T, 'U>(mapper : ((Int, 'T) -> 'U), array : 'T[]) : 'U[] /// ``` /// /// # See Also -/// - Microsoft.Quantum.Arrays.Mapped +/// - [Std.Arrays.Mapped](xref:Qdk.Std.Arrays.Mapped) function MappedOverRange<'T>(mapper : (Int -> 'T), range : Range) : 'T[] { mutable output = []; for element in range { @@ -1320,7 +1320,7 @@ function Tail<'A>(array : 'A[]) : 'A { /// ``` /// /// # See Also -/// - Microsoft.Quantum.Arrays.Zipped +/// - [Std.Arrays.Zipped](xref:Qdk.Std.Arrays.Zipped) function Unzipped<'T, 'U>(array : ('T, 'U)[]) : ('T[], 'U[]) { mutable first = []; mutable second = []; @@ -1429,7 +1429,7 @@ function Windows<'T>(size : Int, array : 'T[]) : 'T[][] { /// ``` /// /// # See Also -/// - Microsoft.Quantum.Arrays.Unzipped +/// - [Std.Arrays.Unzipped](xref:Qdk.Std.Arrays.Unzipped) function Zipped<'T, 'U>(left : 'T[], right : 'U[]) : ('T, 'U)[] { let arrayLength = MinI(Length(left), Length(right)); mutable zipped = []; diff --git a/library/std/src/Std/Canon.qs b/library/std/src/Std/Canon.qs index 94ae4e4e72..98751cc66a 100644 --- a/library/std/src/Std/Canon.qs +++ b/library/std/src/Std/Canon.qs @@ -54,7 +54,7 @@ operation ApplyToEach<'T>(singleElementOperation : ('T => Unit), register : 'T[] /// ``` /// /// # See Also -/// - Microsoft.Quantum.Canon.ApplyToEach +/// - [Std.Canon.ApplyToEach](xref:Qdk.Std.Canon.ApplyToEach) operation ApplyToEachA<'T>(singleElementOperation : ('T => Unit is Adj), register : 'T[]) : Unit is Adj { for item in register { singleElementOperation(item); @@ -83,7 +83,7 @@ operation ApplyToEachA<'T>(singleElementOperation : ('T => Unit is Adj), registe /// ``` /// /// # See Also -/// - Microsoft.Quantum.Canon.ApplyToEach +/// - [Std.Canon.ApplyToEach](xref:Qdk.Std.Canon.ApplyToEach) operation ApplyToEachC<'T>(singleElementOperation : ('T => Unit is Ctl), register : 'T[]) : Unit is Ctl { for item in register { singleElementOperation(item); @@ -112,7 +112,7 @@ operation ApplyToEachC<'T>(singleElementOperation : ('T => Unit is Ctl), registe /// ``` /// /// # See Also -/// - Microsoft.Quantum.Canon.ApplyToEach +/// - [Std.Canon.ApplyToEach](xref:Qdk.Std.Canon.ApplyToEach) operation ApplyToEachCA<'T>(singleElementOperation : ('T => Unit is Adj + Ctl), register : 'T[]) : Unit is Adj + Ctl { for item in register { singleElementOperation(item); diff --git a/library/std/src/Std/Intrinsic.qs b/library/std/src/Std/Intrinsic.qs index 1cc3e1f1d6..67465050f9 100644 --- a/library/std/src/Std/Intrinsic.qs +++ b/library/std/src/Std/Intrinsic.qs @@ -463,7 +463,7 @@ operation R1(theta : Double, qubit : Qubit) : Unit is Adj + Ctl { /// /// WARNING: /// This operation uses the **opposite** sign convention from -/// Microsoft.Quantum.Intrinsic.R. +/// Std.Intrinsic.R. /// /// # Input /// ## numerator @@ -523,7 +523,7 @@ operation ResetAll(qubits : Qubit[]) : Unit { /// /// WARNING: /// This operation uses the **opposite** sign convention from -/// Microsoft.Quantum.Intrinsic.R. +/// Std.Intrinsic.R. /// /// # Input /// ## pauli @@ -1140,6 +1140,55 @@ operation Z(qubit : Qubit) : Unit is Adj + Ctl { adjoint self; } +/// # Summary +/// Applies the given unitary matrix to the given qubits. The matrix is checked at runtime to ensure it's shape is square and that the matrix dimensions are `2 ^ Length(qubits)`. +/// This operation is simulator-only and is not supported on hardware. +/// +/// # Input +/// ## matrix +/// The unitary matrix to apply. +/// ## qubits +/// The qubits to which the unitary matrix should be applied. +/// +/// # Example +/// This performs a two qubit CNOT using the unitary matrix representation: +/// ```qsharp +/// import Std.Math.Complex; +/// use qs = Qubit[2]; +/// let one = new Complex { Real = 1.0, Imag = 0.0 }; +/// let zero = new Complex { Real = 0.0, Imag = 0.0 }; +/// ApplyUnitary( +/// [ +/// [one, zero, zero, zero], +/// [zero, one, zero, zero], +/// [zero, zero, zero, one], +/// [zero, zero, one, zero] +/// ], +/// qs +/// ); +/// ``` +@Config(Unrestricted) +operation ApplyUnitary(matrix : Complex[][], qubits : Qubit[]) : Unit { + let num_rows = Length(matrix); + for col in matrix { + if Length(col) != num_rows { + fail "matrix passed to ApplyUnitary must be square."; + } + } + + let num_qubits = Length(qubits); + if num_rows != 1 <<< num_qubits { + fail "matrix passed to ApplyUnitary must have dimensions 2^Length(qubits)."; + } + + Apply(matrix, qubits); +} + +@Config(Unrestricted) +operation Apply(matrix : Complex[][], qubits : Qubit[]) : Unit { + body intrinsic; +} + /// # Summary /// Logs a message. /// @@ -1155,4 +1204,4 @@ function Message(msg : String) : Unit { body intrinsic; } -export AND, CCNOT, CNOT, Exp, H, I, M, Measure, R, R1, R1Frac, Reset, ResetAll, RFrac, Rx, Rxx, Ry, Ryy, Rz, Rzz, S, SWAP, T, X, Y, Z, Message; +export AND, CCNOT, CNOT, Exp, H, I, M, Measure, R, R1, R1Frac, Reset, ResetAll, RFrac, Rx, Rxx, Ry, Ryy, Rz, Rzz, S, SWAP, T, X, Y, Z, ApplyUnitary, Message; diff --git a/library/std/src/Std/Math.qs b/library/std/src/Std/Math.qs index 281fcfef4a..e3dc39138f 100644 --- a/library/std/src/Std/Math.qs +++ b/library/std/src/Std/Math.qs @@ -22,7 +22,7 @@ import Std.Diagnostics.*; /// [Wikipedia article - Pi](https://en.wikipedia.org/wiki/Pi) /// /// # See Also -/// - Microsoft.Quantum.Math.E +/// - [Std.Math.E](xref:Qdk.Std.Math.E) function PI() : Double { 3.14159265358979323846 } @@ -39,7 +39,7 @@ function PI() : Double { /// [Wikipedia article - e](https://en.wikipedia.org/wiki/E_(mathematical_constant)) /// /// # See Also -/// - Microsoft.Quantum.Math.PI +/// - [Std.Math.PI](xref:Qdk.Std.Math.PI) function E() : Double { 2.7182818284590452354 } @@ -103,7 +103,7 @@ function IsNaN(d : Double) : Bool { /// ``` /// /// # See Also -/// - Microsoft.Quantum.Math.IsNaN +/// - [Std.Math.IsNaN](xref:Qdk.Std.Math.IsNaN) function IsInfinite(d : Double) : Bool { return d == 1.0 / 0.0 or d == -1.0 / 0.0; } @@ -820,11 +820,11 @@ function HammingWeightI(n : Int) : Int { /// The factorial of `n`. /// /// # Remarks -/// For inputs greater than 20, please use `Microsoft.Quantum.Math.FactorialL`. +/// For inputs greater than 20, please use `Std.Math.FactorialL`. /// /// # See Also -/// - Microsoft.Quantum.Math.FactorialL -/// - Microsoft.Quantum.Math.ApproximateFactorial +/// - [Std.Math.FactorialL](xref:Qdk.Std.Math.FactorialL) +/// - [Std.Math.ApproximateFactorial](xref:Qdk.Std.Math.ApproximateFactorial) function FactorialI(n : Int) : Int { Fact(n >= 0, "The factorial is not defined for negative inputs."); Fact(n <= 20, "The largest factorial that can be stored as an Int is 20!. Use FactorialL or ApproximateFactorial."); @@ -865,8 +865,8 @@ function FactorialI(n : Int) : Int { /// The factorial of `n`. /// /// # See Also -/// - Microsoft.Quantum.Math.FactorialI -/// - Microsoft.Quantum.Math.ApproximateFactorial +/// - [Std.Math.FactorialI](xref:Qdk.Std.Math.FactorialI) +/// - [Std.Math.ApproximateFactorial](xref:Qdk.Std.Math.ApproximateFactorial) function FactorialL(n : Int) : BigInt { Fact(n >= 0, "The factorial is not defined for negative inputs."); @@ -896,8 +896,8 @@ function FactorialL(n : Int) : BigInt { /// The approximate factorial of `n`. /// /// # See Also -/// - Microsoft.Quantum.Math.FactorialI -/// - Microsoft.Quantum.Math.FactorialL +/// - [Std.Math.FactorialI](xref:Qdk.Std.Math.FactorialI) +/// - [Std.Math.FactorialL](xref:Qdk.Std.Math.FactorialL) function ApproximateFactorial(n : Int) : Double { Fact(n >= 0, "The factorial is not defined for negative inputs."); Fact(n <= 169, "The largest approximate factorial that can be stored as a Double is 169!. Use FactorialL."); @@ -979,9 +979,9 @@ function LogGammaD(x : Double) : Double { /// The natural logarithm of the factorial of the provided input. /// /// # See Also -/// - Microsoft.Quantum.Math.ApproximateFactorial -/// - Microsoft.Quantum.Math.FactorialI -/// - Microsoft.Quantum.Math.FactorialL +/// - [Std.Math.ApproximateFactorial](xref:Qdk.Std.Math.ApproximateFactorial) +/// - [Std.Math.FactorialI](xref:Qdk.Std.Math.FactorialI) +/// - [Std.Math.FactorialL](xref:Qdk.Std.Math.FactorialL) function LogFactorialD(n : Int) : Double { LogGammaD(IntAsDouble(n) + 1.0) } diff --git a/library/std/src/Std/Measurement.qs b/library/std/src/Std/Measurement.qs index 8639b947c4..81bc287eaa 100644 --- a/library/std/src/Std/Measurement.qs +++ b/library/std/src/Std/Measurement.qs @@ -24,7 +24,7 @@ open QIR.Intrinsic; /// The result of measuring in the `Z ⊗ Z ⊗ ••• ⊗ Z` basis. /// /// # See also -/// - Microsoft.Quantum.Measurement.MeasureEachZ +/// - [Std.Measurement.MeasureEachZ](xref:Qdk.Std.Measurement.MeasureEachZ) operation MeasureAllZ(register : Qubit[]) : Result { Measure(Repeated(PauliZ, Length(register)), register) } @@ -54,8 +54,8 @@ operation MeasureAllZ(register : Qubit[]) : Result { /// and returns one result. The operation does not reset the qubits. /// /// # See also -/// - Microsoft.Quantum.Measurement.MeasureAllZ -/// - Microsoft.Quantum.Measurement.MResetEachZ +/// - [Std.Measurement.MeasureAllZ](xref:Qdk.Std.Measurement.MeasureAllZ) +/// - [Std.Measurement.MResetEachZ](xref:Qdk.Std.Measurement.MResetEachZ) operation MeasureEachZ(register : Qubit[]) : Result[] { mutable results = []; for qubit in register { @@ -76,7 +76,7 @@ operation MeasureEachZ(register : Qubit[]) : Result[] { /// An array of measurement results. /// /// # See also -/// - Microsoft.Quantum.Measurement.MeasureEachZ +/// - [Std.Measurement.MeasureEachZ](xref:Qdk.Std.Measurement.MeasureEachZ) operation MResetEachZ(register : Qubit[]) : Result[] { mutable results = []; for qubit in register { diff --git a/library/std/src/Std/StatePreparation.qs b/library/std/src/Std/StatePreparation.qs index 186d3cb03f..1b67ab7d03 100644 --- a/library/std/src/Std/StatePreparation.qs +++ b/library/std/src/Std/StatePreparation.qs @@ -52,7 +52,7 @@ import /// Vivek V. Shende, Stephen S. Bullock, Igor L. Markov /// /// # See Also -/// - Unstable.StatePreparation.ApproximatelyPreparePureStateCP +/// - Std.StatePreparation.ApproximatelyPreparePureStateCP operation PreparePureStateD(coefficients : Double[], qubits : Qubit[]) : Unit is Adj + Ctl { let coefficientsAsComplexPolar = Mapped(a -> ComplexAsComplexPolar(Complex(a, 0.0)), coefficients); ApproximatelyPreparePureStateCP(0.0, coefficientsAsComplexPolar, qubits); diff --git a/library/std/src/Std/TableLookup.qs b/library/std/src/Std/TableLookup.qs index df690bf5c1..e4365cd56a 100644 --- a/library/std/src/Std/TableLookup.qs +++ b/library/std/src/Std/TableLookup.qs @@ -110,7 +110,7 @@ operation SinglyControlledSelect( ) : Unit { let (N, n) = DimensionsForSelect(data, address); - if BeginEstimateCaching("Unstable.TableLookup.SinglyControlledSelect", N) { + if BeginEstimateCaching("Std.TableLookup.SinglyControlledSelect", N) { if N == 1 { // base case Controlled WriteMemoryContents([ctl], (Head(data), target)); diff --git a/npm/qsharp/test/basics.js b/npm/qsharp/test/basics.js index 8ffb034418..5372aa65d0 100644 --- a/npm/qsharp/test/basics.js +++ b/npm/qsharp/test/basics.js @@ -187,7 +187,7 @@ async function runExerciseSolutionCheck(exercise, solution) { async function getAllKataExamples(kata) { let examples = []; - // Get all the examples conatined in solution explanations. + // Get all the examples contained in solution explanations. const exerciseExamples = kata.sections .filter((section) => section.type === "exercise") .map((exercise) => diff --git a/pip/qsharp/interop/qiskit/backends/backend_base.py b/pip/qsharp/interop/qiskit/backends/backend_base.py index 5faf2c2557..a6b18d8ea2 100644 --- a/pip/qsharp/interop/qiskit/backends/backend_base.py +++ b/pip/qsharp/interop/qiskit/backends/backend_base.py @@ -12,6 +12,7 @@ from qiskit.circuit import ( QuantumCircuit, ) +from qiskit.version import get_version_info from qiskit.qasm3.exporter import Exporter from qiskit.providers import BackendV2, Options @@ -319,19 +320,26 @@ def _transpile(self, circuit: QuantumCircuit, **options) -> QuantumCircuit: circuit = self.run_qiskit_passes(circuit, options) - orig = self.target.num_qubits - try: - self.target.num_qubits = circuit.num_qubits - transpile_options = self._build_transpile_options(**options) - backend = transpile_options.pop("backend", self) - target = transpile_options.pop("target", self.target) - # in 1.3 add qubits_initially_zero=True to the transpile call + transpile_options = self._build_transpile_options(**options) + backend = transpile_options.pop("backend", self) + target = transpile_options.pop("target", self.target) + if get_version_info().startswith("1.2"): + # The older Qiskit version does not support the `qubits_initially_zero` option transpiled_circuit = transpile( - circuit, backend=backend, target=target, **transpile_options + circuit, + backend=backend, + target=target, + **transpile_options, ) - return transpiled_circuit - finally: - self.target.num_qubits = orig + else: + transpiled_circuit = transpile( + circuit, + backend=backend, + target=target, + qubits_initially_zero=True, + **transpile_options, + ) + return transpiled_circuit def run_qiskit_passes(self, circuit, options): pass_options = self._build_qiskit_pass_options(**options) diff --git a/pip/qsharp/interop/qiskit/backends/qirtarget.py b/pip/qsharp/interop/qiskit/backends/qirtarget.py index 7954094e95..51db0b0e33 100644 --- a/pip/qsharp/interop/qiskit/backends/qirtarget.py +++ b/pip/qsharp/interop/qiskit/backends/qirtarget.py @@ -61,6 +61,8 @@ def __init__( ): super().__init__(num_qubits=num_qubits) + self._num_qubits = num_qubits + if target_profile != TargetProfile.Base: self.add_instruction(ControlFlowOp, name="control_flow") self.add_instruction(IfElseOp, name="if_else") @@ -121,3 +123,16 @@ def __init__( self.add_instruction(IGate, name="id") self.add_instruction(CHGate, name="ch") + + # NOTE: The follow property intentionally shadows the property on the parent class to allow it to return `None` + # when the value is not set, which allows bypassing transpilation checks for number of qubits. Without this, + # versions of Qiskit 1.3.0 and higher default to `0` which will fail later checks. + @property + def num_qubits(self): + return self._num_qubits + + # NOTE: The follow property setter intentionally shadows the property on the parent class to allow it to be set, which + # maintains compatiblity with Qiskit versions before 1.3.0 where the property was settable. + @num_qubits.setter + def num_qubits(self, value): + self._num_qubits = value diff --git a/pip/tests-integration/interop_qiskit/test_gate_correctness.py b/pip/tests-integration/interop_qiskit/test_gate_correctness.py index b2cf697cf3..723bb9f650 100644 --- a/pip/tests-integration/interop_qiskit/test_gate_correctness.py +++ b/pip/tests-integration/interop_qiskit/test_gate_correctness.py @@ -242,7 +242,13 @@ def _test_circuit( ): target_profile = TargetProfile.Base seed = 42 - backend = QSharpBackend(target_profile=target_profile, seed=seed) + backend = QSharpBackend( + target_profile=target_profile, + seed=seed, + transpile_options={ + "optimization_level": 0 # Use no optimization to get consistent results in simulations + }, + ) try: job = backend.run(circuit, shots=num_shots) result = job.result() diff --git a/pip/tests-integration/interop_qiskit/test_gateset_qasm.py b/pip/tests-integration/interop_qiskit/test_gateset_qasm.py index 66df35227c..68245e33ce 100644 --- a/pip/tests-integration/interop_qiskit/test_gateset_qasm.py +++ b/pip/tests-integration/interop_qiskit/test_gateset_qasm.py @@ -16,6 +16,9 @@ def run_transpile_test( ) -> None: circuit = QuantumCircuit(3, 3) operation(circuit) + if "optimization_level" not in options: + # Use no optimization so gate transpilation is consistent + options["optimization_level"] = 0 info = QSharpBackend()._qasm3(circuit, **options) lines = info.splitlines() # remove the first four lines, which are the header diff --git a/pip/tests-integration/interop_qiskit/test_re.py b/pip/tests-integration/interop_qiskit/test_re.py index 01777ca841..d4dee46571 100644 --- a/pip/tests-integration/interop_qiskit/test_re.py +++ b/pip/tests-integration/interop_qiskit/test_re.py @@ -38,7 +38,7 @@ def test_qsharp_estimation_with_single_params() -> None: for index in range(10): circuit.t(index) circuit.measure(index, index) - sim = ResourceEstimatorBackend() + sim = ResourceEstimatorBackend(transpile_options={"optimization_level": 0}) res = sim.run(circuit, params=params).result() assert res["status"] == "success" @@ -69,8 +69,8 @@ def test_estimate_qiskit_rgqft_multiplier() -> None: { "numQubits": 16, "tCount": 90, - "rotationCount": 958, - "rotationDepth": 658, + "rotationCount": 1002, + "rotationDepth": 680, "cczCount": 0, "ccixCount": 0, "measurementCount": 0, @@ -94,8 +94,8 @@ def test_estimate_qiskit_rgqft_multiplier_in_threadpool() -> None: { "numQubits": 16, "tCount": 90, - "rotationCount": 958, - "rotationDepth": 658, + "rotationCount": 1002, + "rotationDepth": 680, "cczCount": 0, "ccixCount": 0, "measurementCount": 0, diff --git a/pip/tests-integration/test_requirements.txt b/pip/tests-integration/test_requirements.txt index e60aedadc9..ef5088095f 100644 --- a/pip/tests-integration/test_requirements.txt +++ b/pip/tests-integration/test_requirements.txt @@ -1,5 +1,5 @@ pytest==8.2.2 -qiskit>=1.2.2,<2.0.0 +qiskit>=1.3.0,<2.0.0 qirrunner==0.7.1 pyqir==0.10.2 qiskit-aer==0.14.2 diff --git a/samples/algorithms/BernsteinVazirani.qs b/samples/algorithms/BernsteinVazirani.qs index 769f310d7d..70877115e7 100644 --- a/samples/algorithms/BernsteinVazirani.qs +++ b/samples/algorithms/BernsteinVazirani.qs @@ -1,5 +1,5 @@ /// # Sample -/// Bernstein-Vazirani algorithm +/// Bernstein-Vazirani Algorithm /// /// # Description /// The Bernstein-Vazirani algorithm determines the value of a bit string diff --git a/samples/algorithms/BernsteinVaziraniNISQ.qs b/samples/algorithms/BernsteinVaziraniNISQ.qs index 88a4a436fc..0fd8fbd0de 100644 --- a/samples/algorithms/BernsteinVaziraniNISQ.qs +++ b/samples/algorithms/BernsteinVaziraniNISQ.qs @@ -1,5 +1,5 @@ /// # Sample -/// Bernstein-Vazirani algorithm +/// Bernstein-Vazirani Algorithm /// /// # Description /// The Bernstein-Vazirani algorithm determines the value of a bit string diff --git a/samples/algorithms/DeutschJozsa.qs b/samples/algorithms/DeutschJozsa.qs index 79d53aa96b..3c127d678a 100644 --- a/samples/algorithms/DeutschJozsa.qs +++ b/samples/algorithms/DeutschJozsa.qs @@ -1,5 +1,5 @@ /// # Sample -/// Deutsch–Jozsa algorithm +/// Deutsch–Jozsa Algorithm /// /// # Description /// Deutsch–Jozsa is a quantum algorithm that determines whether a given Boolean diff --git a/samples/algorithms/DeutschJozsaNISQ.qs b/samples/algorithms/DeutschJozsaNISQ.qs index 4ebebf6c68..d2c0a081a8 100644 --- a/samples/algorithms/DeutschJozsaNISQ.qs +++ b/samples/algorithms/DeutschJozsaNISQ.qs @@ -1,5 +1,5 @@ /// # Sample -/// Deutsch–Jozsa algorithm +/// Deutsch–Jozsa Algorithm /// /// # Description /// Deutsch–Jozsa is a quantum algorithm that determines whether a given Boolean diff --git a/samples/algorithms/GHZ.qs b/samples/algorithms/GHZ.qs index 2a1a0f4443..7b418f96a4 100644 --- a/samples/algorithms/GHZ.qs +++ b/samples/algorithms/GHZ.qs @@ -1,5 +1,5 @@ /// # Sample -/// GHZ +/// Greenberger–Horne–Zeilinger /// /// # Description /// The Greenberger–Horne–Zeilinger state, or GHZ state, is a state with 3 diff --git a/samples/algorithms/Grover.qs b/samples/algorithms/Grover.qs index 40b75016d2..3118fa0267 100644 --- a/samples/algorithms/Grover.qs +++ b/samples/algorithms/Grover.qs @@ -1,5 +1,5 @@ /// # Sample -/// Grover's search algorithm +/// Grover's Search Algorithm /// /// # Description /// Grover's search algorithm is a quantum algorithm that finds with high diff --git a/samples/algorithms/HiddenShift.qs b/samples/algorithms/HiddenShift.qs index 325c95e159..ebb7159d70 100644 --- a/samples/algorithms/HiddenShift.qs +++ b/samples/algorithms/HiddenShift.qs @@ -1,5 +1,5 @@ /// # Sample -/// Hidden shift +/// Hidden Shift /// /// # Description /// There is a family of problems known as hidden shift problems, in which it diff --git a/samples/algorithms/HiddenShiftNISQ.qs b/samples/algorithms/HiddenShiftNISQ.qs index 75a8fb616c..b3bafa1b24 100644 --- a/samples/algorithms/HiddenShiftNISQ.qs +++ b/samples/algorithms/HiddenShiftNISQ.qs @@ -1,5 +1,5 @@ /// # Sample -/// Hidden shift +/// Hidden Shift /// /// # Description /// There is a family of problems known as hidden shift problems, in which it diff --git a/samples/algorithms/MajoranaQubits/qsharp.json b/samples/algorithms/MajoranaQubits/qsharp.json new file mode 100644 index 0000000000..0967ef424b --- /dev/null +++ b/samples/algorithms/MajoranaQubits/qsharp.json @@ -0,0 +1 @@ +{} diff --git a/samples/algorithms/MajoranaQubits/src/GateSet.qs b/samples/algorithms/MajoranaQubits/src/GateSet.qs new file mode 100644 index 0000000000..3396842f2b --- /dev/null +++ b/samples/algorithms/MajoranaQubits/src/GateSet.qs @@ -0,0 +1,88 @@ +/// A set of gates built upon the custom measurements +/// provided by the hardware provider. +/// +/// Source: +/// [1] Surface code compilation via edge-disjoint paths +/// https://arxiv.org/pdf/2110.11493 + +/// Apply a CNOT gate to the given qubits. +/// Source: [1] Figure 3. +operation CNOT(control : Qubit, target : Qubit) : Unit { + // Prepare an ancilla qubit in the |+⟩ state. + use ancilla = Qubit(); + PrepareX(ancilla); + + let a = Mzz(control, ancilla); + let b = Mxx(ancilla, target); + let c = Mz(ancilla); + Reset(ancilla); + + if b == One { + Z(control); + } + + if a != c { + X(target); + } +} + + +/// Prepare a qubit in the |+⟩ state. +operation PrepareX(q : Qubit) : Unit { + if Mx(q) == One { + Z(q); + } +} + +/// Prepare a qubit in the |0⟩ state. +operation PrepareZ(q : Qubit) : Unit { + if Mz(q) == One { + X(q); + } +} + +/// Prepare a Bell Pair. +/// Source: [1] Figure 18a. +operation BellPair(q1 : Qubit, q2 : Qubit) : Unit { + // Collapse the qubits onto the Pauli-Z basis. + Mz(q1); + Mz(q2); + + // If they are not aligned in the Pauli-X basis, phase flip one of them. + if Mxx(q1, q2) == One { + Z(q2); + } +} + +/// Measure a Bell Pair. +/// Source: [1] Figure 18b. +/// Below is a map showing how the Bell states map to the Result pairs: +/// |𝚽⁺⟩ -> (Zero, Zero) +/// |𝚿⁺⟩ -> (Zero, One) +/// |𝚽⁻⟩ -> (One, Zero) +/// |𝚿⁻⟩ -> (One, One) +operation BellMeasurement(q1 : Qubit, q2 : Qubit) : (Result, Result) { + let z = Mzz(q1, q2); + let x = Mxx(q1, q2); + (x, z) +} + +/// User friendly wrapper around the Mx hardware gate. +operation Mx(q : Qubit) : Result { + HardwareIntrinsics.__quantum__qis__mx__body(q) +} + +/// User friendly wrapper around the Mz hardware gate. +operation Mz(q : Qubit) : Result { + HardwareIntrinsics.__quantum__qis__mz__body(q) +} + +/// User friendly wrapper around the Mxx hardware gate. +operation Mxx(q1 : Qubit, q2 : Qubit) : Result { + HardwareIntrinsics.__quantum__qis__mxx__body(q1, q2) +} + +/// User friendly wrapper around the Mzz hardware gate. +operation Mzz(q1 : Qubit, q2 : Qubit) : Result { + HardwareIntrinsics.__quantum__qis__mzz__body(q1, q2) +} diff --git a/samples/algorithms/MajoranaQubits/src/HardwareIntrinsics.qs b/samples/algorithms/MajoranaQubits/src/HardwareIntrinsics.qs new file mode 100644 index 0000000000..0921939c71 --- /dev/null +++ b/samples/algorithms/MajoranaQubits/src/HardwareIntrinsics.qs @@ -0,0 +1,27 @@ +/// A set of custom measurements exposed from a hardware +/// provider using Majorana Qubits. + +@Measurement() +@SimulatableIntrinsic() +operation __quantum__qis__mx__body(q : Qubit) : Result { + H(q); + M(q) +} + +@Measurement() +@SimulatableIntrinsic() +operation __quantum__qis__mz__body(q : Qubit) : Result { + M(q) +} + +@Measurement() +@SimulatableIntrinsic() +operation __quantum__qis__mxx__body(q1 : Qubit, q2 : Qubit) : Result { + Std.Intrinsic.Measure([PauliX, PauliX], [q1, q2]) +} + +@Measurement() +@SimulatableIntrinsic() +operation __quantum__qis__mzz__body(q1 : Qubit, q2 : Qubit) : Result { + Std.Intrinsic.Measure([PauliZ, PauliZ], [q1, q2]) +} diff --git a/samples/algorithms/MajoranaQubits/src/Main.qs b/samples/algorithms/MajoranaQubits/src/Main.qs new file mode 100644 index 0000000000..4047d7c931 --- /dev/null +++ b/samples/algorithms/MajoranaQubits/src/Main.qs @@ -0,0 +1,30 @@ +/// # Sample +/// Majorana Qubits +/// +/// # Description +/// In hardware providing majorana qubits, common quantum operations +/// are implemented using measurements and Pauli corrections. This +/// sample shows a hypotetical hardware provider exposing some custom +/// gates to Q# and a small library built on top of it. + +/// Sample program using custom gates from a hardware provider. +operation Main() : (Result, Result) { + // Create a Bell Pair in the |𝚽⁺⟩ state. + use qs = Qubit[2]; + GateSet.BellPair(qs[0], qs[1]); + + // Applying X to any of the qubits will result in the |𝚿⁺⟩ Bell state. + // X(qs[0]); // Uncomment to try + + // Applying Z to any of the qubits will result in the |𝚽⁻⟩ Bell state. + // Z(qs[0]); // Uncomment to try + + // Applying X and Z to the pair will result in the |𝚿⁻⟩ Bell state. + // Note that they can be applied to the same Qubit. + // Z(qs[0]); // Uncomment to try + // X(qs[0]); + + let res = GateSet.BellMeasurement(qs[0], qs[1]); + ResetAll(qs); + res +} diff --git a/samples/algorithms/Shor.qs b/samples/algorithms/Shor.qs index 2383f69038..2da2d9fc97 100644 --- a/samples/algorithms/Shor.qs +++ b/samples/algorithms/Shor.qs @@ -1,5 +1,5 @@ /// # Sample -/// Shor's algorithm +/// Shor's Algorithm /// /// # Description /// Shor's algorithm is a quantum algorithm for finding the prime factors of an @@ -10,7 +10,7 @@ import Std.Convert.*; import Std.Diagnostics.*; import Std.Random.*; import Std.Math.*; -import Microsoft.Quantum.Unstable.Arithmetic.*; +import Std.Arithmetic.*; import Std.Arrays.*; operation Main() : (Int, Int) { diff --git a/samples/estimation/EkeraHastadFactoring.qs b/samples/estimation/EkeraHastadFactoring.qs index e1ccee2321..e23efb86c9 100644 --- a/samples/estimation/EkeraHastadFactoring.qs +++ b/samples/estimation/EkeraHastadFactoring.qs @@ -12,8 +12,8 @@ import Std.Convert.*; import Std.Math.*; import Std.ResourceEstimation.*; import Std.Arrays.*; -import Microsoft.Quantum.Unstable.Arithmetic.*; -import Microsoft.Quantum.Unstable.TableLookup.*; +import Std.Arithmetic.*; +import Std.TableLookup.*; // !!! IMPORTANT !!! // When computing resource estimtes from the VS Code plugin directly on this diff --git a/samples/estimation/ShorRE.qs b/samples/estimation/ShorRE.qs index e307a045cd..6804a888d6 100644 --- a/samples/estimation/ShorRE.qs +++ b/samples/estimation/ShorRE.qs @@ -13,7 +13,7 @@ import Std.Diagnostics.*; import Std.Intrinsic.*; import Std.Math.*; import Std.Measurement.*; -import Microsoft.Quantum.Unstable.Arithmetic.*; +import Std.Arithmetic.*; import Std.ResourceEstimation.*; operation Main() : Unit { diff --git a/samples/estimation/df-chemistry/chemistry.py b/samples/estimation/df-chemistry/chemistry.py index 21bd255991..10c64335f4 100644 --- a/samples/estimation/df-chemistry/chemistry.py +++ b/samples/estimation/df-chemistry/chemistry.py @@ -493,11 +493,7 @@ def ndarray2d_to_string(arr): "errorBudget": 0.01, "qubitParams": {"name": "qubit_maj_ns_e6"}, "qecScheme": {"name": "floquet_code"}, - }, - { - "qubitParams": {"name": "qubit_gate_us_e3"}, - "estimateType": "frontier", - }, + } ] else: params = [] diff --git a/samples/estimation/df-chemistry/src/DoubleFactorizedChemistry.qs b/samples/estimation/df-chemistry/src/DoubleFactorizedChemistry.qs index 91c0e59d9e..58407d788d 100644 --- a/samples/estimation/df-chemistry/src/DoubleFactorizedChemistry.qs +++ b/samples/estimation/df-chemistry/src/DoubleFactorizedChemistry.qs @@ -6,8 +6,8 @@ import Std.Convert.*; import Std.Diagnostics.*; import Std.Math.*; import Std.ResourceEstimation.*; -import Microsoft.Quantum.Unstable.Arithmetic.*; -import Microsoft.Quantum.Unstable.TableLookup.*; +import Std.Arithmetic.*; +import Std.TableLookup.*; import Prepare.*; // ------------------------------------------ // diff --git a/samples/estimation/df-chemistry/src/Prepare.qs b/samples/estimation/df-chemistry/src/Prepare.qs index f05c492540..688f3892a7 100644 --- a/samples/estimation/df-chemistry/src/Prepare.qs +++ b/samples/estimation/df-chemistry/src/Prepare.qs @@ -5,8 +5,8 @@ import Std.Convert.*; import Std.Diagnostics.*; import Std.Intrinsic.*; import Std.Math.*; -import Microsoft.Quantum.Unstable.Arithmetic.*; -import Microsoft.Quantum.Unstable.TableLookup.*; +import Std.Arithmetic.*; +import Std.TableLookup.*; // ------------------------------------- // // State preparation (public operations) // diff --git a/samples/language/CustomMeasurements.qs b/samples/language/CustomMeasurements.qs new file mode 100644 index 0000000000..8addd2d654 --- /dev/null +++ b/samples/language/CustomMeasurements.qs @@ -0,0 +1,27 @@ +// # Sample +// Custom Operations +// +// # Description +// The @Measurement attribute in Q# allows you to define custom measurements +// that are lowered to QIR in the same way the `M` measurement in the standard +// library is lowered. That means an `"irreversible"` attribute is added to +// the callable declaration and the output results are moved to the paramaters +// and treated as result registers. +// +// # Who is this for? +// The target audience are library authors targeting specific hardware. + +/// Try running the command `Q#: Get QIR for the current Q# program` +/// in VS-Code's Command Palette. +operation Main() : Result { + use q = Qubit(); + H(q); + __quantum__qis__mx__body(q) +} + +@Measurement() +@SimulatableIntrinsic() +operation __quantum__qis__mx__body(q : Qubit) : Result { + H(q); + M(q) +} diff --git a/samples/samples.mjs b/samples/samples.mjs index 6ce85e88c0..ed9bd88dac 100644 --- a/samples/samples.mjs +++ b/samples/samples.mjs @@ -17,9 +17,9 @@ export default [ { title: "Random Number Generator (Advanced)", file: "./algorithms/QRNG.qs", shots: 1000 }, { title: "Deutsch-Jozsa", file: "./algorithms/DeutschJozsaNISQ.qs", shots: 1 }, { title: "Deutsch-Jozsa (Advanced)", file: "./algorithms/DeutschJozsa.qs", shots: 1 }, - { title: "Bernstein–Vazirani", file: "./algorithms/BernsteinVaziraniNISQ.qs", shots: 1 }, - { title: "Bernstein–Vazirani (Advanced)", file: "./algorithms/BernsteinVazirani.qs", shots: 1 }, - { title: "Grover's search", file: "./algorithms/Grover.qs", shots: 100 }, + { title: "Bernstein-Vazirani", file: "./algorithms/BernsteinVaziraniNISQ.qs", shots: 1 }, + { title: "Bernstein-Vazirani (Advanced)", file: "./algorithms/BernsteinVazirani.qs", shots: 1 }, + { title: "Grover's Search", file: "./algorithms/Grover.qs", shots: 100 }, { title: "Hidden Shift", file: "./algorithms/HiddenShiftNISQ.qs", shots: 1 }, { title: "Hidden Shift (Advanced)", file: "./algorithms/HiddenShift.qs", shots: 1 }, { title: "Shor", file: "./algorithms/Shor.qs", shots: 1 }, diff --git a/samples_test/src/tests/language.rs b/samples_test/src/tests/language.rs index 4b51b10169..61b7137eca 100644 --- a/samples_test/src/tests/language.rs +++ b/samples_test/src/tests/language.rs @@ -144,6 +144,8 @@ pub const COPYANDUPDATEOPERATOR_EXPECT_DEBUG: Expect = expect![[r#" Updated array: [10, 11, 100, 13] Updated array: [10, 100, 12, 200] ()"#]]; +pub const CUSTOMMEASUREMENTS_EXPECT: Expect = expect!["Zero"]; +pub const CUSTOMMEASUREMENTS_EXPECT_DEBUG: Expect = expect!["Zero"]; pub const DATATYPES_EXPECT: Expect = expect![[r#" Binary BigInt: 42 Octal BigInt: 42 diff --git a/vscode/src/azure/providerProperties.ts b/vscode/src/azure/providerProperties.ts index e8b2176279..81f7191e9d 100644 --- a/vscode/src/azure/providerProperties.ts +++ b/vscode/src/azure/providerProperties.ts @@ -13,9 +13,8 @@ export function targetSupportQir(target: string) { // Note: Most of these should be dynamic at some point, with configuration coming // from the service, and able to be overridden by settings. return ( - target.startsWith("ionq") || - target.startsWith("quantinuum") || - target.startsWith("rigetti") + !(target == "microsoft.estimator") && + !(target.startsWith("microsoft") && target.endsWith("cpu")) ); } @@ -28,5 +27,5 @@ export function shouldExcludeProvider(provider: string) { } export function supportsAdaptive(target: string) { - return target.startsWith("quantinuum"); + return !target.startsWith("ionq") && !target.startsWith("rigetti"); } diff --git a/vscode/src/common.ts b/vscode/src/common.ts index ea6da48537..71de7e08b6 100644 --- a/vscode/src/common.ts +++ b/vscode/src/common.ts @@ -3,7 +3,7 @@ import { TextDocument, Uri, Range, Location } from "vscode"; import { Utils } from "vscode-uri"; -import { ILocation, IRange, IWorkspaceEdit } from "qsharp-lang"; +import { ILocation, IRange, IWorkspaceEdit, VSDiagnostic } from "qsharp-lang"; import * as vscode from "vscode"; export const qsharpLanguageId = "qsharp"; @@ -58,3 +58,40 @@ export function toVscodeWorkspaceEdit( } return workspaceEdit; } + +export function toVsCodeDiagnostic(d: VSDiagnostic): vscode.Diagnostic { + let severity; + switch (d.severity) { + case "error": + severity = vscode.DiagnosticSeverity.Error; + break; + case "warning": + severity = vscode.DiagnosticSeverity.Warning; + break; + case "info": + severity = vscode.DiagnosticSeverity.Information; + break; + } + const vscodeDiagnostic = new vscode.Diagnostic( + toVscodeRange(d.range), + d.message, + severity, + ); + if (d.uri && d.code) { + vscodeDiagnostic.code = { + value: d.code, + target: vscode.Uri.parse(d.uri), + }; + } else if (d.code) { + vscodeDiagnostic.code = d.code; + } + if (d.related) { + vscodeDiagnostic.relatedInformation = d.related.map((r) => { + return new vscode.DiagnosticRelatedInformation( + toVscodeLocation(r.location), + r.message, + ); + }); + } + return vscodeDiagnostic; +} diff --git a/vscode/src/diagnostics.ts b/vscode/src/diagnostics.ts index 3a4dd2503d..e0fd154c86 100644 --- a/vscode/src/diagnostics.ts +++ b/vscode/src/diagnostics.ts @@ -1,100 +1,20 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { - ILanguageService, - IQSharpError, - VSDiagnostic, - log, - qsharpLibraryUriScheme, -} from "qsharp-lang"; +import { IQSharpError, log, qsharpLibraryUriScheme } from "qsharp-lang"; import * as vscode from "vscode"; -import { toVscodeLocation, toVscodeRange, qsharpLanguageId } from "./common.js"; +import { qsharpLanguageId, toVsCodeDiagnostic } from "./common.js"; -export function startCheckingQSharp( - languageService: ILanguageService, -): vscode.Disposable[] { - return [ - ...startLanguageServiceDiagnostics(languageService), - ...startQsharpJsonDiagnostics(), - ...startCommandDiagnostics(), - ]; -} - -function startLanguageServiceDiagnostics( - languageService: ILanguageService, -): vscode.Disposable[] { - const diagCollection = - vscode.languages.createDiagnosticCollection(qsharpLanguageId); - - async function onDiagnostics(evt: { - detail: { - uri: string; - version: number; - diagnostics: VSDiagnostic[]; - }; - }) { - const diagnostics = evt.detail; - const uri = vscode.Uri.parse(diagnostics.uri); - - if (uri.scheme === qsharpLibraryUriScheme) { - // Don't report diagnostics for library files. - return; - } - - diagCollection.set( - uri, - diagnostics.diagnostics.map((d) => toVsCodeDiagnostic(d)), - ); - } - - languageService.addEventListener("diagnostics", onDiagnostics); - - return [ - { - dispose: () => { - languageService.removeEventListener("diagnostics", onDiagnostics); - }, - }, - diagCollection, - ]; -} - -export function toVsCodeDiagnostic(d: VSDiagnostic): vscode.Diagnostic { - let severity; - switch (d.severity) { - case "error": - severity = vscode.DiagnosticSeverity.Error; - break; - case "warning": - severity = vscode.DiagnosticSeverity.Warning; - break; - case "info": - severity = vscode.DiagnosticSeverity.Information; - break; - } - const vscodeDiagnostic = new vscode.Diagnostic( - toVscodeRange(d.range), - d.message, - severity, - ); - if (d.uri && d.code) { - vscodeDiagnostic.code = { - value: d.code, - target: vscode.Uri.parse(d.uri), - }; - } else if (d.code) { - vscodeDiagnostic.code = d.code; - } - if (d.related) { - vscodeDiagnostic.relatedInformation = d.related.map((r) => { - return new vscode.DiagnosticRelatedInformation( - toVscodeLocation(r.location), - r.message, - ); - }); - } - return vscodeDiagnostic; +/** + * Initialize diagnostics for `qsharp.json` files and failures + * that get reported from various Q# commands. + * + * These are distinct from the errors reported by the Q# language + * service, (a.k.a. compiler errors that get reported as you type). + * Those are initialized in `language-service/diagnostics.js` + */ +export function startOtherQSharpDiagnostics(): vscode.Disposable[] { + return [...startQsharpJsonDiagnostics(), ...startCommandDiagnostics()]; } // diff --git a/vscode/src/extension.ts b/vscode/src/extension.ts index a0061bbc17..750700f373 100644 --- a/vscode/src/extension.ts +++ b/vscode/src/extension.ts @@ -2,31 +2,17 @@ // Licensed under the MIT License. import { - ILanguageService, - getLanguageService, getLibrarySourceContent, - loadWasmModule, log, qsharpGithubUriScheme, qsharpLibraryUriScheme, } from "qsharp-lang"; import * as vscode from "vscode"; import { initAzureWorkspaces } from "./azure/commands.js"; -import { createCodeActionsProvider } from "./codeActions.js"; -import { createCodeLensProvider } from "./codeLens.js"; -import { - isQsharpDocument, - isQsharpNotebookCell, - qsharpLanguageId, -} from "./common.js"; -import { createCompletionItemProvider } from "./completion"; -import { getTarget } from "./config"; import { initProjectCreator } from "./createProject.js"; -import { activateDebugger } from "./debugger/activate"; -import { createDefinitionProvider } from "./definition"; -import { startCheckingQSharp } from "./diagnostics"; -import { createFormattingProvider } from "./format.js"; -import { createHoverProvider } from "./hover"; +import { activateDebugger } from "./debugger/activate.js"; +import { startOtherQSharpDiagnostics } from "./diagnostics.js"; +import { activateLanguageService } from "./language-service/activate.js"; import { Logging, initLogForwarder, @@ -35,29 +21,12 @@ import { import { initFileSystem } from "./memfs.js"; import { registerCreateNotebookCommand, - registerQSharpNotebookCellUpdateHandlers, registerQSharpNotebookHandlers, } from "./notebook.js"; -import { - fetchGithubRaw, - findManifestDirectory, - getGithubSourceContent, - listDirectory, - readFile, - resolvePath, - setGithubEndpoint, -} from "./projectSystem.js"; +import { getGithubSourceContent, setGithubEndpoint } from "./projectSystem.js"; import { initCodegen } from "./qirGeneration.js"; -import { createReferenceProvider } from "./references.js"; -import { createRenameProvider } from "./rename.js"; -import { createSignatureHelpProvider } from "./signature.js"; import { activateTargetProfileStatusBarItem } from "./statusbar.js"; -import { - EventType, - QsharpDocumentType, - initTelemetry, - sendTelemetryEvent, -} from "./telemetry.js"; +import { initTelemetry } from "./telemetry.js"; import { registerWebViewCommands } from "./webviewPanel.js"; export async function activate( @@ -102,6 +71,8 @@ export async function activate( ...(await activateLanguageService(context.extensionUri)), ); + context.subscriptions.push(...startOtherQSharpDiagnostics()); + context.subscriptions.push(...registerQSharpNotebookHandlers()); initAzureWorkspaces(context); @@ -123,270 +94,6 @@ export interface ExtensionApi { setGithubEndpoint: (endpoint: string) => void; } -function registerDocumentUpdateHandlers(languageService: ILanguageService) { - vscode.workspace.textDocuments.forEach((document) => { - updateIfQsharpDocument(document); - }); - - // we manually send an OpenDocument telemetry event if this is a Q# document, because the - // below subscriptions won't fire for documents that are already open when the extension is activated - vscode.workspace.textDocuments.forEach((document) => { - if (isQsharpDocument(document)) { - const documentType = isQsharpNotebookCell(document) - ? QsharpDocumentType.JupyterCell - : QsharpDocumentType.Qsharp; - sendTelemetryEvent( - EventType.OpenedDocument, - { documentType }, - { linesOfCode: document.lineCount }, - ); - } - }); - - const subscriptions = []; - subscriptions.push( - vscode.workspace.onDidOpenTextDocument((document) => { - const documentType = isQsharpNotebookCell(document) - ? QsharpDocumentType.JupyterCell - : isQsharpDocument(document) - ? QsharpDocumentType.Qsharp - : QsharpDocumentType.Other; - if (documentType !== QsharpDocumentType.Other) { - sendTelemetryEvent( - EventType.OpenedDocument, - { documentType }, - { linesOfCode: document.lineCount }, - ); - } - updateIfQsharpDocument(document); - }), - ); - - subscriptions.push( - vscode.workspace.onDidChangeTextDocument((evt) => { - updateIfQsharpDocument(evt.document); - }), - ); - - subscriptions.push( - vscode.workspace.onDidCloseTextDocument((document) => { - if (isQsharpDocument(document) && !isQsharpNotebookCell(document)) { - languageService.closeDocument(document.uri.toString()); - } - }), - ); - - // Watch manifest changes and update each document in the same project as the manifest. - subscriptions.push( - vscode.workspace.onDidSaveTextDocument((manifest) => { - updateProjectDocuments(manifest.uri); - }), - ); - - // Trigger an update on all .qs child documents when their manifest is deleted, - // so that they can get reparented to single-file-projects. - subscriptions.push( - vscode.workspace.onDidDeleteFiles((event) => { - event.files.forEach((uri) => { - updateProjectDocuments(uri); - }); - }), - ); - - // Checks if the URI belongs to a qsharp manifest, and updates all - // open documents in the same project as the manifest. - function updateProjectDocuments(manifest: vscode.Uri) { - if (manifest.scheme === "file" && manifest.fsPath.endsWith("qsharp.json")) { - const project_folder = manifest.fsPath.slice( - 0, - manifest.fsPath.length - "qsharp.json".length, - ); - vscode.workspace.textDocuments.forEach((document) => { - if ( - !document.isClosed && - // Check that the document is on the same project as the manifest. - document.fileName.startsWith(project_folder) - ) { - updateIfQsharpDocument(document); - } - }); - } - } - - function updateIfQsharpDocument(document: vscode.TextDocument) { - if (isQsharpDocument(document) && !isQsharpNotebookCell(document)) { - // Regular (not notebook) Q# document. - languageService.updateDocument( - document.uri.toString(), - document.version, - document.getText(), - ); - } - } - - return subscriptions; -} - -async function activateLanguageService(extensionUri: vscode.Uri) { - const subscriptions: vscode.Disposable[] = []; - - const languageService = await loadLanguageService(extensionUri); - - // diagnostics - subscriptions.push(...startCheckingQSharp(languageService)); - - // synchronize document contents - subscriptions.push(...registerDocumentUpdateHandlers(languageService)); - - // synchronize notebook cell contents - subscriptions.push( - ...registerQSharpNotebookCellUpdateHandlers(languageService), - ); - - // synchronize configuration - subscriptions.push(registerConfigurationChangeHandlers(languageService)); - - // format document - subscriptions.push( - vscode.languages.registerDocumentFormattingEditProvider( - qsharpLanguageId, - createFormattingProvider(languageService), - ), - ); - - // format range - subscriptions.push( - vscode.languages.registerDocumentRangeFormattingEditProvider( - qsharpLanguageId, - createFormattingProvider(languageService), - ), - ); - - // completions - subscriptions.push( - vscode.languages.registerCompletionItemProvider( - qsharpLanguageId, - createCompletionItemProvider(languageService), - // Trigger characters should be kept in sync with the ones in `playground/src/main.tsx` - "@", - ".", - ), - ); - - // hover - subscriptions.push( - vscode.languages.registerHoverProvider( - qsharpLanguageId, - createHoverProvider(languageService), - ), - ); - - // go to def - subscriptions.push( - vscode.languages.registerDefinitionProvider( - qsharpLanguageId, - createDefinitionProvider(languageService), - ), - ); - - // find references - subscriptions.push( - vscode.languages.registerReferenceProvider( - qsharpLanguageId, - createReferenceProvider(languageService), - ), - ); - - // signature help - subscriptions.push( - vscode.languages.registerSignatureHelpProvider( - qsharpLanguageId, - createSignatureHelpProvider(languageService), - "(", - ",", - ), - ); - - // rename symbol - subscriptions.push( - vscode.languages.registerRenameProvider( - qsharpLanguageId, - createRenameProvider(languageService), - ), - ); - - // code lens - subscriptions.push( - vscode.languages.registerCodeLensProvider( - qsharpLanguageId, - createCodeLensProvider(languageService), - ), - ); - - subscriptions.push( - vscode.languages.registerCodeActionsProvider( - qsharpLanguageId, - createCodeActionsProvider(languageService), - ), - ); - - // add the language service dispose handler as well - subscriptions.push(languageService); - - return subscriptions; -} - -async function updateLanguageServiceProfile(languageService: ILanguageService) { - const targetProfile = getTarget(); - - switch (targetProfile) { - case "base": - case "adaptive_ri": - case "unrestricted": - break; - default: - log.warn(`Invalid value for target profile: ${targetProfile}`); - } - log.debug("Target profile set to: " + targetProfile); - - languageService.updateConfiguration({ - targetProfile: targetProfile, - lints: [{ lint: "needlessOperation", level: "warn" }], - }); -} - -async function loadLanguageService(baseUri: vscode.Uri) { - const start = performance.now(); - const wasmUri = vscode.Uri.joinPath(baseUri, "./wasm/qsc_wasm_bg.wasm"); - const wasmBytes = await vscode.workspace.fs.readFile(wasmUri); - await loadWasmModule(wasmBytes); - const languageService = await getLanguageService({ - findManifestDirectory, - readFile, - listDirectory, - resolvePath: async (a, b) => resolvePath(a, b), - fetchGithub: fetchGithubRaw, - }); - await updateLanguageServiceProfile(languageService); - const end = performance.now(); - sendTelemetryEvent( - EventType.LoadLanguageService, - {}, - { timeToStartMs: end - start }, - ); - return languageService; -} - -function registerConfigurationChangeHandlers( - languageService: ILanguageService, -) { - return vscode.workspace.onDidChangeConfiguration((event) => { - if (event.affectsConfiguration("Q#.qir.targetProfile")) { - updateLanguageServiceProfile(languageService); - } - }); -} - export class QsTextDocumentContentProvider implements vscode.TextDocumentContentProvider { diff --git a/vscode/src/language-service/activate.ts b/vscode/src/language-service/activate.ts new file mode 100644 index 0000000000..d4815d8713 --- /dev/null +++ b/vscode/src/language-service/activate.ts @@ -0,0 +1,302 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { + ILanguageService, + getLanguageService, + loadWasmModule, + log, +} from "qsharp-lang"; +import * as vscode from "vscode"; +import { + isQsharpDocument, + isQsharpNotebookCell, + qsharpLanguageId, +} from "../common.js"; +import { getTarget } from "../config.js"; +import { + fetchGithubRaw, + findManifestDirectory, + listDirectory, + readFile, + resolvePath, +} from "../projectSystem.js"; +import { + EventType, + QsharpDocumentType, + sendTelemetryEvent, +} from "../telemetry.js"; +import { createCodeActionsProvider } from "./codeActions.js"; +import { createCodeLensProvider } from "./codeLens.js"; +import { createCompletionItemProvider } from "./completion.js"; +import { createDefinitionProvider } from "./definition.js"; +import { startLanguageServiceDiagnostics } from "./diagnostics.js"; +import { createFormattingProvider } from "./format.js"; +import { createHoverProvider } from "./hover.js"; +import { registerQSharpNotebookCellUpdateHandlers } from "./notebook.js"; +import { createReferenceProvider } from "./references.js"; +import { createRenameProvider } from "./rename.js"; +import { createSignatureHelpProvider } from "./signature.js"; + +export async function activateLanguageService(extensionUri: vscode.Uri) { + const subscriptions: vscode.Disposable[] = []; + + const languageService = await loadLanguageService(extensionUri); + + // diagnostics + subscriptions.push(...startLanguageServiceDiagnostics(languageService)); + + // synchronize document contents + subscriptions.push(...registerDocumentUpdateHandlers(languageService)); + + // synchronize notebook cell contents + subscriptions.push( + ...registerQSharpNotebookCellUpdateHandlers(languageService), + ); + + // synchronize configuration + subscriptions.push(registerConfigurationChangeHandlers(languageService)); + + // format document + subscriptions.push( + vscode.languages.registerDocumentFormattingEditProvider( + qsharpLanguageId, + createFormattingProvider(languageService), + ), + ); + + // format range + subscriptions.push( + vscode.languages.registerDocumentRangeFormattingEditProvider( + qsharpLanguageId, + createFormattingProvider(languageService), + ), + ); + + // completions + subscriptions.push( + vscode.languages.registerCompletionItemProvider( + qsharpLanguageId, + createCompletionItemProvider(languageService), + // Trigger characters should be kept in sync with the ones in `playground/src/main.tsx` + "@", + ".", + ), + ); + + // hover + subscriptions.push( + vscode.languages.registerHoverProvider( + qsharpLanguageId, + createHoverProvider(languageService), + ), + ); + + // go to def + subscriptions.push( + vscode.languages.registerDefinitionProvider( + qsharpLanguageId, + createDefinitionProvider(languageService), + ), + ); + + // find references + subscriptions.push( + vscode.languages.registerReferenceProvider( + qsharpLanguageId, + createReferenceProvider(languageService), + ), + ); + + // signature help + subscriptions.push( + vscode.languages.registerSignatureHelpProvider( + qsharpLanguageId, + createSignatureHelpProvider(languageService), + "(", + ",", + ), + ); + + // rename symbol + subscriptions.push( + vscode.languages.registerRenameProvider( + qsharpLanguageId, + createRenameProvider(languageService), + ), + ); + + // code lens + subscriptions.push( + vscode.languages.registerCodeLensProvider( + qsharpLanguageId, + createCodeLensProvider(languageService), + ), + ); + + subscriptions.push( + vscode.languages.registerCodeActionsProvider( + qsharpLanguageId, + createCodeActionsProvider(languageService), + ), + ); + + // add the language service dispose handler as well + subscriptions.push(languageService); + + return subscriptions; +} + +async function loadLanguageService(baseUri: vscode.Uri) { + const start = performance.now(); + const wasmUri = vscode.Uri.joinPath(baseUri, "./wasm/qsc_wasm_bg.wasm"); + const wasmBytes = await vscode.workspace.fs.readFile(wasmUri); + await loadWasmModule(wasmBytes); + const languageService = await getLanguageService({ + findManifestDirectory, + readFile, + listDirectory, + resolvePath: async (a, b) => resolvePath(a, b), + fetchGithub: fetchGithubRaw, + }); + await updateLanguageServiceProfile(languageService); + const end = performance.now(); + sendTelemetryEvent( + EventType.LoadLanguageService, + {}, + { timeToStartMs: end - start }, + ); + return languageService; +} +function registerDocumentUpdateHandlers(languageService: ILanguageService) { + vscode.workspace.textDocuments.forEach((document) => { + updateIfQsharpDocument(document); + }); + + // we manually send an OpenDocument telemetry event if this is a Q# document, because the + // below subscriptions won't fire for documents that are already open when the extension is activated + vscode.workspace.textDocuments.forEach((document) => { + if (isQsharpDocument(document)) { + const documentType = isQsharpNotebookCell(document) + ? QsharpDocumentType.JupyterCell + : QsharpDocumentType.Qsharp; + sendTelemetryEvent( + EventType.OpenedDocument, + { documentType }, + { linesOfCode: document.lineCount }, + ); + } + }); + + const subscriptions = []; + subscriptions.push( + vscode.workspace.onDidOpenTextDocument((document) => { + const documentType = isQsharpNotebookCell(document) + ? QsharpDocumentType.JupyterCell + : isQsharpDocument(document) + ? QsharpDocumentType.Qsharp + : QsharpDocumentType.Other; + if (documentType !== QsharpDocumentType.Other) { + sendTelemetryEvent( + EventType.OpenedDocument, + { documentType }, + { linesOfCode: document.lineCount }, + ); + } + updateIfQsharpDocument(document); + }), + ); + + subscriptions.push( + vscode.workspace.onDidChangeTextDocument((evt) => { + updateIfQsharpDocument(evt.document); + }), + ); + + subscriptions.push( + vscode.workspace.onDidCloseTextDocument((document) => { + if (isQsharpDocument(document) && !isQsharpNotebookCell(document)) { + languageService.closeDocument(document.uri.toString()); + } + }), + ); + + // Watch manifest changes and update each document in the same project as the manifest. + subscriptions.push( + vscode.workspace.onDidSaveTextDocument((manifest) => { + updateProjectDocuments(manifest.uri); + }), + ); + + // Trigger an update on all .qs child documents when their manifest is deleted, + // so that they can get reparented to single-file-projects. + subscriptions.push( + vscode.workspace.onDidDeleteFiles((event) => { + event.files.forEach((uri) => { + updateProjectDocuments(uri); + }); + }), + ); + + // Checks if the URI belongs to a qsharp manifest, and updates all + // open documents in the same project as the manifest. + function updateProjectDocuments(manifest: vscode.Uri) { + if (manifest.scheme === "file" && manifest.fsPath.endsWith("qsharp.json")) { + const project_folder = manifest.fsPath.slice( + 0, + manifest.fsPath.length - "qsharp.json".length, + ); + vscode.workspace.textDocuments.forEach((document) => { + if ( + !document.isClosed && + // Check that the document is on the same project as the manifest. + document.fileName.startsWith(project_folder) + ) { + updateIfQsharpDocument(document); + } + }); + } + } + + function updateIfQsharpDocument(document: vscode.TextDocument) { + if (isQsharpDocument(document) && !isQsharpNotebookCell(document)) { + // Regular (not notebook) Q# document. + languageService.updateDocument( + document.uri.toString(), + document.version, + document.getText(), + ); + } + } + + return subscriptions; +} + +function registerConfigurationChangeHandlers( + languageService: ILanguageService, +) { + return vscode.workspace.onDidChangeConfiguration((event) => { + if (event.affectsConfiguration("Q#.qir.targetProfile")) { + updateLanguageServiceProfile(languageService); + } + }); +} + +async function updateLanguageServiceProfile(languageService: ILanguageService) { + const targetProfile = getTarget(); + + switch (targetProfile) { + case "base": + case "adaptive_ri": + case "unrestricted": + break; + default: + log.warn(`Invalid value for target profile: ${targetProfile}`); + } + log.debug("Target profile set to: " + targetProfile); + + languageService.updateConfiguration({ + targetProfile: targetProfile, + lints: [{ lint: "needlessOperation", level: "warn" }], + }); +} diff --git a/vscode/src/codeActions.ts b/vscode/src/language-service/codeActions.ts similarity index 97% rename from vscode/src/codeActions.ts rename to vscode/src/language-service/codeActions.ts index 03fb7869c7..513f28fe88 100644 --- a/vscode/src/codeActions.ts +++ b/vscode/src/language-service/codeActions.ts @@ -3,7 +3,7 @@ import { ILanguageService, ICodeAction } from "qsharp-lang"; import * as vscode from "vscode"; -import { toVscodeWorkspaceEdit } from "./common"; +import { toVscodeWorkspaceEdit } from "../common"; export function createCodeActionsProvider(languageService: ILanguageService) { return new QSharpCodeActionProvider(languageService); diff --git a/vscode/src/codeLens.ts b/vscode/src/language-service/codeLens.ts similarity index 98% rename from vscode/src/codeLens.ts rename to vscode/src/language-service/codeLens.ts index 7790628105..98672811cb 100644 --- a/vscode/src/codeLens.ts +++ b/vscode/src/language-service/codeLens.ts @@ -7,7 +7,7 @@ import { qsharpLibraryUriScheme, } from "qsharp-lang"; import * as vscode from "vscode"; -import { toVscodeRange } from "./common"; +import { toVscodeRange } from "../common"; export function createCodeLensProvider(languageService: ILanguageService) { return new QSharpCodeLensProvider(languageService); diff --git a/vscode/src/completion.ts b/vscode/src/language-service/completion.ts similarity index 96% rename from vscode/src/completion.ts rename to vscode/src/language-service/completion.ts index 6526962c0b..92f2fc8bc8 100644 --- a/vscode/src/completion.ts +++ b/vscode/src/language-service/completion.ts @@ -4,8 +4,8 @@ import { ILanguageService, samples } from "qsharp-lang"; import * as vscode from "vscode"; import { CompletionItem } from "vscode"; -import { EventType, sendTelemetryEvent } from "./telemetry"; -import { toVscodeRange } from "./common"; +import { toVscodeRange } from "../common"; +import { EventType, sendTelemetryEvent } from "../telemetry"; export function createCompletionItemProvider( languageService: ILanguageService, diff --git a/vscode/src/definition.ts b/vscode/src/language-service/definition.ts similarity index 94% rename from vscode/src/definition.ts rename to vscode/src/language-service/definition.ts index 0800224b4a..fb2f6a6a23 100644 --- a/vscode/src/definition.ts +++ b/vscode/src/language-service/definition.ts @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { toVscodeLocation } from "./common"; import { ILanguageService } from "qsharp-lang"; import * as vscode from "vscode"; +import { toVscodeLocation } from "../common"; export function createDefinitionProvider(languageService: ILanguageService) { return new QSharpDefinitionProvider(languageService); diff --git a/vscode/src/language-service/diagnostics.ts b/vscode/src/language-service/diagnostics.ts new file mode 100644 index 0000000000..cbd0e9ac1d --- /dev/null +++ b/vscode/src/language-service/diagnostics.ts @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { + ILanguageService, + VSDiagnostic, + qsharpLibraryUriScheme, +} from "qsharp-lang"; +import * as vscode from "vscode"; +import { qsharpLanguageId, toVsCodeDiagnostic } from "../common"; + +export function startLanguageServiceDiagnostics( + languageService: ILanguageService, +): vscode.Disposable[] { + const diagCollection = + vscode.languages.createDiagnosticCollection(qsharpLanguageId); + + async function onDiagnostics(evt: { + detail: { + uri: string; + version: number; + diagnostics: VSDiagnostic[]; + }; + }) { + const diagnostics = evt.detail; + const uri = vscode.Uri.parse(diagnostics.uri); + + if (uri.scheme === qsharpLibraryUriScheme) { + // Don't report diagnostics for library files. + return; + } + + diagCollection.set( + uri, + diagnostics.diagnostics.map((d) => toVsCodeDiagnostic(d)), + ); + } + + languageService.addEventListener("diagnostics", onDiagnostics); + + return [ + { + dispose: () => { + languageService.removeEventListener("diagnostics", onDiagnostics); + }, + }, + diagCollection, + ]; +} diff --git a/vscode/src/format.ts b/vscode/src/language-service/format.ts similarity index 92% rename from vscode/src/format.ts rename to vscode/src/language-service/format.ts index 71765f7a89..fb9275dfd5 100644 --- a/vscode/src/format.ts +++ b/vscode/src/language-service/format.ts @@ -3,9 +3,9 @@ import { ILanguageService } from "qsharp-lang"; import * as vscode from "vscode"; -import { toVscodeRange } from "./common"; -import { EventType, FormatEvent, sendTelemetryEvent } from "./telemetry"; -import { getRandomGuid } from "./utils"; +import { toVscodeRange } from "../common"; +import { EventType, FormatEvent, sendTelemetryEvent } from "../telemetry"; +import { getRandomGuid } from "../utils"; export function createFormattingProvider(languageService: ILanguageService) { return new QSharpFormattingProvider(languageService); diff --git a/vscode/src/hover.ts b/vscode/src/language-service/hover.ts similarity index 94% rename from vscode/src/hover.ts rename to vscode/src/language-service/hover.ts index 6cab20afad..4307174099 100644 --- a/vscode/src/hover.ts +++ b/vscode/src/language-service/hover.ts @@ -3,7 +3,7 @@ import { ILanguageService } from "qsharp-lang"; import * as vscode from "vscode"; -import { toVscodeRange } from "./common"; +import { toVscodeRange } from "../common"; export function createHoverProvider(languageService: ILanguageService) { return new QSharpHoverProvider(languageService); diff --git a/vscode/src/language-service/notebook.ts b/vscode/src/language-service/notebook.ts new file mode 100644 index 0000000000..c17e542501 --- /dev/null +++ b/vscode/src/language-service/notebook.ts @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { ILanguageService, log } from "qsharp-lang"; +import * as vscode from "vscode"; +import { isQsharpNotebookCell } from "../common.js"; +import { findQSharpCellMagic, jupyterNotebookType } from "../notebook.js"; + +const qsharpConfigMimeType = "application/x.qsharp-config"; + +const openQSharpNotebooks = new Set(); + +/** + * Document update handlers for syncing notebook cell contents with the language service. + */ +export function registerQSharpNotebookCellUpdateHandlers( + languageService: ILanguageService, +) { + vscode.workspace.notebookDocuments.forEach((notebook) => { + updateIfQsharpNotebook(notebook); + }); + + const subscriptions = []; + subscriptions.push( + vscode.workspace.onDidOpenNotebookDocument((notebook) => { + updateIfQsharpNotebook(notebook); + }), + ); + + subscriptions.push( + vscode.workspace.onDidChangeNotebookDocument((event) => { + updateIfQsharpNotebook(event.notebook); + }), + ); + + subscriptions.push( + vscode.workspace.onDidCloseNotebookDocument((notebook) => { + closeIfKnownQsharpNotebook(notebook); + }), + ); + + function updateIfQsharpNotebook(notebook: vscode.NotebookDocument) { + if (notebook.notebookType === jupyterNotebookType) { + const qsharpMetadata = getQSharpConfigMetadata(notebook); + const qsharpCells = getQSharpCells(notebook); + const notebookUri = notebook.uri.toString(); + if (qsharpCells.length > 0) { + openQSharpNotebooks.add(notebookUri); + languageService.updateNotebookDocument( + notebookUri, + notebook.version, + qsharpMetadata, + qsharpCells.map((cell) => { + return { + uri: cell.document.uri.toString(), + version: cell.document.version, + code: getQSharpText(cell.document), + }; + }), + ); + } else { + // All Q# cells could have been deleted, check if we know this doc from previous calls + closeIfKnownQsharpNotebook(notebook); + } + } + } + + function closeIfKnownQsharpNotebook(notebook: vscode.NotebookDocument) { + const notebookUri = notebook.uri.toString(); + if (openQSharpNotebooks.has(notebookUri)) { + languageService.closeNotebookDocument(notebookUri); + openQSharpNotebooks.delete(notebook.uri.toString()); + } + } + + function getQSharpCells(notebook: vscode.NotebookDocument) { + return notebook + .getCells() + .filter((cell) => isQsharpNotebookCell(cell.document)); + } + + function getQSharpText(document: vscode.TextDocument) { + const magicRange = findQSharpCellMagic(document); + if (magicRange) { + const magicStartOffset = document.offsetAt(magicRange.start); + const magicEndOffset = document.offsetAt(magicRange.end); + // Erase the %%qsharp magic line if it's there. + // Replace it with a comment so that document offsets remain the same. + // This will save us from having to map offsets later when + // communicating with the language service. + const text = document.getText(); + return ( + text.substring(0, magicStartOffset) + + "//qsharp" + + text.substring(magicEndOffset) + ); + } else { + // No %%qsharp magic. This can happen if the user manually sets the + // cell language to Q#. Python won't recognize the cell as a Q# cell, + // so this will fail at runtime, but as the language service we respect + // the manually set cell language, so we treat this as any other + // Q# cell. We could consider raising a warning here to help the user. + log.info( + "found Q# cell without %%qsharp magic: " + document.uri.toString(), + ); + return document.getText(); + } + } + + return subscriptions; +} + +/** + * Finds an output cell that contains an item with the Q# config MIME type, + * and returns the data from it. This data and is generated by the execution of a + * `qsharp.init()` call. It's Q# configuration data to be passed + * to the language service as "notebook metadata". + */ +function getQSharpConfigMetadata(notebook: vscode.NotebookDocument): object { + const data = notebook + .getCells() + .flatMap((cell) => cell.outputs) + .flatMap((output) => output.items) + .find((item) => { + return item.mime === qsharpConfigMimeType; + })?.data; + + if (data) { + const dataString = new TextDecoder().decode(data); + log.trace("found Q# config metadata: " + dataString); + return JSON.parse(dataString); + } else { + return {}; + } +} diff --git a/vscode/src/references.ts b/vscode/src/language-service/references.ts similarity index 95% rename from vscode/src/references.ts rename to vscode/src/language-service/references.ts index 7531cff9f4..528038c189 100644 --- a/vscode/src/references.ts +++ b/vscode/src/language-service/references.ts @@ -3,7 +3,7 @@ import { ILanguageService } from "qsharp-lang"; import * as vscode from "vscode"; -import { toVscodeLocation } from "./common"; +import { toVscodeLocation } from "../common"; export function createReferenceProvider(languageService: ILanguageService) { return new QSharpReferenceProvider(languageService); diff --git a/vscode/src/rename.ts b/vscode/src/language-service/rename.ts similarity index 95% rename from vscode/src/rename.ts rename to vscode/src/language-service/rename.ts index 0569a73801..02060ab4f5 100644 --- a/vscode/src/rename.ts +++ b/vscode/src/language-service/rename.ts @@ -3,7 +3,7 @@ import { ILanguageService } from "qsharp-lang"; import * as vscode from "vscode"; -import { toVscodeRange, toVscodeWorkspaceEdit } from "./common"; +import { toVscodeRange, toVscodeWorkspaceEdit } from "../common"; export function createRenameProvider(languageService: ILanguageService) { return new QSharpRenameProvider(languageService); diff --git a/vscode/src/signature.ts b/vscode/src/language-service/signature.ts similarity index 100% rename from vscode/src/signature.ts rename to vscode/src/language-service/signature.ts diff --git a/vscode/src/notebook.ts b/vscode/src/notebook.ts index 065bddf1ea..5e53cb54bd 100644 --- a/vscode/src/notebook.ts +++ b/vscode/src/notebook.ts @@ -1,16 +1,16 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { ILanguageService, log } from "qsharp-lang"; +import { log } from "qsharp-lang"; import * as vscode from "vscode"; -import { isQsharpNotebookCell, qsharpLanguageId } from "./common.js"; import { WorkspaceTreeProvider } from "./azure/treeView.js"; import { getPythonCodeForWorkspace } from "./azure/workspaceActions.js"; +import { qsharpLanguageId } from "./common.js"; import { notebookTemplate } from "./notebookTemplate.js"; const qsharpCellMagic = "%%qsharp"; -const jupyterNotebookType = "jupyter-notebook"; -const qsharpConfigMimeType = "application/x.qsharp-config"; +export const jupyterNotebookType = "jupyter-notebook"; +let defaultLanguageId: string | undefined; /** * Sets up handlers to detect Q# code cells in Jupyter notebooks and set the language to Q#. @@ -53,8 +53,6 @@ export function registerQSharpNotebookHandlers() { }), ); - let defaultLanguageId: string | undefined; - function updateQSharpCellLanguages(cells: vscode.NotebookCell[]) { for (const cell of cells) { // If this is a code cell that starts with %%qsharp, and language wasn't already set to Q#, set it. @@ -98,13 +96,11 @@ export function registerQSharpNotebookHandlers() { return subscriptions; } -const openQSharpNotebooks = new Set(); - /** * Returns the range of the `%%qsharp` cell magic, or `undefined` * if it does not exist. */ -function findQSharpCellMagic(document: vscode.TextDocument) { +export function findQSharpCellMagic(document: vscode.TextDocument) { // Ignore whitespace before the cell magic for (let i = 0; i < document.lineCount; i++) { const line = document.lineAt(i); @@ -127,130 +123,6 @@ function findQSharpCellMagic(document: vscode.TextDocument) { return undefined; } -/** - * This one is for syncing with the language service - */ -export function registerQSharpNotebookCellUpdateHandlers( - languageService: ILanguageService, -) { - vscode.workspace.notebookDocuments.forEach((notebook) => { - updateIfQsharpNotebook(notebook); - }); - - const subscriptions = []; - subscriptions.push( - vscode.workspace.onDidOpenNotebookDocument((notebook) => { - updateIfQsharpNotebook(notebook); - }), - ); - - subscriptions.push( - vscode.workspace.onDidChangeNotebookDocument((event) => { - updateIfQsharpNotebook(event.notebook); - }), - ); - - subscriptions.push( - vscode.workspace.onDidCloseNotebookDocument((notebook) => { - closeIfKnownQsharpNotebook(notebook); - }), - ); - - function updateIfQsharpNotebook(notebook: vscode.NotebookDocument) { - if (notebook.notebookType === jupyterNotebookType) { - const qsharpMetadata = getQSharpConfigMetadata(notebook); - const qsharpCells = getQSharpCells(notebook); - const notebookUri = notebook.uri.toString(); - if (qsharpCells.length > 0) { - openQSharpNotebooks.add(notebookUri); - languageService.updateNotebookDocument( - notebookUri, - notebook.version, - qsharpMetadata, - qsharpCells.map((cell) => { - return { - uri: cell.document.uri.toString(), - version: cell.document.version, - code: getQSharpText(cell.document), - }; - }), - ); - } else { - // All Q# cells could have been deleted, check if we know this doc from previous calls - closeIfKnownQsharpNotebook(notebook); - } - } - } - - function closeIfKnownQsharpNotebook(notebook: vscode.NotebookDocument) { - const notebookUri = notebook.uri.toString(); - if (openQSharpNotebooks.has(notebookUri)) { - languageService.closeNotebookDocument(notebookUri); - openQSharpNotebooks.delete(notebook.uri.toString()); - } - } - - function getQSharpCells(notebook: vscode.NotebookDocument) { - return notebook - .getCells() - .filter((cell) => isQsharpNotebookCell(cell.document)); - } - - function getQSharpText(document: vscode.TextDocument) { - const magicRange = findQSharpCellMagic(document); - if (magicRange) { - const magicStartOffset = document.offsetAt(magicRange.start); - const magicEndOffset = document.offsetAt(magicRange.end); - // Erase the %%qsharp magic line if it's there. - // Replace it with a comment so that document offsets remain the same. - // This will save us from having to map offsets later when - // communicating with the language service. - const text = document.getText(); - return ( - text.substring(0, magicStartOffset) + - "//qsharp" + - text.substring(magicEndOffset) - ); - } else { - // No %%qsharp magic. This can happen if the user manually sets the - // cell language to Q#. Python won't recognize the cell as a Q# cell, - // so this will fail at runtime, but as the language service we respect - // the manually set cell language, so we treat this as any other - // Q# cell. We could consider raising a warning here to help the user. - log.info( - "found Q# cell without %%qsharp magic: " + document.uri.toString(), - ); - return document.getText(); - } - } - - return subscriptions; -} - -/** - * Finds an output cell that contains an item with the Q# config MIME type, - * and returns the data from it. This data and is generated by the execution of a - * `qsharp.init()` call. It's Q# configuration data to be passed - * to the language service as "notebook metadata". - */ -function getQSharpConfigMetadata(notebook: vscode.NotebookDocument): object { - const data = notebook - .getCells() - .flatMap((cell) => cell.outputs) - .flatMap((output) => output.items) - .find((item) => { - return item.mime === qsharpConfigMimeType; - })?.data; - - if (data) { - const dataString = new TextDecoder().decode(data); - log.trace("found Q# config metadata: " + dataString); - return JSON.parse(dataString); - } else { - return {}; - } -} - // Yes, this function is long, but mostly to deal with multi-folder VS Code workspace or multi // Azure Quantum workspace connection scenarios. The actual notebook creation is pretty simple. export function registerCreateNotebookCommand( diff --git a/vscode/src/webview/docview.tsx b/vscode/src/webview/docview.tsx index 1d6b8ec8c5..efe758a700 100644 --- a/vscode/src/webview/docview.tsx +++ b/vscode/src/webview/docview.tsx @@ -168,6 +168,22 @@ function DocsPage(props: { fragmentsToRender: ItemDocs[] }) { const [searchText, setSearchText] = useState(""); useEffect(() => { + // Update the xref links to navigate to the correct member + document.querySelectorAll('a[href^="xref:"]').forEach((a) => { + const anchor = a as HTMLAnchorElement; + const xref = "xref:"; + let link = anchor.href.slice(xref.length); + link = link.replaceAll(".", "/"); + // Just for Qdk links, we want to strip out the leading "Qdk." + if (link.startsWith("Qdk/")) { + link = link.slice(4); + } + a.addEventListener("click", (e) => { + e.preventDefault(); + setPath(link); + }); + }); + // If the member is navigated to, scroll to it after rendering const member = currPath.split("/")[2]; scrollToElement(member); @@ -184,7 +200,7 @@ function DocsPage(props: { fragmentsToRender: ItemDocs[] }) { ? [] : getSearchResults(searchText, props.fragmentsToRender); - // Used to bold the text links when overing + // Used to bold the text links when hovering function overLi(e: MouseEvent) { (e.target as HTMLElement).style.fontWeight = "600"; (e.target as HTMLElement).style.textDecoration = "underline";