From b802b254b7cb98049573a367ed399e23ad784e59 Mon Sep 17 00:00:00 2001 From: Mathias Soeken Date: Tue, 8 Sep 2020 20:32:18 +0200 Subject: [PATCH 01/15] Improved assertion for PrepareUniformSuperposition (#324) * Improved assertion. * Clarifying remark on adjointable call. Co-authored-by: Mathias Soeken --- Standard/src/Preparation/UniformSuperposition.qs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/Standard/src/Preparation/UniformSuperposition.qs b/Standard/src/Preparation/UniformSuperposition.qs index 177c43dcef9..e68599eeb33 100644 --- a/Standard/src/Preparation/UniformSuperposition.qs +++ b/Standard/src/Preparation/UniformSuperposition.qs @@ -5,13 +5,14 @@ namespace Microsoft.Quantum.Preparation { open Microsoft.Quantum.Canon; open Microsoft.Quantum.Intrinsic; open Microsoft.Quantum.Convert; + open Microsoft.Quantum.Diagnostics; open Microsoft.Quantum.Arithmetic; open Microsoft.Quantum.AmplitudeAmplification; open Microsoft.Quantum.Oracles; open Microsoft.Quantum.Math; /// # Summary - /// Creates a uniform superposition over states that encode 0 through `nIndices`. + /// Creates a uniform superposition over states that encode 0 through `nIndices - 1`. /// /// That is, this unitary $U$ creates a uniform superposition over all number states /// $0$ to $M-1$, given an input state $\ket{0\cdots 0}$. In other words, @@ -30,13 +31,17 @@ namespace Microsoft.Quantum.Preparation { /// initialized in the state $\ket{0\cdots 0}$. /// /// # Remarks - /// ## Example + /// The operation is adjointable, but requires that `indexRegister` is in a uniform + /// superposition over the first `nIndices` basis states in that case. + /// + /// # Example /// The following example prepares the state $\frac{1}{\sqrt{6}}\sum_{j=0}^{5}\ket{j}$ /// on $3$ qubits. /// ``` Q# /// let nIndices = 6; /// using(indexRegister = Qubit[3]) { /// PrepareUniformSuperposition(nIndices, LittleEndian(indexRegister)); + /// // ... /// } /// ``` operation PrepareUniformSuperposition(nIndices: Int, indexRegister: LittleEndian) : Unit is Adj + Ctl { @@ -53,6 +58,7 @@ namespace Microsoft.Quantum.Preparation { } using (flagQubit = Qubit[3]) { + AssertAllZero(indexRegister!); let targetQubits = indexRegister![0..nQubits - 1]; let qubits = flagQubit + targetQubits; let stateOracle = StateOracle(PrepareUniformSuperposition_(nIndices, nQubits, _, _)); From 827554ed66c4380832bdce3ee52f8f814bf8d3c5 Mon Sep 17 00:00:00 2001 From: Andres Paz Date: Wed, 16 Sep 2020 23:03:05 -0700 Subject: [PATCH 02/15] End-to-end build (#325) --- .github/workflows/automerge.yml | 4 +-- .github/workflows/qdk-sync.yml | 28 ++++++++++++++++ .pre-commit-config.yaml | 2 +- Build/e2e.yml | 33 +++++++++++++++++++ Chemistry/README.md | 6 ++-- Chemistry/src/DataModel/DataModel.csproj | 2 +- .../BroombridgeDataStructurev0.1.cs | 2 +- .../BroombridgeDataStructurev0.2.cs | 2 +- .../Broombridge/BroombridgeSerializer.cs | 2 +- Chemistry/src/Jupyter/Jupyter.csproj | 4 +-- Chemistry/src/Metapackage/Metapackage.csproj | 2 +- Chemistry/src/Runtime/Runtime.csproj | 2 +- .../tests/TestData/Broombridge/LiH_0.1.yaml | 2 +- .../tests/TestData/Broombridge/LiH_0.2.yaml | 2 +- .../Broombridge/broombridge_v0.1.yaml | 2 +- .../Broombridge/broombridge_v0.2.yaml | 2 +- .../TestData/Broombridge/hydrogen_0.1.yaml | 2 +- .../TestData/Broombridge/hydrogen_0.2.yaml | 2 +- Chemistry/tests/TestData/FciDump/h2_631g.yaml | 2 +- MachineLearning/src/MachineLearning.csproj | 2 +- .../qsharp/tests/broombridge.yaml | 2 +- README.md | 2 +- .../src/Synthesis/ControlledOnTruthTable.qs | 2 +- build.yml | 9 +++-- sync.cmd | 2 +- 25 files changed, 94 insertions(+), 28 deletions(-) create mode 100644 .github/workflows/qdk-sync.yml create mode 100644 Build/e2e.yml diff --git a/.github/workflows/automerge.yml b/.github/workflows/automerge.yml index d45a296b737..143313aa57e 100644 --- a/.github/workflows/automerge.yml +++ b/.github/workflows/automerge.yml @@ -5,7 +5,7 @@ on: pull_request: # Note that we only support automerge on branches that have required checks. branches: - - master + - main - feature/* types: - labeled @@ -19,7 +19,7 @@ on: pull_request_review: # Note that we only support automerge on branches that have required checks. branches: - - master + - main - feature/* types: - submitted diff --git a/.github/workflows/qdk-sync.yml b/.github/workflows/qdk-sync.yml new file mode 100644 index 00000000000..26b4da3d7d6 --- /dev/null +++ b/.github/workflows/qdk-sync.yml @@ -0,0 +1,28 @@ +name: Sync QDK repos + +on: + push: + branches: + - main + +jobs: + sync-repos: + runs-on: ubuntu-latest + steps: + - name: Login to Azure + uses: Azure/login@v1 + with: + creds: ${{ secrets.AZURE_CREDENTIALS }} + + - id: AzureKeyVault + uses: Azure/get-keyvault-secrets@v1.0 + with: + keyvault: 'kv-qdk-build' + secrets: 'qdkBuildPAT' + + - name: 'Trigger QDK sync build' + uses: Azure/pipelines@releases/v1 + with: + azure-devops-project-url: 'https://dev.azure.com/ms-quantum-public/Microsoft Quantum (public)' + azure-pipeline-name: 'microsoft.qdk.sync' + azure-devops-token: ${{ steps.AzureKeyVault.outputs.qdkBuildPAT }} diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 720a2c62f04..7a4ad5261f8 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -5,7 +5,7 @@ repos: - id: trailing-whitespace args: [--markdown-linebreak-ext=md] - id: no-commit-to-branch - args: [-b, "master"] + args: [-b, "main"] - id: check-yaml - repo: local hooks: diff --git a/Build/e2e.yml b/Build/e2e.yml new file mode 100644 index 00000000000..a5b980711be --- /dev/null +++ b/Build/e2e.yml @@ -0,0 +1,33 @@ +name: $(Build.Major).$(Build.Minor).$(date:yyMM).$(BuildId) + +parameters: +- name: validation_level + displayName: Validation Level + type: string + default: normal + values: + - minimal + - normal + - full + +trigger: none + +pr: +- main +- feature/* +- features/* +- release/* + +resources: + repositories: + - repository: qdk + type: github + endpoint: github + name: microsoft/qdk + ref: refs/heads/main + +extends: + template: build/qdk-module-e2e.yml@qdk + parameters: + module: QuantumLibraries + validation_level: ${{ parameters.validation_level }} diff --git a/Chemistry/README.md b/Chemistry/README.md index af55bebbab0..53784f5a395 100644 --- a/Chemistry/README.md +++ b/Chemistry/README.md @@ -1,14 +1,14 @@ # Microsoft Quantum Chemistry Library # This folder contains the C# and Q# sources used to implement the [Microsoft Quantum Chemistry library](https://docs.microsoft.com/en-us/quantum/libraries/chemistry/). -Samples of how to use the library can be found in the Chemistry folder of the [Microsoft/Quantum repository](https://github.com/Microsoft/Quantum/tree/master/Chemistry). +Samples of how to use the library can be found in the Chemistry folder of the [Microsoft/Quantum repository](https://github.com/microsoft/Quantum/tree/main/Chemistry). ## Building and testing ## The quantum chemistry library consists of two cross-platform project built using [.NET Core](https://docs.microsoft.com/en-us/dotnet/core/): -- [**DataModel.csproj**](https://github.com/Microsoft/QuantumLibraries/tree/master/Chemistry/src/DataModel/DataModel.csproj): C# sources used to load, parse, and pre-compute Hamiltonians loaded from LIQ𝑈𝑖|âŒȘ or Broombridge files. -- [**Runtime.csproj**](https://github.com/Microsoft/QuantumLibraries/tree/master/Chemistry/src/Runtime/Runtime.csproj): Q# sources used to implement quantum chemistry simulation algorithms, given representations produced by the DataModel. +- [**DataModel.csproj**](https://github.com/microsoft/QuantumLibraries/tree/main/Chemistry/src/DataModel/DataModel.csproj): C# sources used to load, parse, and pre-compute Hamiltonians loaded from LIQ𝑈𝑖|âŒȘ or Broombridge files. +- [**Runtime.csproj**](https://github.com/microsoft/QuantumLibraries/tree/main/Chemistry/src/Runtime/Runtime.csproj): Q# sources used to implement quantum chemistry simulation algorithms, given representations produced by the DataModel. Once .NET Core is installed, you may build and run its tests by executing the following from a command line: diff --git a/Chemistry/src/DataModel/DataModel.csproj b/Chemistry/src/DataModel/DataModel.csproj index 47f07491b0d..bdc7bb56ed9 100644 --- a/Chemistry/src/DataModel/DataModel.csproj +++ b/Chemistry/src/DataModel/DataModel.csproj @@ -14,7 +14,7 @@ Microsoft.Quantum.Chemistry.DataModel See: https://docs.microsoft.com/en-us/quantum/relnotes/ MIT - https://github.com/Microsoft/QuantumLibraries/tree/master/Chemistry + https://github.com/microsoft/QuantumLibraries/tree/main/Chemistry qdk-nuget-icon.png Quantum Q# Qsharp 1591 diff --git a/Chemistry/src/DataModel/Serialization/Broombridge/BroombridgeDataStructurev0.1.cs b/Chemistry/src/DataModel/Serialization/Broombridge/BroombridgeDataStructurev0.1.cs index e38acf87039..60864998679 100644 --- a/Chemistry/src/DataModel/Serialization/Broombridge/BroombridgeDataStructurev0.1.cs +++ b/Chemistry/src/DataModel/Serialization/Broombridge/BroombridgeDataStructurev0.1.cs @@ -128,7 +128,7 @@ internal static V0_1.IntegralSet ToBroombridgeV0_1(this ElectronicStructureProbl #region Broombridge v0.1 format public static class V0_1 { - public static string SchemaUrl = "https://raw.githubusercontent.com/microsoft/Quantum/master/Chemistry/Schema/broombridge-0.1.schema.json"; + public static string SchemaUrl = "https://raw.githubusercontent.com/microsoft/Quantum/main/Chemistry/Schema/broombridge-0.1.schema.json"; public struct Data { diff --git a/Chemistry/src/DataModel/Serialization/Broombridge/BroombridgeDataStructurev0.2.cs b/Chemistry/src/DataModel/Serialization/Broombridge/BroombridgeDataStructurev0.2.cs index 2bcc87a8162..755a6c80a63 100644 --- a/Chemistry/src/DataModel/Serialization/Broombridge/BroombridgeDataStructurev0.2.cs +++ b/Chemistry/src/DataModel/Serialization/Broombridge/BroombridgeDataStructurev0.2.cs @@ -167,7 +167,7 @@ this IEnumerable initialStates #region Broombridge v0.2 format public static class V0_2 { - public static string SchemaUrl = "https://raw.githubusercontent.com/microsoft/Quantum/master/Chemistry/Schema/broombridge-0.2.schema.json"; + public static string SchemaUrl = "https://raw.githubusercontent.com/microsoft/Quantum/main/Chemistry/Schema/broombridge-0.2.schema.json"; internal static class UpdaterStrings { public const string SingleConfigurational = "single_configurational"; diff --git a/Chemistry/src/DataModel/Serialization/Broombridge/BroombridgeSerializer.cs b/Chemistry/src/DataModel/Serialization/Broombridge/BroombridgeSerializer.cs index 3616e82ca97..ce02a23a0b2 100644 --- a/Chemistry/src/DataModel/Serialization/Broombridge/BroombridgeSerializer.cs +++ b/Chemistry/src/DataModel/Serialization/Broombridge/BroombridgeSerializer.cs @@ -92,7 +92,7 @@ public static class Deserializers /// internal static Dictionary VersionNumberDict = new Dictionary() { - // https://github.com/Microsoft/Quantum/blob/master/Chemistry/Schema/broombridge-0.1.schema.json + // https://github.com/microsoft/Quantum/blob/main/Chemistry/Schema/broombridge-0.1.schema.json ["0.1"] = VersionNumber.v0_1, ["broombridge-0.1.schema"] = VersionNumber.v0_1, // TODO: URL of 0.2 schema. diff --git a/Chemistry/src/Jupyter/Jupyter.csproj b/Chemistry/src/Jupyter/Jupyter.csproj index 833b8769531..c949abacfd0 100644 --- a/Chemistry/src/Jupyter/Jupyter.csproj +++ b/Chemistry/src/Jupyter/Jupyter.csproj @@ -10,8 +10,8 @@ Microsoft's Quantum Chemistry Libraries Jupyter integration. © Microsoft Corporation. All rights reserved. See: https://docs.microsoft.com/en-us/quantum/relnotes/ - https://github.com/Microsoft/QuantumLibraries/raw/master/LICENSE.txt - https://github.com/Microsoft/QuantumLibraries/tree/master/Chemistry + https://github.com/microsoft/QuantumLibraries/raw/main/LICENSE.txt + https://github.com/microsoft/QuantumLibraries/tree/main/Chemistry qdk-nuget-icon.png Quantum Q# Qsharp Jupyter 1591 diff --git a/Chemistry/src/Metapackage/Metapackage.csproj b/Chemistry/src/Metapackage/Metapackage.csproj index d4b1668e95a..cd940394e81 100644 --- a/Chemistry/src/Metapackage/Metapackage.csproj +++ b/Chemistry/src/Metapackage/Metapackage.csproj @@ -13,7 +13,7 @@ Microsoft.Quantum.Chemistry See: https://docs.microsoft.com/en-us/quantum/relnotes/ MIT - https://github.com/Microsoft/QuantumLibraries/tree/master/Chemistry + https://github.com/microsoft/QuantumLibraries/tree/main/Chemistry qdk-nuget-icon.png Quantum Q# Qsharp 1591 diff --git a/Chemistry/src/Runtime/Runtime.csproj b/Chemistry/src/Runtime/Runtime.csproj index aa91f2bf0ef..902c0c66483 100644 --- a/Chemistry/src/Runtime/Runtime.csproj +++ b/Chemistry/src/Runtime/Runtime.csproj @@ -15,7 +15,7 @@ Microsoft.Quantum.Chemistry.Runtime See: https://docs.microsoft.com/en-us/quantum/relnotes/ MIT - https://github.com/Microsoft/QuantumLibraries/tree/master/Chemistry + https://github.com/microsoft/QuantumLibraries/tree/main/Chemistry qdk-nuget-icon.png Quantum Q# Qsharp 1591 diff --git a/Chemistry/tests/TestData/Broombridge/LiH_0.1.yaml b/Chemistry/tests/TestData/Broombridge/LiH_0.1.yaml index d445ffea4e1..4da9dd7aede 100644 --- a/Chemistry/tests/TestData/Broombridge/LiH_0.1.yaml +++ b/Chemistry/tests/TestData/Broombridge/LiH_0.1.yaml @@ -1,5 +1,5 @@ -"$schema": https://raw.githubusercontent.com/Microsoft/Quantum/master/Chemistry/Schema/broombridge-0.1.schema.json +"$schema": https://raw.githubusercontent.com/Microsoft/Quantum/main/Chemistry/Schema/broombridge-0.1.schema.json bibliography: - {url: 'https://www.nwchem-sw.org'} diff --git a/Chemistry/tests/TestData/Broombridge/LiH_0.2.yaml b/Chemistry/tests/TestData/Broombridge/LiH_0.2.yaml index 48fd61a5792..3c0586b6c06 100644 --- a/Chemistry/tests/TestData/Broombridge/LiH_0.2.yaml +++ b/Chemistry/tests/TestData/Broombridge/LiH_0.2.yaml @@ -1,4 +1,4 @@ -"$schema": https://raw.githubusercontent.com/Microsoft/Quantum/master/Chemistry/Schema/broombridge-0.2.schema.json +"$schema": https://raw.githubusercontent.com/Microsoft/Quantum/main/Chemistry/Schema/broombridge-0.2.schema.json bibliography: - {url: 'https://www.nwchem-sw.org'} diff --git a/Chemistry/tests/TestData/Broombridge/broombridge_v0.1.yaml b/Chemistry/tests/TestData/Broombridge/broombridge_v0.1.yaml index b74f4f0072f..2617b40d25a 100644 --- a/Chemistry/tests/TestData/Broombridge/broombridge_v0.1.yaml +++ b/Chemistry/tests/TestData/Broombridge/broombridge_v0.1.yaml @@ -1,7 +1,7 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # Generated by nwchem version v... -"$schema": https://github.com/Microsoft/Quantum/blob/master/Chemistry/Schema/broombridge-0.1.schema.json +"$schema": https://github.com/microsoft/Quantum/blob/main/Chemistry/Schema/broombridge-0.1.schema.json format: # required version: "0.1" # must match exactly generator: # optional diff --git a/Chemistry/tests/TestData/Broombridge/broombridge_v0.2.yaml b/Chemistry/tests/TestData/Broombridge/broombridge_v0.2.yaml index b6bb948516f..79d3d30d62e 100644 --- a/Chemistry/tests/TestData/Broombridge/broombridge_v0.2.yaml +++ b/Chemistry/tests/TestData/Broombridge/broombridge_v0.2.yaml @@ -1,7 +1,7 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # Generated by nwchem version v... -"$schema": https://github.com/Microsoft/Quantum/blob/master/Chemistry/Schema/broombridge-0.2.schema.json +"$schema": https://github.com/microsoft/Quantum/blob/main/Chemistry/Schema/broombridge-0.2.schema.json format: version: "0.2" # required. Must match exactly generator: # optional diff --git a/Chemistry/tests/TestData/Broombridge/hydrogen_0.1.yaml b/Chemistry/tests/TestData/Broombridge/hydrogen_0.1.yaml index fda4dff03ef..fdf98af2368 100644 --- a/Chemistry/tests/TestData/Broombridge/hydrogen_0.1.yaml +++ b/Chemistry/tests/TestData/Broombridge/hydrogen_0.1.yaml @@ -1,5 +1,5 @@ -"$schema": https://raw.githubusercontent.com/Microsoft/Quantum/master/Chemistry/Schema/broombridge-0.1.schema.json +"$schema": https://raw.githubusercontent.com/Microsoft/Quantum/main/Chemistry/Schema/broombridge-0.1.schema.json bibliography: - {url: 'https://www.nwchem-sw.org'} diff --git a/Chemistry/tests/TestData/Broombridge/hydrogen_0.2.yaml b/Chemistry/tests/TestData/Broombridge/hydrogen_0.2.yaml index 61bd380ccd3..129c9bf1390 100644 --- a/Chemistry/tests/TestData/Broombridge/hydrogen_0.2.yaml +++ b/Chemistry/tests/TestData/Broombridge/hydrogen_0.2.yaml @@ -1,5 +1,5 @@ -"$schema": https://raw.githubusercontent.com/Microsoft/Quantum/master/Chemistry/Schema/broombridge-0.2.schema.json +"$schema": https://raw.githubusercontent.com/Microsoft/Quantum/main/Chemistry/Schema/broombridge-0.2.schema.json bibliography: - {url: 'https://www.nwchem-sw.org'} diff --git a/Chemistry/tests/TestData/FciDump/h2_631g.yaml b/Chemistry/tests/TestData/FciDump/h2_631g.yaml index 9024b04fdd4..292b786e7de 100644 --- a/Chemistry/tests/TestData/FciDump/h2_631g.yaml +++ b/Chemistry/tests/TestData/FciDump/h2_631g.yaml @@ -1,7 +1,7 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # H2 molecule using 6-31G basis, containing 2 electrons 4 orbitals -$schema: https://raw.githubusercontent.com/Microsoft/Quantum/master/Chemistry/Schema/broombridge-0.2.schema.json +$schema: https://raw.githubusercontent.com/Microsoft/Quantum/main/Chemistry/Schema/broombridge-0.2.schema.json format: version: '0.2' problem_description: diff --git a/MachineLearning/src/MachineLearning.csproj b/MachineLearning/src/MachineLearning.csproj index d1028037fc1..73b86c36b20 100644 --- a/MachineLearning/src/MachineLearning.csproj +++ b/MachineLearning/src/MachineLearning.csproj @@ -30,7 +30,7 @@ Microsoft.Quantum.MachineLearning See: https://docs.microsoft.com/quantum/relnotes/ MIT - https://github.com/Microsoft/QuantumLibraries/tree/master/MachineLearning + https://github.com/microsoft/QuantumLibraries/tree/main/MachineLearning qdk-nuget-icon.png Quantum Q# Qsharp 1591 diff --git a/Python/qsharp-chemistry/qsharp/tests/broombridge.yaml b/Python/qsharp-chemistry/qsharp/tests/broombridge.yaml index 070201bc5e0..1c47e5fe34e 100644 --- a/Python/qsharp-chemistry/qsharp/tests/broombridge.yaml +++ b/Python/qsharp-chemistry/qsharp/tests/broombridge.yaml @@ -1,7 +1,7 @@ # © Microsoft # MIT license # Generated by nwchem version v... -"$schema": https://github.com/Microsoft/Quantum/blob/master/Chemistry/Schema/broombridge-0.2.schema.json +"$schema": https://github.com/microsoft/Quantum/blob/main/Chemistry/Schema/broombridge-0.2.schema.json format: version: "0.2" # required. Must match exactly generator: # optional diff --git a/README.md b/README.md index fe930f1f41c..2cccf9b1bf0 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ of samples on how to use these libraries to write quantum based programs. | branch | status | |--------|-----------| -| master | [![Build Status](https://dev.azure.com/ms-quantum-public/Microsoft%20Quantum%20(public)/_apis/build/status/Microsoft.QuantumLibraries?branchName=master)](https://dev.azure.com/ms-quantum-public/Microsoft%20Quantum%20(public)/_build/latest?definitionId=1&branchName=master) | +| main | [![Build Status](https://dev.azure.com/ms-quantum-public/Microsoft%20Quantum%20(public)/_apis/build/status/Microsoft.QuantumLibraries?branchName=main)](https://dev.azure.com/ms-quantum-public/Microsoft%20Quantum%20(public)/_build/latest?definitionId=1&branchName=main) | ## Feedback ## diff --git a/Standard/src/Synthesis/ControlledOnTruthTable.qs b/Standard/src/Synthesis/ControlledOnTruthTable.qs index c716242ea53..6f28a15894d 100644 --- a/Standard/src/Synthesis/ControlledOnTruthTable.qs +++ b/Standard/src/Synthesis/ControlledOnTruthTable.qs @@ -139,7 +139,7 @@ namespace Microsoft.Quantum.Synthesis { /// and the least significant bit `0` corresponds to the input assignment `(0, 0, 0)`. /// It can be represented by the big integer `0xE8L` in hexadecimal notation or as `232L` /// in decimal notation. The `L` suffix indicates that the constant is of type `BigInt`. - /// More details on this representation can also be found in the [truth tables kata](https://github.com/microsoft/QuantumKatas/tree/master/TruthTables). + /// More details on this representation can also be found in the [truth tables kata](https://github.com/microsoft/QuantumKatas/tree/main/TruthTables). /// /// The implementation makes use of @"microsoft.quantum.intrinsic.cnot" /// and @"microsoft.quantum.intrinsic.r1" gates. diff --git a/build.yml b/build.yml index 10d43034934..2d78da0bab9 100644 --- a/build.yml +++ b/build.yml @@ -2,9 +2,14 @@ # Build configuration file to run build on azure-pipelines # name: $(Build.Major).$(Build.Minor).$(date:yyMM).$(DayOfMonth)$(rev:rr) -trigger: -- master + +trigger: none + +pr: +- main - feature/* +- features/* +- release/* variables: Build.Major: 0 diff --git a/sync.cmd b/sync.cmd index b0b089f4319..396148cc7b2 100644 --- a/sync.cmd +++ b/sync.cmd @@ -3,7 +3,7 @@ :: the public repository (https://github.com/Microsoft/Quantum.git) :: set branch=%1 -IF "%branch%" == "" SET branch=master +IF "%branch%" == "" SET branch=main git fetch origin git fetch public || call :addPublic From fdd6b964c1da5cf19f589d71bd223e0a14194ee3 Mon Sep 17 00:00:00 2001 From: Chris Granade Date: Sat, 19 Sep 2020 18:11:59 -0700 Subject: [PATCH 03/15] Add API design notes from 10 September 2020. (#328) --- Design/meetings/2020/api-design-2020-09-10.md | 81 +++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 Design/meetings/2020/api-design-2020-09-10.md diff --git a/Design/meetings/2020/api-design-2020-09-10.md b/Design/meetings/2020/api-design-2020-09-10.md new file mode 100644 index 00000000000..22bf37c488e --- /dev/null +++ b/Design/meetings/2020/api-design-2020-09-10.md @@ -0,0 +1,81 @@ +# Q# API Design Meeting / 10 September 2020 + +Attendees (in order by username): @bettinaheim, @cgranade, @efratshabtai, @guenp, @msoeken. + +## Agenda + +- Improvements to `Microsoft.Quantum.Array` namespace +- Removing `Microsoft.Quantum.Simulation.QuantumProcessor.Extensions` namespace + +## Discussion + +### Microsoft.Quantum.Arrays + +**Proposal**: https://github.com/microsoft/QuantumLibraries/issues/313 + +**Discussion**: + +- Zip is very commonly used in existing Q# code, is it worth being consistent in this case at the cost of causing significant breakage? + - Consistency is important for reaching Q# 1.0. + - Can we resolve using code actions as aliases instead of deprecation stubs? + - No conventions and nomenclature are truly universal across languages. + - Helped by IntelliSense features as well, need matching investment in IQ#. + - Modify unknown identifier error message to provide actionable guidance ("did you mean...?") + - Aliases can be helpful, but are maintenance nightmare. + - **Action item**: discuss aliases, error messages, and/or other possible onboarding paths further. +- Likely missing: function `((Int -> 'T), Range) -> 'T[]`. + - There as `MappedOverRange`, but should we have a better name? + - Perhaps "over" is confusing? + - Inconsistent w/ use of suffixes for input types. + - **Action item**: Propose better name here, addressing "over" and type suffix conventions. +- `CumulativeFolded`: Should it return initial state or not? + - `np.cumsum` excludes initial state + - **Action item**: Examine other languages here. +- `ColumnAt`: No matching `RowAt`, because it's not directly needed. Should we add anyway? + - `RowAt` is distinct from `ElementAt` in that it requires two levels of indices, whereas `ElementAt` does not. + - **Action item**: Modify proposal to add `RowAt`. +- `Count`: simpler for what is currently a common usecase for `Filtered`. + - Would be simplified by https://github.com/microsoft/qsharp-compiler/issues/557; defer introducing specializations until result of that discussion. +- `EmptyArray`: doesn't solve problem that `[]` can't be used as an empty array of a given type, while `[3]` works as an array literal. + - **Action item**: File as issue on qsharp-compiler? +- `Interleaved`: Should it support more than two inputs? + - If array-valued input, can use Transposed and Flattened together. + - Possibly change to take array-valued input, but then implementation can check length of input and do a more efficient thing if possible. + - **Action item**: Modify proposal to take array of inputs. +- `Unique`: doesn't work as written, would be slow if implemented. + - **Action item**: Modify proposal to defer. +- `Zipped`/`Unzipped`: Not elegant to have `Unzipped3`, `Unzipped4`, ... + - Also solvable by https://github.com/microsoft/qsharp-compiler/issues/557, but solution would be unwieldy. +- Missing: function to sort arrays. + - **Action item**: Modify proposal to add `Sorted`. +- `ApplyTo{Head,Tail,Most,Rest}` + - ApplyToHead is redundant with ApplyToFirstQubit, but worth keeping for consistency with Tail, Most, Rest. +- `ArrayAsHeadAndRest` / `ArrayAsMostAndTail`: + - **Action item**: Rename to `HeadAndRest` / `MostAndTail`, move to `Microsoft.Quantum.Arrays`. +- Missing fact to check that a 2D array is rectangular / square. + - `RectangularArrayFact` / `SquareArrayFact`? + - **Action item**: Modify proposal to add these two facts. + +**Other action items**: + +- Comment on user feedback with ElementAt. +- Rename `folder` input on Microsoft.Quantum.Arrays.Folded to `fn` for consistency with `CumulativeFolded`. +- Discuss grouping removal of deprecation stubs, rather than splitting removals over multiple releases. Would 1.0 be a reasonable timeframe? + +**Consensus**: Proceed as per above action items. + +### Remove Microsoft.Quantum.Simulation.QuantumProcessor.Extensions + +**Proposal**: The functions and operations in the Microsoft.Quantum.Simulation.QuantumProcessor.Extensions namespace are completely redundant with existing Q# standard library callables, and exist to help manage dependency ordering. It is proposed to move duplicated callables to the qsharp-runtime repo, and deprecate the copies in Microsoft.Quantum.Simulation.QuantumProcessor.Extensions. + +**Discussion**: + +- Does this affect the rewrite steps? + - Yes, but we can port those rewrite steps, and should do so. It will take minimal effort to do so. +- Impact on samples/katas? + - Minimal; only one sample uses at all. +- Observation: calling deprecated operations from deprecated operations still results in warnings (e.g.: ResultStack). + - Proposal: don't raise deprecation warnings from within deprecated callables. + - Action item: make feature request on qsharp-compiler. + +**Consensus**: Proceed as proposed. From c4f69418a55f3c93f1725a7b090523af28d08885 Mon Sep 17 00:00:00 2001 From: Mathias Soeken Date: Thu, 24 Sep 2020 01:23:18 +0200 Subject: [PATCH 04/15] Various additions and improvements to Microsoft.Quantum.Arrays (#330) --- ...JordanWignerClusterOperatorEvolutionSet.qs | 7 +- .../JordanWigner/JordanWignerEvolutionSet.qs | 5 +- .../Runtime/JordanWigner/JordanWignerVQE.qs | 4 +- MachineLearning/src/Private.qs | 2 +- MachineLearning/src/Structure.qs | 4 +- MachineLearning/src/Training.qs | 10 +- MachineLearning/src/Validation.qs | 2 +- MachineLearning/tests/StructureTests.qs | 10 +- Numerics/src/FixedPoint/Multiplication.qs | 4 +- Numerics/src/FixedPoint/Reciprocal.qs | 2 +- .../AmplitudeAmplification.qs | 2 +- Standard/src/Arithmetic/Arithmetic.qs | 2 +- Standard/src/Arithmetic/Integer.qs | 8 +- Standard/src/Arithmetic/Modular.qs | 2 +- Standard/src/Arithmetic/Reflections.qs | 2 +- Standard/src/Arrays/Arrays.qs | 44 +- Standard/src/Arrays/Deprecated.qs | 151 ++++++ Standard/src/Arrays/EqualA.qs | 2 +- Standard/src/Arrays/Filter.qs | 45 +- Standard/src/Arrays/Interleaved.qs | 50 ++ Standard/src/Arrays/Map.qs | 104 +++++ Standard/src/Arrays/Multidimensional.qs | 276 +++++++++++ Standard/src/Arrays/Reductions.qs | 55 +++ Standard/src/Arrays/Sorted.qs | 134 ++++++ Standard/src/Arrays/Unique.qs | 59 +++ Standard/src/Arrays/Windows.qs | 76 +++ Standard/src/Arrays/Zip.qs | 63 ++- Standard/src/Canon/And.qs | 2 +- Standard/src/Canon/Combinators/ApplyIf.qs | 8 +- .../Canon/Combinators/ApplyRepeatedOver.qs | 8 +- .../src/Canon/Combinators/ApplyToArray.qs | 434 ++++++++++++++++++ Standard/src/Canon/Parity.qs | 2 +- .../Characterization/Distinguishability.qs | 2 +- Standard/src/Diagnostics/Facts.qs | 4 +- Standard/src/Logical/Comparisons.qs | 85 ++++ Standard/src/Preparation/Reference.qs | 2 +- Standard/src/Synthesis/DecompositionBased.qs | 2 +- Standard/src/Synthesis/Transposition.qs | 4 +- Standard/tests/ArrayTests.qs | 194 ++++++-- Standard/tests/Arrays/SortedTests.qs | 76 +++ Standard/tests/Arrays/UniqueTests.qs | 25 + Standard/tests/CombinatorTests.qs | 8 +- Standard/tests/EnumerationTests.qs | 29 +- Standard/tests/Logical/ComparisonTests.qs | 38 ++ Standard/tests/QubitizationTests.qs | 2 +- 45 files changed, 1935 insertions(+), 115 deletions(-) create mode 100644 Standard/src/Arrays/Deprecated.qs create mode 100644 Standard/src/Arrays/Interleaved.qs create mode 100644 Standard/src/Arrays/Multidimensional.qs create mode 100644 Standard/src/Arrays/Reductions.qs create mode 100644 Standard/src/Arrays/Sorted.qs create mode 100644 Standard/src/Arrays/Unique.qs create mode 100644 Standard/src/Arrays/Windows.qs create mode 100644 Standard/src/Canon/Combinators/ApplyToArray.qs create mode 100644 Standard/src/Logical/Comparisons.qs create mode 100644 Standard/tests/Arrays/SortedTests.qs create mode 100644 Standard/tests/Arrays/UniqueTests.qs create mode 100644 Standard/tests/Logical/ComparisonTests.qs diff --git a/Chemistry/src/Runtime/JordanWigner/JordanWignerClusterOperatorEvolutionSet.qs b/Chemistry/src/Runtime/JordanWigner/JordanWignerClusterOperatorEvolutionSet.qs index 3489b204f33..660b48b4b4c 100644 --- a/Chemistry/src/Runtime/JordanWigner/JordanWignerClusterOperatorEvolutionSet.qs +++ b/Chemistry/src/Runtime/JordanWigner/JordanWignerClusterOperatorEvolutionSet.qs @@ -10,7 +10,7 @@ namespace Microsoft.Quantum.Chemistry.JordanWigner { open Microsoft.Quantum.Arrays; /// # Summary - /// Computes Z component of Jordan–Wigner string between + /// Computes Z component of Jordan–Wigner string between /// fermion indices in a fermionic operator with an even /// number of creation / annihilation operators. /// @@ -89,7 +89,7 @@ namespace Microsoft.Quantum.Chemistry.JordanWigner { let ops = [[PauliX, PauliY], [PauliY, PauliX]]; let signs = [+1.0, -1.0]; - for ((op, sign) in Zip(ops, signs)) { + for ((op, sign) in Zipped(ops, signs)) { let pauliString = _ComputeJordanWignerPauliString(Length(qubits), idxFermions, op); Exp(pauliString, sign * angle, qubits); } @@ -124,7 +124,7 @@ namespace Microsoft.Quantum.Chemistry.JordanWigner { let ops = [[y,y,x,y],[x,x,x,y],[x,y,y,y],[y,x,y,y],[x,y,x,x],[y,x,x,x],[y,y,y,x],[x,x,y,x]]; let (sortedIndices, signs, globalSign) = _JordanWignerClusterOperatorPQRSTermSigns([p,q,r,s]); - for ((op, sign) in Zip(ops, signs)) { + for ((op, sign) in Zipped(ops, signs)) { let pauliString = _ComputeJordanWignerPauliString(Length(qubits), sortedIndices, op); Exp(pauliString, globalSign * sign * angle, qubits); } @@ -272,4 +272,3 @@ namespace Microsoft.Quantum.Chemistry.JordanWigner { } - diff --git a/Chemistry/src/Runtime/JordanWigner/JordanWignerEvolutionSet.qs b/Chemistry/src/Runtime/JordanWigner/JordanWignerEvolutionSet.qs index 969a72221da..d9890ef31bd 100644 --- a/Chemistry/src/Runtime/JordanWigner/JordanWignerEvolutionSet.qs +++ b/Chemistry/src/Runtime/JordanWigner/JordanWignerEvolutionSet.qs @@ -8,7 +8,7 @@ namespace Microsoft.Quantum.Chemistry.JordanWigner { open Microsoft.Quantum.Chemistry; open Microsoft.Quantum.Arrays; - // This evolution set runs off data optimized for a Jordan–Wigner encoding. + // This evolution set runs off data optimized for a Jordan–Wigner encoding. // This collects terms Z, ZZ, PQandPQQR, hpqrs separately. // This only apples the needed hpqrs XXXX XXYY terms. // Operations here are expressed in terms of Exp([...]) @@ -134,7 +134,7 @@ namespace Microsoft.Quantum.Chemistry.JordanWigner { if (idxFermions[0] < qubitQidx and qubitQidx < idxFermions[3]) { let termPR1 = GeneratorIndex((idxTermType, [1.0]), [idxFermions[0], idxFermions[3] - 1]); - _ApplyJordanWignerPQTerm_(termPR1, angle, new Qubit[0], Exclude([qubitQidx], qubits)); + _ApplyJordanWignerPQTerm_(termPR1, angle, new Qubit[0], Excluding([qubitQidx], qubits)); } else { let termPR1 = GeneratorIndex((idxTermType, [1.0]), [0, idxFermions[3] - idxFermions[0]]); @@ -280,4 +280,3 @@ namespace Microsoft.Quantum.Chemistry.JordanWigner { } - diff --git a/Chemistry/src/Runtime/JordanWigner/JordanWignerVQE.qs b/Chemistry/src/Runtime/JordanWigner/JordanWignerVQE.qs index ba605577cb2..41e688129fa 100644 --- a/Chemistry/src/Runtime/JordanWigner/JordanWignerVQE.qs +++ b/Chemistry/src/Runtime/JordanWigner/JordanWignerVQE.qs @@ -39,7 +39,7 @@ namespace Microsoft.Quantum.Chemistry.JordanWigner.VQE { mutable jwTermEnergy = 0.; - for ((coeff, op) in Zip(coeffs, ops)) { + for ((coeff, op) in Zipped(coeffs, ops)) { // Only perform computation if the coefficient is significant enough if (AbsD(coeff) >= 1e-10) { // Compute expectation value using the fast frequency estimator, add contribution to Jordan-Wigner term energy @@ -95,7 +95,7 @@ namespace Microsoft.Quantum.Chemistry.JordanWigner.VQE { mutable compactOp = compactOps[iOp]; mutable op = ConstantArray(nQubits, PauliI); - for ((idx, pauli) in Zip(indices, compactOp)) { + for ((idx, pauli) in Zipped(indices, compactOp)) { set op w/= idx <- pauli; } for (i in indices[0]+1..indices[1]-1) { diff --git a/MachineLearning/src/Private.qs b/MachineLearning/src/Private.qs index 33a9ffa96b9..98d595441e5 100644 --- a/MachineLearning/src/Private.qs +++ b/MachineLearning/src/Private.qs @@ -6,7 +6,7 @@ namespace Microsoft.Quantum.MachineLearning { open Microsoft.Quantum.Math; function _AllNearlyEqualD(v1 : Double[], v2 : Double[]) : Bool { - return Length(v1) == Length(v2) and All(NearlyEqualD, Zip(v1, v2)); + return Length(v1) == Length(v2) and All(NearlyEqualD, Zipped(v1, v2)); } function _TailMeasurement(nQubits : Int) : (Qubit[] => Result) { diff --git a/MachineLearning/src/Structure.qs b/MachineLearning/src/Structure.qs index a3a80c5abd1..760e94ea9db 100644 --- a/MachineLearning/src/Structure.qs +++ b/MachineLearning/src/Structure.qs @@ -63,7 +63,7 @@ namespace Microsoft.Quantum.MachineLearning { } function _UncontrolledSpanSequence(idxsQubits : Int[]) : (Int, Int[])[] { - return Zip( + return Zipped( idxsQubits, ConstantArray(Length(idxsQubits), new Int[0]) ); @@ -210,4 +210,4 @@ namespace Microsoft.Quantum.MachineLearning { return combined; } -} \ No newline at end of file +} diff --git a/MachineLearning/src/Training.qs b/MachineLearning/src/Training.qs index 9eda6e6a0ae..0944b3ed998 100644 --- a/MachineLearning/src/Training.qs +++ b/MachineLearning/src/Training.qs @@ -160,9 +160,9 @@ namespace Microsoft.Quantum.MachineLearning { // size of the step taken during the move. We can find this size // as the squared norm of the gradient. SquaredNorm(batchGradient), - // To actually apply the step, we can use Mapped(PlusD, Zip(...)) + // To actually apply the step, we can use Mapped(PlusD, Zipped(...)) // to represent element-wise vector summation. - model w/ Parameters <- Mapped(PlusD, Zip(model::Parameters, batchGradient)) + model w/ Parameters <- Mapped(PlusD, Zipped(model::Parameters, batchGradient)) ); } @@ -239,7 +239,7 @@ namespace Microsoft.Quantum.MachineLearning { features, options::NMeasurements ); let updatedBias = _UpdatedBias( - Zip(probabilities, actualLabels), model::Bias, options::Tolerance + Zipped(probabilities, actualLabels), model::Bias, options::Tolerance ); let updatedLabels = InferredLabels( updatedBias, probabilities @@ -330,7 +330,7 @@ namespace Microsoft.Quantum.MachineLearning { ); // Find the best bias for the new classification parameters. let localBias = _UpdatedBias( - Zip(probabilities, Sampled(validationSchedule, labels)), + Zipped(probabilities, Sampled(validationSchedule, labels)), 0.0, options::Tolerance ); @@ -359,7 +359,7 @@ namespace Microsoft.Quantum.MachineLearning { ); mutable bestSoFar = model w/ Bias <- _UpdatedBias( - Zip(probabilities, actualLabels), + Zipped(probabilities, actualLabels), model::Bias, options::Tolerance ); let inferredLabels = InferredLabels( diff --git a/MachineLearning/src/Validation.qs b/MachineLearning/src/Validation.qs index 532c8c534d8..da28961b377 100644 --- a/MachineLearning/src/Validation.qs +++ b/MachineLearning/src/Validation.qs @@ -27,7 +27,7 @@ namespace Microsoft.Quantum.MachineLearning { : Int[] { return Where( NotEqualI, - Zip(inferredLabels, actualLabels) + Zipped(inferredLabels, actualLabels) ); } diff --git a/MachineLearning/tests/StructureTests.qs b/MachineLearning/tests/StructureTests.qs index e9ee25a29ae..d77108ed1af 100644 --- a/MachineLearning/tests/StructureTests.qs +++ b/MachineLearning/tests/StructureTests.qs @@ -53,14 +53,14 @@ namespace Microsoft.Quantum.MachineLearning.Tests { function EqualCR(x : ML.ControlledRotation, y : ML.ControlledRotation) : Bool { return x::Axis == y::Axis and - All(EqualI, Zip(x::ControlIndices, y::ControlIndices)) and + All(EqualI, Zipped(x::ControlIndices, y::ControlIndices)) and x::TargetIndex == y::TargetIndex and x::ParameterIndex == y::ParameterIndex; } @Test("QuantumSimulator") function LocalRotationsLayerFact() : Unit { - Fact(All(EqualCR, Zip( + Fact(All(EqualCR, Zipped( ML.LocalRotationsLayer(3, PauliY), [ Default() @@ -86,7 +86,7 @@ namespace Microsoft.Quantum.MachineLearning.Tests { @Test("QuantumSimulator") function PartialRotationsLayerFact() : Unit { - Fact(All(EqualCR, Zip( + Fact(All(EqualCR, Zipped( ML.PartialRotationsLayer([4, 5, 6], PauliY), [ Default() @@ -112,7 +112,7 @@ namespace Microsoft.Quantum.MachineLearning.Tests { @Test("QuantumSimulator") function CyclicEntanglingLayerFact() : Unit { - Fact(All(EqualCR, Zip( + Fact(All(EqualCR, Zipped( ML.CyclicEntanglingLayer(3, PauliX, 2), [ Default() @@ -160,7 +160,7 @@ namespace Microsoft.Quantum.MachineLearning.Tests { w/ ParameterIndex <- 0 ] ]); - Fact(All(EqualCR, Zip( + Fact(All(EqualCR, Zipped( combined, [ Default() diff --git a/Numerics/src/FixedPoint/Multiplication.qs b/Numerics/src/FixedPoint/Multiplication.qs index 837f0d7a362..3629d6472ad 100644 --- a/Numerics/src/FixedPoint/Multiplication.qs +++ b/Numerics/src/FixedPoint/Multiplication.qs @@ -43,7 +43,7 @@ namespace Microsoft.Quantum.Arithmetic { MultiplySI(xsInt, ysInt, tmpResultInt); (Controlled ApplyToEachCA)(controls, (CNOT, - Zip(tmpResult[n-px..2*n-px-1], zs))); + Zipped(tmpResult[n-px..2*n-px-1], zs))); (Adjoint MultiplySI)(xsInt, ysInt, tmpResultInt); } } @@ -77,7 +77,7 @@ namespace Microsoft.Quantum.Arithmetic { SquareSI(xsInt, tmpResultInt); (Controlled ApplyToEachCA)(controls, (CNOT, - Zip(tmpResult[n-px..2*n-px-1], ys))); + Zipped(tmpResult[n-px..2*n-px-1], ys))); (Adjoint SquareSI)(xsInt, tmpResultInt); } } diff --git a/Numerics/src/FixedPoint/Reciprocal.qs b/Numerics/src/FixedPoint/Reciprocal.qs index 0da13f03a96..33521863651 100644 --- a/Numerics/src/FixedPoint/Reciprocal.qs +++ b/Numerics/src/FixedPoint/Reciprocal.qs @@ -32,7 +32,7 @@ namespace Microsoft.Quantum.Arithmetic { ([sign], SignedLittleEndian(LittleEndian(xs))); ComputeReciprocalI(LittleEndian(xs), LittleEndian(tmpRes)); (Controlled ApplyToEachCA)(controls, - (CNOT, Zip(tmpRes[p+pRes-1+n-Length(rs)..Min([n+p+pRes, 2*n-1])], rs))); + (CNOT, Zipped(tmpRes[p+pRes-1+n-Length(rs)..Min([n+p+pRes, 2*n-1])], rs))); (Controlled Invert2sSI)([sign], SignedLittleEndian(LittleEndian(rs))); (Adjoint ComputeReciprocalI)(LittleEndian(xs), LittleEndian(tmpRes)); (Controlled Adjoint Invert2sSI) diff --git a/Standard/src/AmplitudeAmplification/AmplitudeAmplification.qs b/Standard/src/AmplitudeAmplification/AmplitudeAmplification.qs index dde60e11be4..646943ef900 100644 --- a/Standard/src/AmplitudeAmplification/AmplitudeAmplification.qs +++ b/Standard/src/AmplitudeAmplification/AmplitudeAmplification.qs @@ -57,7 +57,7 @@ namespace Microsoft.Quantum.AmplitudeAmplification { systemRegister : Qubit[] ) : Unit is Adj + Ctl { - for ((startPhase, targetPhase) in Zip(phases!)) { + for ((startPhase, targetPhase) in Zipped(phases!)) { if (startPhase != 0.0) { startStateReflection::ApplyReflection( startPhase, auxiliaryRegister diff --git a/Standard/src/Arithmetic/Arithmetic.qs b/Standard/src/Arithmetic/Arithmetic.qs index 189d0e79ce3..abab5bed060 100644 --- a/Standard/src/Arithmetic/Arithmetic.qs +++ b/Standard/src/Arithmetic/Arithmetic.qs @@ -28,7 +28,7 @@ namespace Microsoft.Quantum.Arithmetic { : Unit is Adj + Ctl { ApplyToEachCA( CControlledCA(X), - Zip(IntAsBoolArray(value, Length(target!)), target!) + Zipped(IntAsBoolArray(value, Length(target!)), target!) ); } diff --git a/Standard/src/Arithmetic/Integer.qs b/Standard/src/Arithmetic/Integer.qs index 6599c7c63fa..03e4fd1ff17 100644 --- a/Standard/src/Arithmetic/Integer.qs +++ b/Standard/src/Arithmetic/Integer.qs @@ -182,7 +182,7 @@ namespace Microsoft.Quantum.Arithmetic { CCNOT(xs![nQubits - 2], ys![nQubits - 1], carry); ApplyToEachCA(X, Most(Rest(ys!))); // X on ys[1..(nQubits-2)] CNOT(ancilla, ys![1]) ; - ApplyToEachCA(CNOT, Zip(Rest(Most(xs!)), Rest(Rest(ys!)))); + ApplyToEachCA(CNOT, Zipped(Rest(Most(xs!)), Rest(Rest(ys!)))); } /// # Summary @@ -222,7 +222,7 @@ namespace Microsoft.Quantum.Arithmetic { using (auxiliary = Qubit()) { within { - ApplyToEachCA(CNOT, Zip(Rest(xs!), Rest(ys!))); + ApplyToEachCA(CNOT, Zipped(Rest(xs!), Rest(ys!))); CNOT(xs![1], auxiliary); CCNOT(xs![0], ys![0], auxiliary); ApplyOuterCDKMAdder(xs, ys, auxiliary); @@ -309,7 +309,7 @@ namespace Microsoft.Quantum.Arithmetic { "Input registers must have the same number of qubits." ); - ApplyToEachCA(CNOT, Zip(Rest(xs!), Rest(ys!))); + ApplyToEachCA(CNOT, Zipped(Rest(xs!), Rest(ys!))); Adjoint ApplyCNOTChain(Rest(xs!)); } @@ -492,7 +492,7 @@ namespace Microsoft.Quantum.Arithmetic { else { within { ApplyToEachCA(X, ys!); - ApplyToEachCA(CNOT, Zip(Rest(xs!), Rest(ys!))); + ApplyToEachCA(CNOT, Zipped(Rest(xs!), Rest(ys!))); } apply { within { (Adjoint ApplyCNOTChain) (Rest(xs!)); diff --git a/Standard/src/Arithmetic/Modular.qs b/Standard/src/Arithmetic/Modular.qs index b4c94a58081..f9b91b6a7e9 100644 --- a/Standard/src/Arithmetic/Modular.qs +++ b/Standard/src/Arithmetic/Modular.qs @@ -245,7 +245,7 @@ namespace Microsoft.Quantum.Arithmetic { MultiplyAndAddByModularInteger(constMultiplier, modulus, multiplier, summandLE); // now the joint state is |x⟩|x⋅a(mod N)⟩ - ApplyToEachCA(SWAP, Zip(summandLE!, multiplier!)); + ApplyToEachCA(SWAP, Zipped(summandLE!, multiplier!)); // now the joint state is |x⋅a(mod N)⟩|x⟩ let inverseMod = InverseModI(constMultiplier, modulus); diff --git a/Standard/src/Arithmetic/Reflections.qs b/Standard/src/Arithmetic/Reflections.qs index eece6613db2..fdd459d1806 100644 --- a/Standard/src/Arithmetic/Reflections.qs +++ b/Standard/src/Arithmetic/Reflections.qs @@ -31,7 +31,7 @@ namespace Microsoft.Quantum.Arithmetic { // of X instructions that flip all the zeros in our index. ApplyToEachCA( CControlledCA(X), - Zip(Mapped(Not, IntAsBoolArray(index, Length(reg!))), reg!) + Zipped(Mapped(Not, IntAsBoolArray(index, Length(reg!))), reg!) ); } apply { Controlled Z(Most(reg!), Tail(reg!)); diff --git a/Standard/src/Arrays/Arrays.qs b/Standard/src/Arrays/Arrays.qs index 32e5ef991ab..c24f16329ee 100644 --- a/Standard/src/Arrays/Arrays.qs +++ b/Standard/src/Arrays/Arrays.qs @@ -63,10 +63,6 @@ namespace Microsoft.Quantum.Arrays { return array[0 .. Length(array) - 2]; } - internal function Lookup<'T> (array : 'T[], index : Int) : 'T { - return array[index]; - } - /// # Summary /// Given an array, returns a function which returns elements of that /// array. @@ -90,7 +86,7 @@ namespace Microsoft.Quantum.Arrays { /// where functions are used to avoid the need to record an entire array /// in memory. function LookupFunction<'T> (array : 'T[]) : (Int -> 'T) { - return Lookup(array, _); + return ElementAt(_, array); } /// # Summary @@ -129,6 +125,40 @@ namespace Microsoft.Quantum.Arrays { return array[0]; } + /// # Summary + /// Returns a tuple of first and all remaining elements of the array. + /// + /// # Type Parameters + /// ## 'A + /// The type of the array elements. + /// + /// # Input + /// ## array + /// An array with at least one element. + /// + /// # Output + /// A tuple of first and all remaining elements of the array. + function HeadAndRest<'A>(array : 'A[]) : ('A, 'A[]) { + return (Head(array), Rest(array)); + } + + /// # Summary + /// Returns a tuple of all but one and the last element of the array. + /// + /// # Type Parameters + /// ## 'A + /// The type of the array elements. + /// + /// # Input + /// ## array + /// An array with at least one element. + /// + /// # Output + /// A tuple of all but one and the last element of the array. + function MostAndTail<'A>(array : 'A[]) : ('A[], 'A) { + return (Most(array), Tail(array)); + } + /// # Summary /// Creates an array of given length with all elements equal to given value. /// @@ -182,9 +212,9 @@ namespace Microsoft.Quantum.Arrays { /// ```qsharp /// let array = [10, 11, 12, 13, 14, 15]; /// // The following line returns [10, 12, 15]. - /// let subarray = Exclude([1, 3, 4], array); + /// let subarray = Excluding([1, 3, 4], array); /// ``` - function Exclude<'T> (remove : Int[], array : 'T[]) : 'T[] { + function Excluding<'T>(remove : Int[], array : 'T[]) : 'T[] { let nSliced = Length(remove); let nElements = Length(array); diff --git a/Standard/src/Arrays/Deprecated.qs b/Standard/src/Arrays/Deprecated.qs new file mode 100644 index 00000000000..c90700a9b3f --- /dev/null +++ b/Standard/src/Arrays/Deprecated.qs @@ -0,0 +1,151 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +namespace Microsoft.Quantum.Arrays { + open Microsoft.Quantum.Arithmetic; + open Microsoft.Quantum.Logical; + + /// # Summary + /// Given two arrays, returns a new array of pairs such that each pair + /// contains an element from each original array. + /// + /// # Type Parameters + /// ## 'T + /// The type of the left array elements. + /// ## 'U + /// The type of the right array elements. + /// + /// # Input + /// ## left + /// An array containing values for the first element of each tuple. + /// ## right + /// An array containing values for the second element of each tuple. + /// + /// # Output + /// An array containing pairs of the form `(left[idx], right[idx])` for + /// each `idx`. If the two arrays are not of equal length, the output will + /// be as long as the shorter of the inputs. + /// + /// # Remarks + /// ## Example + /// ```qsharp + /// let left = [1, 3, 71]; + /// let right = [false, true]; + /// let pairs = Zip(left, right); // [(1, false), (3, true)] + /// ``` + /// + /// # See Also + /// - Zip3 + /// - Zip4 + /// - Unzipped + @Deprecated("Microsoft.Quantum.Arrays.Zipped") + function Zip<'T, 'U> (left : 'T[], right : 'U[]) : ('T, 'U)[] { + return Zipped(left, right); + } + + /// # Summary + /// Given three arrays, returns a new array of 3-tuples such that each 3-tuple + /// contains an element from each original array. + /// + /// # Type Parameters + /// ## 'T1 + /// The type of the first array elements. + /// ## 'T2 + /// The type of the second array elements. + /// ## 'T3 + /// The type of the third array elements. + /// + /// # Input + /// ## first + /// An array containing values for the first element of each tuple. + /// ## second + /// An array containing values for the second element of each tuple. + /// ## third + /// An array containing values for the third element of each tuple. + /// + /// # Output + /// An array containing 3-tuples of the form `(first[idx], second[idx], third[idx])` for + /// each `idx`. If the three arrays are not of equal length, the output will + /// be as long as the shorter of the inputs. + /// + /// # See Also + /// - Zip + /// - Zip4 + @Deprecated("Microsoft.Quantum.Arrays.Zipped3") + function Zip3<'T1, 'T2, 'T3> (first : 'T1[], second : 'T2[], third : 'T3[]) : ('T1, 'T2, 'T3)[] { + return Zipped3(first, second, third); + } + + + /// # Summary + /// Given four arrays, returns a new array of 4-tuples such that each 4-tuple + /// contains an element from each original array. + /// + /// # Type Parameters + /// ## 'T1 + /// The type of the first array elements. + /// ## 'T2 + /// The type of the second array elements. + /// ## 'T3 + /// The type of the third array elements. + /// ## 'T4 + /// The type of the fourth array elements. + /// + /// # Input + /// ## first + /// An array containing values for the first element of each tuple. + /// ## second + /// An array containing values for the second element of each tuple. + /// ## third + /// An array containing values for the third element of each tuple. + /// ## fourth + /// An array containing values for the fourth element of each tuple. + /// + /// # Output + /// An array containing 4-tuples of the form `(first[idx], second[idx], third[idx], fourth[idx])` for + /// each `idx`. If the four arrays are not of equal length, the output will + /// be as long as the shorter of the inputs. + /// + /// # See Also + /// - Zip + /// - Zip3 + @Deprecated("Microsoft.Quantum.Arrays.Zipped4") + function Zip4<'T1, 'T2, 'T3, 'T4> (first : 'T1[], second : 'T2[], third : 'T3[], fourth : 'T4[]) : ('T1, 'T2, 'T3, 'T4)[] { + return Zipped4(first, second, third, fourth); + } + + + + /// # Summary + /// Returns an array containing the elements of another array, + /// excluding elements at a given list of indices. + /// + /// # Type Parameters + /// ## 'T + /// The type of the array elements. + /// + /// # Input + /// ## remove + /// An array of indices denoting which elements should be excluded + /// from the output. + /// ## array + /// Array of which the values in the output array are taken. + /// + /// # Output + /// An array `output` such that `output[0]` is the first element + /// of `array` whose index does not appear in `remove`, + /// such that `output[1]` is the second such element, and so + /// forth. + /// + /// # Remarks + /// ## Example + /// ```qsharp + /// let array = [10, 11, 12, 13, 14, 15]; + /// // The following line returns [10, 12, 15]. + /// let subarray = Exclude([1, 3, 4], array); + /// ``` + function Exclude<'T>(remove : Int[], array : 'T[]) : 'T[] { + return Excluding(remove, array); + } + +} diff --git a/Standard/src/Arrays/EqualA.qs b/Standard/src/Arrays/EqualA.qs index 960db42b490..eb3cfc4143f 100644 --- a/Standard/src/Arrays/EqualA.qs +++ b/Standard/src/Arrays/EqualA.qs @@ -51,7 +51,7 @@ namespace Microsoft.Quantum.Arrays { if (Length(array1) != Length(array2)) { return false; } - return All(equal, Zip(array1, array2)); + return All(equal, Zipped(array1, array2)); } } diff --git a/Standard/src/Arrays/Filter.qs b/Standard/src/Arrays/Filter.qs index f03605ef773..38a7c463637 100644 --- a/Standard/src/Arrays/Filter.qs +++ b/Standard/src/Arrays/Filter.qs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace Microsoft.Quantum.Arrays { @@ -40,7 +40,7 @@ namespace Microsoft.Quantum.Arrays { /// } /// ``` /// The outcome one should expect from this example will be an array of numbers greater than 5. - function Filtered<'T> (predicate : ('T -> Bool), array : 'T[]) : 'T[] { + function Filtered<'T>(predicate : ('T -> Bool), array : 'T[]) : 'T[] { mutable totalFound = 0; mutable idxArray = new Int[Length(array)]; @@ -80,4 +80,45 @@ namespace Microsoft.Quantum.Arrays { ); } + /// # Summary + /// Given an array and a predicate that is defined + /// for the elements of the array, returns the number of elements + /// an array that consists of those elements that satisfy the predicate. + /// + /// # Remarks + /// The function is defined for generic types, i.e., whenever we have + /// an array `'T[]` and a predicate `'T -> Bool` we can filter elements. + /// + /// # Type Parameters + /// ## 'T + /// The type of `array` elements. + /// + /// # Input + /// ## predicate + /// A function from `'T` to Boolean that is used to filter elements. + /// ## array + /// An array of elements over `'T`. + /// + /// # Output + /// The number of elements in `array` that satisfy the predicate. + /// + /// # Example + /// The following code demonstrates the "Count" function. + /// A predicate is defined using the @"microsoft.quantum.logical.greaterthani" function: + /// ```Q# + /// let predicate = GreaterThanI(_, 5); + /// let count = Count(predicate, [2, 5, 9, 1, 8]); + /// // count = 2 + /// ``` + function Count<'T>(predicate : ('T -> Bool), array : 'T[]) : Int { + mutable totalFound = 0; + + for (element in array) { + if (predicate(element)) { + set totalFound += 1; + } + } + + return totalFound; + } } diff --git a/Standard/src/Arrays/Interleaved.qs b/Standard/src/Arrays/Interleaved.qs new file mode 100644 index 00000000000..05cbc93b6e4 --- /dev/null +++ b/Standard/src/Arrays/Interleaved.qs @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace Microsoft.Quantum.Arrays { + open Microsoft.Quantum.Diagnostics; + + /// # Summary + /// Interleaves two arrays of (almost) same size. + /// + /// # Description + /// This function returns the interleaving of two arrays, starting + /// with the first element from the first array, then the first + /// element from the second array, and so on. + /// + /// The first array must either be + /// of the same length as the second one, or can have one more element. + /// + /// # Type Parameters + /// ## 'T + /// The type of each element of `first` and `second`. + /// + /// # Input + /// ## first + /// The first array to be interleaved. + /// + /// ## second + /// The second array to be interleaved. + /// + /// # Output + /// Interleaved array + /// + /// # Example + /// ```Q# + /// // same as int1 = [1, -1, 2, -2, 3, -3] + /// let int1 = Interleaved([1, 2, 3], [-1, -2, -3]) + /// + /// // same as int2 = [false, true, false, true, false] + /// let int2 = Interleaved(ConstantArray(3, false), ConstantArray(2, true)); + /// ``` + function Interleaved<'T>(first : 'T[], second : 'T[]) : 'T[] { + let lFirst = Length(first); + let lSecond = Length(second); + + Fact(lFirst >= lSecond and lFirst - lSecond <= 1, "Array `first` is either of same size as `second`, or has one more element"); + + return new 'T[lFirst + lSecond] + w/ 0..2..(lFirst + lSecond - 1) <- first + w/ 1..2..(lFirst + lSecond - 1) <- second; + } +} diff --git a/Standard/src/Arrays/Map.qs b/Standard/src/Arrays/Map.qs index e6e28337d0e..b541190a738 100644 --- a/Standard/src/Arrays/Map.qs +++ b/Standard/src/Arrays/Map.qs @@ -2,6 +2,7 @@ // Licensed under the MIT License. namespace Microsoft.Quantum.Arrays { + open Microsoft.Quantum.Math; /// # Summary /// Given an array and a function that is defined @@ -86,6 +87,109 @@ namespace Microsoft.Quantum.Arrays { return resultArray; } + /// # Summary + /// Given a range and a function that takes an integer as input, + /// returns a new array that consists + /// of the images of the range values under the function. + /// + /// # Remarks + /// The function is defined for generic types, i.e., whenever we have + /// a function `mapper: Int -> 'T` we can map the values + /// of the range and produce an array of type `'T[]`. + /// + /// # Type Parameters + /// ## 'T + /// The result type of the `mapper` function. + /// + /// # Input + /// ## mapper + /// A function from `Int` to `'T` that is used to map range values. + /// ## range + /// A range of integers. + /// + /// # Output + /// An array `'T[]` of elements that are mapped by the `mapper` function. + /// + /// # Example + /// This example adds 1 to a range of even numbers: + /// ```Q# + /// let numbers = MappedOverRange(PlusI(1, _), 0..2..10); + /// // numbers = [1, 3, 5, 7, 9, 11] + /// ``` + /// + /// # See Also + /// - Microsoft.Quantum.Arrays.Mapped + function MappedOverRange<'T> (mapper : (Int -> 'T), range : Range) : 'T[] { + let start = RangeStart(range); + let step = RangeStep(range); + let end = RangeEnd(range); + if ((end - start) / step >= 0) { + let nTerms = (end - start) / step + 1; + mutable resultArray = new 'T[nTerms]; + mutable idxElement = 0; + for (elem in range) { + set resultArray w/= idxElement <- mapper(elem); + set idxElement += 1; + } + return resultArray; + } else { + return new 'T[0]; + } + } + + /// # Summary + /// Given an array and a function that maps an array element to some output + /// array, returns the concatenated output arrays for each array element. + /// + /// # Type Parameters + /// ## 'TInput + /// The type of `array` elements. + /// ## 'TOutput + /// The `mapper` function returns arrays of this type. + /// + /// # Input + /// ## mapper + /// A function from `'TInput` to `'TOutput[]` that is used to map array elements. + /// ## array + /// An array of elements. + /// + /// # Output + /// An array of `'TOutput[]` which is the concatenation of all arrays generated by + /// the mapping function. + /// + /// # Example + /// ```Q# + /// let Numbers = SequenceI(1, _); // generates numbers starting from 1 + /// let values = FlatMapped(Numbers, [1, 2, 3]); + /// // values = [1, 1, 2, 1, 2, 3] + /// ``` + function FlatMapped<'TInput, 'TOutput>(mapper : ('TInput -> 'TOutput[]), array : 'TInput[]) : 'TOutput[] { + return Fold(PlusA<'TOutput>, new 'TOutput[0], Mapped(mapper, array)); + } + + /// # Summary + /// Given an array of arrays, returns the concatenation of all arrays. + /// + /// # Type Parameters + /// ## 'T + /// The type of `array` elements. + /// + /// # Input + /// ## arrays + /// Array of arrays. + /// + /// # Output + /// Concatenation of all arrays. + /// + /// # Example + /// ```Q# + /// let flattened = Flattened([[1, 2], [3], [4, 5, 6]]); + /// // flattened = [1, 2, 3, 4, 5, 6] + /// ``` + function Flattened<'T>(arrays : 'T[][]): 'T[] { + return Fold(PlusA<'T>, new 'T[0], arrays); + } + /// # Summary /// Given an array and an operation that is defined /// for the elements of the array, returns a new array that consists diff --git a/Standard/src/Arrays/Multidimensional.qs b/Standard/src/Arrays/Multidimensional.qs new file mode 100644 index 00000000000..7e2102585ab --- /dev/null +++ b/Standard/src/Arrays/Multidimensional.qs @@ -0,0 +1,276 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace Microsoft.Quantum.Arrays { + open Microsoft.Quantum.Canon; + open Microsoft.Quantum.Convert; + open Microsoft.Quantum.Diagnostics; + open Microsoft.Quantum.Logical; + open Microsoft.Quantum.Math; + + /// # Summary + /// Returns the transpose of a matrix represented as an array + /// of arrays. + /// + /// # Description + /// Input as an $r \times c$ matrix with $r$ rows and $c$ columns. The matrix + /// is row-based, i.e., `matrix[i][j]` accesses the element at row $i$ and column $j$. + /// + /// This function returns the $c \times r$ matrix that is the transpose of the + /// input matrix. + /// + /// # Type Parameters + /// ## 'T + /// The type of each element of `matrix`. + /// + /// # Input + /// ## matrix + /// Row-based $r \times c$ matrix + /// + /// # Output + /// Transposed $c \times r$ matrix + /// + /// # Example + /// ```Q# + /// // same as [[1, 4], [2, 5], [3, 6]] + /// let transposed = Transposed([[1, 2, 3], [4, 5, 6]]); + /// ``` + function Transposed<'T>(matrix : 'T[][]) : 'T[][] { + let numRows = Length(matrix); + Fact(numRows > 0, "Matrix must have at least 1 row"); + let numColumns = Length(Head(matrix)); + Fact(numColumns > 0, "Matrix must have at least 1 column"); + RectangularArrayFact(matrix, "Matrix is not a rectangular array"); + + return Mapped(ColumnAtUnchecked(_, matrix), SequenceI(0, numColumns - 1)); + } + + /// # Summary + /// Returns the at the given index of an array. + /// + /// # Type Parameters + /// ## 'T + /// The type of each element of `array`. + /// + /// # Input + /// ## index + /// Index of element + /// ## array + /// The array being indexed. + /// + /// # Remark + /// This function is more general than `LookupFunction`, since + /// it can also be used for partial application on a fixed index. + /// Note that the type parameter must explicitly be provided in + /// this case as it cannot be deduced automatically. + /// + /// # Example + /// Get the third number in four famous integer sequences. (note + /// that the 0 index corresponds to the _first_ value of the sequence.) + /// ```Q# + /// let lucas = [2, 1, 3, 4, 7, 11, 18, 29, 47, 76]; + /// let prime = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]; + /// let fibonacci = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]; + /// let catalan = [1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862]; + /// let famous2 = Mapped(ElementAt(2, _), [lucas, prime, fibonacci, catalan]); + /// // same as: famous2 = [3, 5, 1, 2] + /// ``` + /// + /// # See Also + /// - Microsoft.Quantum.Arrays.LookupFunction + /// - Microsoft.Quantum.Arrays.ElementsAt + function ElementAt<'T>(index : Int, array : 'T[]) : 'T { + Fact(index >= 0 and index < Length(array), "Index is out of bound"); + return array[index]; + } + + /// # Summary + /// Returns the array's elements at a given range + /// of indices. + /// + /// # Type Parameters + /// ## 'T + /// The type of each element of `array`. + /// + /// # Input + /// ## range + /// Range of array indexes + /// ## array + /// Array + /// + /// # Example + /// Get the odd indexes in famous integer sequences. (note + /// that the 0 index corresponds to the _first_ value of the sequence.) + /// ```Q# + /// let lucas = [2, 1, 3, 4, 7, 11, 18, 29, 47, 76]; + /// let prime = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]; + /// let fibonacci = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]; + /// let catalan = [1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862]; + /// let famousOdd = Mapped(ElementsAt(0..2..9, _), [lucas, prime, fibonacci, catalan]); + /// // same as: famousOdd = [[2, 3, 7, 18, 47], [2, 5, 11, 17, 23], [0, 1, 3, 8, 21], [1, 2, 14, 132, 1430]] + /// ``` + /// + /// # See Also + /// - Microsoft.Quantum.Arrays.ElementAt + /// - Microsoft.Quantum.Arrays.LookupFunction + function ElementsAt<'T>(range : Range, array : 'T[]) : 'T[] { + return array[range]; + } + + /// # Summary + /// Extracts a column from a matrix. + /// + /// # Description + /// This function extracts a column in a matrix in row-wise order. + /// Extracting a row corrsponds to element access of the first index + /// and therefore requires no further treatment. + /// + /// # Type Parameters + /// ## 'T + /// The type of each element of `matrix`. + /// + /// # Input + /// ## column + /// Column of the matrix + /// ## matrix + /// 2-dimensional matrix in row-wise order + /// + /// # Example + /// ```Q# + /// let matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; + /// let column = ColumnAt(0, matrix); + /// // same as: column = [1, 4, 7] + /// ``` + /// + /// # See Also + /// - Microsoft.Quantum.Arrays.Transposed + /// - Microsoft.Quantum.Arrays.Diagonal + function ColumnAt<'T>(column : Int, matrix : 'T[][]) : 'T[] { + RectangularArrayFact(matrix, "Matrix is not a rectangular array"); + return ColumnAtUnchecked(column, matrix); + } + + /// # Summary + /// This function does not check for matrix shape + /// + /// # Description + /// This function can be used in other multidimensional functions, + /// which already check the input matrix for a valid rectangular shape. + internal function ColumnAtUnchecked<'T>(column : Int, matrix : 'T[][]) : 'T[] { + return Mapped( + Compose( + ElementAt<'T>(column, _), + LookupFunction(matrix) + ), RangeAsIntArray(IndexRange(matrix))); + } + + /// # Summary + /// Returns an array of diagonal elements of a 2-dimensional array + /// + /// # Description + /// If the 2-dimensional array has not a square shape, the diagonal over + /// the minimum over the number of rows and columns will be returned. + /// + /// # Type Parameters + /// ## 'T + /// The type of each element of `matrix`. + /// + /// # Input + /// ## matrix + /// 2-dimensional matrix in row-wise order + /// + /// # Example + /// ```Q# + /// let matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; + /// let diagonal = Diagonal(matrix); + /// // same as: column = [1, 5, 9] + /// ``` + /// + /// # See Also + /// - Microsoft.Quantum.Arrays.Transposed + function Diagonal<'T>(matrix : 'T[][]) : 'T[] { + RectangularArrayFact(matrix, "Matrix is not a rectangular array"); + + let numRows = Length(matrix); + let numColumns = numRows == 0 ? 0 | Length(Head(matrix)); + + return MappedOverRange(ElementAtDiagonal(_, matrix), 0..(MinI(numRows, numColumns) - 1)); + } + + internal function ElementAtDiagonal<'T>(index : Int, matrix : 'T[][]) : 'T { + return matrix[index][index]; + } + + /// # Summary + /// Represents a condition that a 2-dimensional array has a rectangular shape + /// + /// # Description + /// This function asserts that each row in an array has the same length. + /// + /// # Type Parameters + /// ## 'T + /// The type of each element of `array`. + /// + /// # Input + /// ## array + /// A 2-dimensional array of elements + /// ## message + /// A message to be printed if the array is not a rectangular array + /// + /// # Example + /// ```Q# + /// RectangularArrayFact([[1, 2], [3, 4]], "Array is not rectangular"); // okay + /// RectangularArrayFact([[1, 2, 3], [4, 5, 6]], "Array is not rectangular"); // okay + /// RectangularArrayFact([[1, 2], [3, 4, 5]], "Array is not rectangular"); // will fail + /// ``` + /// + /// # See Also + /// - Microsoft.Quantum.Arrays.SquareArrayFact + function RectangularArrayFact<'T>(array : 'T[][], message : String) : Unit { + if (Length(array) == 0) { + return (); + } else { + let numColumns = Length(Head(array)); + if (Any(Compose(NotEqualI(numColumns, _), Length<'T>), Rest(array))) { + fail message; + } + } + } + + /// # Summary + /// Represents a condition that a 2-dimensional array has a square shape + /// + /// # Description + /// This function asserts that each row in an array has + /// as many elements as there are rows (elements) in the array. + /// + /// # Type Parameters + /// ## 'T + /// The type of each element of `array`. + /// + /// # Input + /// ## array + /// A 2-dimensional array of elements + /// ## message + /// A message to be printed if the array is not a square array + /// + /// # Example + /// ```Q# + /// SquareArrayFact([[1, 2], [3, 4]], "Array is not a square"); // okay + /// SquareArrayFact([[1, 2, 3], [4, 5, 6]], "Array is not a square"); // will fail + /// SquareArrayFact([[1, 2], [3, 4, 5]], "Array is not a square"); // will fail + /// ``` + /// + /// # See Also + /// - Microsoft.Quantum.Arrays.RectangularArrayFact + function SquareArrayFact<'T>(array : 'T[][], message : String) : Unit { + if (Length(array) == 0) { + return (); + } else { + let numColumns = Length(array); + if (Any(Compose(NotEqualI(numColumns, _), Length<'T>), array)) { + fail message; + } + } + } +} diff --git a/Standard/src/Arrays/Reductions.qs b/Standard/src/Arrays/Reductions.qs new file mode 100644 index 00000000000..201c45b4fd7 --- /dev/null +++ b/Standard/src/Arrays/Reductions.qs @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace Microsoft.Quantum.Arrays { + + /// # Summary + /// Combines Mapped and Fold into a single function + /// + /// # Description + /// This function iterates the `fn` function through the array, starting from + /// an initial state `state` and returns all intermediate values, not including + /// the inital state. + /// + /// # Type Parameters + /// ## 'State + /// The type of states that the `fn` function operates on, i.e., accepts as its first + /// input and returns. + /// ## 'T + /// The type of `array` elements. + /// + /// # Input + /// ## fn + /// A function to be folded over the array + /// + /// ## state + /// The initial state to be folded + /// + /// ## array + /// An array of values to be folded over + /// + /// # Output + /// All intermediate states, including the final state, but not the initial state. + /// The length of the output array is of the same length as `array`. + /// + /// # Remark + /// This function generalizes `Fold` since + /// `Tail(CumulativeFolded(fn, state, array))` is the same as `Fold(fn, state, array)`. + /// + /// # Example + /// ```Q# + /// // same as sums = [1, 3, 6, 10, 15] + /// let sums = CumulativeFolded(PlusI, 0, SequenceI(1, 5)); + /// ``` + function CumulativeFolded<'State, 'T>(fn : (('State, 'T) -> 'State), state : 'State, array : 'T[]) : 'State[] { + mutable current = state; + mutable result = new 'State[Length(array)]; + + for ((i, elem) in Enumerated(array)) { + set current = fn(current, elem); + set result w/= i <- current; + } + + return result; + } +} diff --git a/Standard/src/Arrays/Sorted.qs b/Standard/src/Arrays/Sorted.qs new file mode 100644 index 00000000000..7cb3b15b5fc --- /dev/null +++ b/Standard/src/Arrays/Sorted.qs @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace Microsoft.Quantum.Arrays { + open Microsoft.Quantum.Intrinsic; + open Microsoft.Quantum.Canon; + + /// # Summary + /// Given two sorted arrays, returns a single array containing the + /// elements of both in sorted order. Used internally by merge sort. + internal function Merged<'T>(comparison : (('T, 'T) -> Bool), left : 'T[], right : 'T[]) : 'T[] { + mutable result = new 'T[0]; + mutable l = left; + mutable r = right; + while ((not IsEmpty(l)) and (not IsEmpty(r))) { + if (comparison(Head(l), Head(r))) { + set result += [Head(l)]; + set l = Rest(l); + } else { + set result += [Head(r)]; + set r = Rest(r); + } + } + + // Note that at this point, either or both of l and r are empty, + // such that we can simply append both to our result to get the + // whole merged array. + return result + l + r; + } + + /// # Summary + /// Given an array, returns whether that array is sorted as defined by + /// a given comparison function. + /// + /// # Type Parameters + /// ## 'T + /// The type of each element of `array`. + /// + /// # Input + /// ## comparison + /// A function that compares two elements such that `a` is considered to + /// be less than or equal to `b` if `comparison(a, b)` is `true`. + /// ## array + /// The array to be checked. + /// + /// # Output + /// `true` if and only if for each pair of elements `a` and `b` of + /// `array` occuring in that order, `comparison(a, b)` is `true`. + /// + /// # Remarks + /// The function `comparison` is assumed to be transitive, such that + /// if `comparison(a, b)` and `comparison(b, c)`, then `comparison(a, c)` + /// is assumed. If this property does not hold, then the output of this + /// function may be incorrect. + function IsSorted<'T>(comparison : (('T, 'T) -> Bool), array : 'T[]) : Bool { + return All( + comparison, + Zipped(Most(array), Rest(array)) + ); + } + + /// # Summary + /// Given an array, returns the elements of that array sorted by a given + /// comparison function. + /// + /// # Type Parameters + /// ## 'T + /// The type of each element of `array`. + /// + /// # Input + /// ## comparison + /// A function that compares two elements such that `a` is considered to + /// be less than or equal to `b` if `comparison(a, b)` is `true`. + /// ## array + /// The array to be sorted. + /// + /// # Ouput + /// An array containing the same elements as `array`, such that for all + /// elements `a` occuring earlier than elements `b`, `comparison(a, b)` + /// is `true`. + /// + /// # Example + /// The following snippet sorts an array of integers to occur in ascending + /// order: + /// ```Q# + /// let sortedArray = Sorted(LessThanOrEqualI, [3, 17, 11, -201, -11]); + /// ``` + /// + /// # Remarks + /// The function `comparison` is assumed to be transitive, such that + /// if `comparison(a, b)` and `comparison(b, c)`, then `comparison(a, c)` + /// is assumed. If this property does not hold, then the output of this + /// function may be incorrect. + /// + /// As this is a function, the results are completely determinstic, even + /// when two elements are considered equal under `comparison`; + /// that is, when `comparison(a, b)` and `comparison(b, a)` are both `true`. + /// In particular, the sort performed by this function is guaranteed to be + /// stable, so that if two elements `a` and `b` occur in that order within + /// `array` and are considered equal under `comparison`, then `a` will also + /// appear before `b` in the output. + /// + /// For example: + /// ```Q# + /// function LastDigitLessThanOrEqual(left : Int, right : Int) : Bool { + /// return LessThanOrEqualI( + /// left % 10, right % 10 + /// ); + /// } + /// + /// function SortedByLastDigit() : Int[] { + /// return Sorted(LastDigitLessThanOrEqual, [3, 37, 11, 17]); + /// } + /// // returns [11, 3, 37, 17]. + /// ``` + function Sorted<'T>(comparison : (('T, 'T) -> Bool), array : 'T[]) : 'T[] { + if (Length(array) <= 1) { + return array; + } else { + let idxPivot = Length(array) / 2; + let left = array[...idxPivot - 1]; + let right = array[idxPivot...]; + + // Sort each sublist, then merge them back into a single combined + // list and return. + return Merged<'T>( + comparison, + Sorted(comparison, left), + Sorted(comparison, right) + ); + } + } + +} diff --git a/Standard/src/Arrays/Unique.qs b/Standard/src/Arrays/Unique.qs new file mode 100644 index 00000000000..ea588a399eb --- /dev/null +++ b/Standard/src/Arrays/Unique.qs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace Microsoft.Quantum.Arrays { + /// # Summary + /// Returns a new array that has no equal adjacent elements. + /// + /// # Description + /// Given some array of elements and a function to test equality, this + /// function returns a new array in which the relative order of elements + /// is kept, but all adjacent elements which are equal are filtered to + /// just a single element. + /// + /// # Type Parameters + /// ## 'T + /// The type of each element of `array`. + /// + /// # Input + /// ## equal + /// A function that compares two elements such that `a` is considered to + /// be equal to `b` if `equal(a, b)` is `true`. + /// ## array + /// The array to be filtered for unique elements. + /// + /// # Output + /// Array with no equal adjacent elements. + /// + /// # Remarks + /// If there are multiple elements that are equal but not next to each other, + /// there will be multiple occurrences in the output array. Use this function + /// together with `Sorted` to get an array with overall unique elements. + /// + /// # Example + /// ```Q# + /// let unique1 = Unique(EqualI, [1, 1, 3, 3, 2, 5, 5, 5, 7]); + /// // same as [1, 3, 2, 5, 7] + /// let unique2 = Unique(EqualI, [2, 2, 1, 1, 2, 2, 1, 1]); + /// // same as [2, 1, 2, 1]; + /// let unique3 = Unique(EqualI, Sorted(LessThanOrEqualI, [2, 2, 1, 1, 2, 2, 1, 1])); + /// // same as [1, 2]; + /// ``` + function Unique<'T>(equal : (('T, 'T) -> Bool), array : 'T[]) : 'T[] { + if (Length(array) == 0) { + return new 'T[0]; + } + + mutable unique = ConstantArray(Length(array), Head(array)); + mutable count = 1; + + for (elem in Rest(array)) { + if (not equal(elem, unique[count - 1])) { + set unique w/= count <- elem; + set count += 1; + } + } + + return unique[0..count - 1]; + } +} diff --git a/Standard/src/Arrays/Windows.qs b/Standard/src/Arrays/Windows.qs new file mode 100644 index 00000000000..bcad5c35111 --- /dev/null +++ b/Standard/src/Arrays/Windows.qs @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace Microsoft.Quantum.Arrays { + + /// # Summary + /// Returns all consecutive subarrays of length `size`. + /// + /// # Description + /// This function returns all `n - size + 1` subarrays of + /// length `size` in order, where `n` is the length of `arr`. + /// The first subarrays are `arr[0..size - 1], arr[1..size], arr[2..size + 1]` + /// until the last subarray `arr[n - size..n - 1]`. + /// + /// If `size <= 0` or `size > n`, an empty array is returned. + /// + /// # Type Parameters + /// ## 'T + /// The type of `array` elements. + /// + /// # Input + /// ## size + /// Length of the subarrays. + /// + /// ## array + /// An array of elements. + /// + /// # Example + /// ```Q# + /// // same as [[1, 2, 3], [2, 3, 4], [3, 4, 5]] + /// let windows = Windows(3, [1, 2, 3, 4, 5]); + /// ``` + function Windows<'T>(size : Int, array : 'T[]) : 'T[][] { + let n = Length(array); + + if (size <= 0 or size > n) { + return new 'T[][0]; + } + + mutable result = new 'T[][n + 1 - size]; + + for (i in 0..n - size) { + set result w/= i <- array[i..i + size - 1]; + } + + return result; + } + + /// # Summary + /// Given an array, returns all its prefixes. + /// + /// # Description + /// Returns an array of all prefixes, starting with an array that only + /// has the first element until the complete array. + /// + /// # Type Parameters + /// ## 'T + /// The type of `array` elements. + /// + /// # Input + /// ## array + /// An array of elements. + /// + /// # Example + /// ```Q# + /// let prefixes = Prefixes([23, 42, 144]); + /// // prefixes = [[23], [23, 42], [23, 42, 144]] + /// ``` + function Prefixes<'T>(array : 'T[]) : 'T[][] { + return MappedOverRange(Prefix(_, array), IndexRange(array)); + } + + internal function Prefix<'T>(to : Int, array : 'T[]) : 'T[] { + return array[0..to]; + } +} diff --git a/Standard/src/Arrays/Zip.qs b/Standard/src/Arrays/Zip.qs index caa785a2ba5..2b164f22161 100644 --- a/Standard/src/Arrays/Zip.qs +++ b/Standard/src/Arrays/Zip.qs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace Microsoft.Quantum.Arrays { @@ -30,13 +30,14 @@ namespace Microsoft.Quantum.Arrays { /// ```qsharp /// let left = [1, 3, 71]; /// let right = [false, true]; - /// let pairs = Zip(left, right); // [(1, false), (3, true)] + /// let pairs = Zipped(left, right); // [(1, false), (3, true)] /// ``` /// /// # See Also - /// - Zip3 - /// - Zip4 - function Zip<'T, 'U> (left : 'T[], right : 'U[]) : ('T, 'U)[] { + /// - Microsoft.Quantum.Arrays.Zipped3 + /// - Microsoft.Quantum.Arrays.Zipped4 + /// - Microsoft.Quantum.Arrays.Unzipped + function Zipped<'T, 'U>(left : 'T[], right : 'U[]) : ('T, 'U)[] { let nElements = Length(left) < Length(right) ? Length(left) | Length(right); @@ -75,9 +76,9 @@ namespace Microsoft.Quantum.Arrays { /// be as long as the shorter of the inputs. /// /// # See Also - /// - Zip - /// - Zip4 - function Zip3<'T1, 'T2, 'T3> (first : 'T1[], second : 'T2[], third : 'T3[]) : ('T1, 'T2, 'T3)[] { + /// - Microsoft.Quantum.Arrays.Zipped + /// - Microsoft.Quantum.Arrays.Zipped4 + function Zipped3<'T1, 'T2, 'T3> (first : 'T1[], second : 'T2[], third : 'T3[]) : ('T1, 'T2, 'T3)[] { let nElements = Min([Length(first), Length(second), Length(third)]); mutable output = new ('T1, 'T2, 'T3)[nElements]; @@ -118,9 +119,9 @@ namespace Microsoft.Quantum.Arrays { /// be as long as the shorter of the inputs. /// /// # See Also - /// - Zip - /// - Zip3 - function Zip4<'T1, 'T2, 'T3, 'T4> (first : 'T1[], second : 'T2[], third : 'T3[], fourth : 'T4[]) : ('T1, 'T2, 'T3, 'T4)[] { + /// - Microsoft.Quantum.Arrays.Zipped + /// - Microsoft.Quantum.Arrays.Zipped3 + function Zipped4<'T1, 'T2, 'T3, 'T4> (first : 'T1[], second : 'T2[], third : 'T3[], fourth : 'T4[]) : ('T1, 'T2, 'T3, 'T4)[] { let nElements = Min([Length(first), Length(second), Length(third), Length(fourth)]); mutable output = new ('T1, 'T2, 'T3, 'T4)[nElements]; @@ -131,6 +132,46 @@ namespace Microsoft.Quantum.Arrays { return output; } + /// # Summary + /// Given an array of 2-tuples, returns a tuple of two arrays, each containing + /// the elements of the tuples of the input array. + /// + /// # Type Parameters + /// ## 'T + /// The type of the first element in each tuple + /// ## 'U + /// The type of the second element in each tuple + /// + /// # Input + /// ## arr + /// An array containing 2-tuples + /// + /// # Output + /// Two arrays, the first one containing all first elements of the input + /// tuples, the second one containing all second elements of the input tuples. + /// + /// # Example + /// ```Q# + /// // split is same as ([6, 5, 5, 3, 2, 1], [true, false, false, false, true, false]) + /// let split = Unzipped([(6, true), (5, false), (5, false), (3, false), (2, true), (1, false)]); + /// ``` + /// + /// # Remark + /// This function is equivalent to `(Mapped(Fst<'T, 'U>, arr), Mapped(Snd<'T, 'U>, arr))`. + /// + /// # See Also + /// - Microsoft.Quantum.Arrays.Zipped + function Unzipped<'T, 'U>(arr : ('T, 'U)[]) : ('T[], 'U[]) { + let nElements = Length(arr); + mutable first = new 'T[nElements]; + mutable second = new 'U[nElements]; + for (idxElement in 0 .. nElements - 1) { + let (left, right) = arr[idxElement]; + set first w/= idxElement <- left; + set second w/= idxElement <- right; + } + return (first, second); + } } diff --git a/Standard/src/Canon/And.qs b/Standard/src/Canon/And.qs index 7cfaf5797b1..3b8452f36f4 100644 --- a/Standard/src/Canon/And.qs +++ b/Standard/src/Canon/And.qs @@ -167,7 +167,7 @@ namespace Microsoft.Quantum.Canon { if (i % 2 == 0) { set j = 0; } else { - let e = Zip(current, RangeAsIntArray(0..N - 1)); + let e = Zipped(current, RangeAsIntArray(0..N - 1)); set j = Snd(Head(Filtered(Fst, e))) + 1; } diff --git a/Standard/src/Canon/Combinators/ApplyIf.qs b/Standard/src/Canon/Combinators/ApplyIf.qs index 69dfc6c4c9b..8cb6d8b72b5 100644 --- a/Standard/src/Canon/Combinators/ApplyIf.qs +++ b/Standard/src/Canon/Combinators/ApplyIf.qs @@ -34,7 +34,7 @@ namespace Microsoft.Quantum.Canon { /// ```Q# /// let bitstring = [true, false, true]; /// using (register = Qubit(3)) { - /// ApplyToEach(ApplyIf(X, _, _), Zip(bitstring, register)); + /// ApplyToEach(ApplyIf(X, _, _), Zipped(bitstring, register)); /// // register should now be in the state |101⟩. /// ... /// } @@ -77,7 +77,7 @@ namespace Microsoft.Quantum.Canon { /// ```Q# /// let bitstring = [true, false, true]; /// using (register = Qubit(3)) { - /// ApplyToEach(ApplyIf(X, _, _), Zip(bitstring, register)); + /// ApplyToEach(ApplyIf(X, _, _), Zipped(bitstring, register)); /// // register should now be in the state |101⟩. /// ... /// } @@ -120,7 +120,7 @@ namespace Microsoft.Quantum.Canon { /// ```Q# /// let bitstring = [true, false, true]; /// using (register = Qubit(3)) { - /// ApplyToEach(ApplyIf(X, _, _), Zip(bitstring, register)); + /// ApplyToEach(ApplyIf(X, _, _), Zipped(bitstring, register)); /// // register should now be in the state |101⟩. /// ... /// } @@ -164,7 +164,7 @@ namespace Microsoft.Quantum.Canon { /// ```Q# /// let bitstring = [true, false, true]; /// using (register = Qubit(3)) { - /// ApplyToEach(ApplyIf(X, _, _), Zip(bitstring, register)); + /// ApplyToEach(ApplyIf(X, _, _), Zipped(bitstring, register)); /// // register should now be in the state |101⟩. /// ... /// } diff --git a/Standard/src/Canon/Combinators/ApplyRepeatedOver.qs b/Standard/src/Canon/Combinators/ApplyRepeatedOver.qs index 7db8042d35e..26cdd7c7b2b 100644 --- a/Standard/src/Canon/Combinators/ApplyRepeatedOver.qs +++ b/Standard/src/Canon/Combinators/ApplyRepeatedOver.qs @@ -35,7 +35,7 @@ namespace Microsoft.Quantum.Canon { if (Length(listOfOps) != Length(targets)) { fail "The number of ops and number of targets do not match!"; } - for ((op, targetIndices) in Zip(listOfOps, targets)) { + for ((op, targetIndices) in Zipped(listOfOps, targets)) { if (Length(targetIndices) > Length(register)) { fail "There are too many targets!"; } @@ -69,7 +69,7 @@ namespace Microsoft.Quantum.Canon { if (Length(listOfOps) != Length(targets)) { fail "The number of ops and number of targets do not match!"; } - for ((op, targetIndices) in Zip(listOfOps, targets)) { + for ((op, targetIndices) in Zipped(listOfOps, targets)) { if (Length(targetIndices) > Length(register)) { fail "There are too many targets!"; } @@ -103,7 +103,7 @@ namespace Microsoft.Quantum.Canon { if (Length(listOfOps) != Length(targets)) { fail "The number of ops and number of targets do not match!"; } - for ((op, targetIndices) in Zip(listOfOps, targets)) { + for ((op, targetIndices) in Zipped(listOfOps, targets)) { if (Length(targetIndices) > Length(register)) { fail "There are too many targets!"; } @@ -137,7 +137,7 @@ namespace Microsoft.Quantum.Canon { if (Length(listOfOps) != Length(targets)) { fail "The number of ops and number of targets do not match!"; } - for ((op, targetIndices) in Zip(listOfOps, targets)) { + for ((op, targetIndices) in Zipped(listOfOps, targets)) { if (Length(targetIndices) > Length(register)) { fail "There are too many targets!"; } diff --git a/Standard/src/Canon/Combinators/ApplyToArray.qs b/Standard/src/Canon/Combinators/ApplyToArray.qs new file mode 100644 index 00000000000..1d364e82a13 --- /dev/null +++ b/Standard/src/Canon/Combinators/ApplyToArray.qs @@ -0,0 +1,434 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace Microsoft.Quantum.Canon { + open Microsoft.Quantum.Arrays; + + /// # Summary + /// Applies an operation to the first element of an array. + /// + /// # Description + /// Given an operation `op` and an array of targets `targets`, + /// applies `op(Head(targets))`. + /// + /// # Input + /// ## op + /// An operation to be applied. + /// ## target + /// An array of targets, of which the first will be applied to `op`. + /// + /// # Type Parameters + /// ## 'T + /// The input type of the operation to be applied. + /// + /// # Example + /// The following Q# snippets are equivalent: + /// ```Q# + /// ApplyToHead(H, register); + /// H(Head(register)); + /// ``` + /// + /// # See Also + /// - Microsoft.Quantum.Canon.ApplyToHeadA + /// - Microsoft.Quantum.Canon.ApplyToHeadC + /// - Microsoft.Quantum.Canon.ApplyToHeadCA + operation ApplyToHead<'T>(op : ('T => Unit), targets : 'T[]) : Unit { + op(Head(targets)); + } + + /// # Summary + /// Applies an operation to the first element of an array. + /// + /// # Description + /// Given an operation `op` and an array of targets `targets`, + /// applies `op(Head(targets))`. + /// + /// # Input + /// ## op + /// An operation to be applied. + /// ## target + /// An array of targets, of which the first will be applied to `op`. + /// + /// # Type Parameters + /// ## 'T + /// The input type of the operation to be applied. + /// + /// # See Also + /// - Microsoft.Quantum.Canon.ApplyToHead + /// - Microsoft.Quantum.Canon.ApplyToHeadC + /// - Microsoft.Quantum.Canon.ApplyToHeadCA + operation ApplyToHeadA<'T>(op : ('T => Unit is Adj), targets : 'T[]) : Unit is Adj { + op(Head(targets)); + } + + /// # Summary + /// Applies an operation to the first element of an array. + /// + /// # Description + /// Given an operation `op` and an array of targets `targets`, + /// applies `op(Head(targets))`. + /// + /// # Input + /// ## op + /// An operation to be applied. + /// ## target + /// An array of targets, of which the first will be applied to `op`. + /// + /// # Type Parameters + /// ## 'T + /// The input type of the operation to be applied. + /// + /// # See Also + /// - Microsoft.Quantum.Canon.ApplyToHead + /// - Microsoft.Quantum.Canon.ApplyToHeadA + /// - Microsoft.Quantum.Canon.ApplyToHeadCA + operation ApplyToHeadC<'T>(op : ('T => Unit is Ctl), targets : 'T[]) : Unit is Ctl { + op(Head(targets)); + } + + /// # Summary + /// Applies an operation to the first element of an array. + /// + /// # Description + /// Given an operation `op` and an array of targets `targets`, + /// applies `op(Head(targets))`. + /// + /// # Input + /// ## op + /// An operation to be applied. + /// ## target + /// An array of targets, of which the first will be applied to `op`. + /// + /// # Type Parameters + /// ## 'T + /// The input type of the operation to be applied. + /// + /// # See Also + /// - Microsoft.Quantum.Canon.ApplyToHead + /// - Microsoft.Quantum.Canon.ApplyToHeadA + /// - Microsoft.Quantum.Canon.ApplyToHeadC + operation ApplyToHeadCA<'T>(op : ('T => Unit is Adj+Ctl), targets : 'T[]) : Unit is Adj+Ctl { + op(Head(targets)); + } + + /// # Summary + /// Applies an operation to all but the first element of an array. + /// + /// # Description + /// Given an operation `op` and an array of targets `targets`, + /// applies `op(Rest(targets))`. + /// + /// # Input + /// ## op + /// An operation to be applied. + /// ## target + /// An array of targets, of which all but the first will be applied to `op`. + /// + /// # Type Parameters + /// ## 'T + /// The input type of the operation to be applied. + /// + /// # Example + /// The following Q# snippets are equivalent: + /// ```Q# + /// ApplyToRest(ApplyCNOTChain, register); + /// ApplyCNOTChain(Rest(register)); + /// ``` + /// + /// # See Also + /// - Microsoft.Quantum.Canon.ApplyToRestA + /// - Microsoft.Quantum.Canon.ApplyToRestC + /// - Microsoft.Quantum.Canon.ApplyToRestCA + operation ApplyToRest<'T>(op : ('T[] => Unit), targets : 'T[]) : Unit { + op(Rest(targets)); + } + + /// # Summary + /// Applies an operation to all but the first element of an array. + /// + /// # Description + /// Given an operation `op` and an array of targets `targets`, + /// applies `op(Rest(targets))`. + /// + /// # Input + /// ## op + /// An operation to be applied. + /// ## target + /// An array of targets, of which all but the first will be applied to `op`. + /// + /// # Type Parameters + /// ## 'T + /// The input type of the operation to be applied. + /// + /// # See Also + /// - Microsoft.Quantum.Canon.ApplyToRest + /// - Microsoft.Quantum.Canon.ApplyToRestC + /// - Microsoft.Quantum.Canon.ApplyToRestCA + operation ApplyToRestA<'T>(op : ('T[] => Unit is Adj), targets : 'T[]) : Unit is Adj { + op(Rest(targets)); + } + + /// # Summary + /// Applies an operation to all but the first element of an array. + /// + /// # Description + /// Given an operation `op` and an array of targets `targets`, + /// applies `op(Rest(targets))`. + /// + /// # Input + /// ## op + /// An operation to be applied. + /// ## target + /// An array of targets, of which all but the first will be applied to `op`. + /// + /// # Type Parameters + /// ## 'T + /// The input type of the operation to be applied. + /// + /// # See Also + /// - Microsoft.Quantum.Canon.ApplyToRest + /// - Microsoft.Quantum.Canon.ApplyToRestA + /// - Microsoft.Quantum.Canon.ApplyToRestCA + operation ApplyToRestC<'T>(op : ('T[] => Unit is Ctl), targets : 'T[]) : Unit is Ctl { + op(Rest(targets)); + } + + /// # Summary + /// Applies an operation to all but the first element of an array. + /// + /// # Description + /// Given an operation `op` and an array of targets `targets`, + /// applies `op(Rest(targets))`. + /// + /// # Input + /// ## op + /// An operation to be applied. + /// ## target + /// An array of targets, of which all but the first will be applied to `op`. + /// + /// # Type Parameters + /// ## 'T + /// The input type of the operation to be applied. + /// + /// # See Also + /// - Microsoft.Quantum.Canon.ApplyToRest + /// - Microsoft.Quantum.Canon.ApplyToRestA + /// - Microsoft.Quantum.Canon.ApplyToRestC + operation ApplyToRestCA<'T>(op : ('T[] => Unit is Adj+Ctl), targets : 'T[]) : Unit is Adj+Ctl { + op(Rest(targets)); + } + + /// # Summary + /// Applies an operation to the last element of an array. + /// + /// # Description + /// Given an operation `op` and an array of targets `targets`, + /// applies `op(Tail(targets))`. + /// + /// # Input + /// ## op + /// An operation to be applied. + /// ## target + /// An array of targets, of which the last will be applied to `op`. + /// + /// # Type Parameters + /// ## 'T + /// The input type of the operation to be applied. + /// + /// # Example + /// The following Q# snippets are equivalent: + /// ```Q# + /// ApplyToTail(H, register); + /// H(Tail(register)); + /// ``` + /// + /// # See Also + /// - Microsoft.Quantum.Canon.ApplyToTailA + /// - Microsoft.Quantum.Canon.ApplyToTailC + /// - Microsoft.Quantum.Canon.ApplyToTailCA + operation ApplyToTail<'T>(op : ('T => Unit), targets : 'T[]) : Unit { + op(Tail(targets)); + } + + /// # Summary + /// Applies an operation to the last element of an array. + /// + /// # Description + /// Given an operation `op` and an array of targets `targets`, + /// applies `op(Tail(targets))`. + /// + /// # Input + /// ## op + /// An operation to be applied. + /// ## target + /// An array of targets, of which the last will be applied to `op`. + /// + /// # Type Parameters + /// ## 'T + /// The input type of the operation to be applied. + /// + /// # See Also + /// - Microsoft.Quantum.Canon.ApplyToTail + /// - Microsoft.Quantum.Canon.ApplyToTailC + /// - Microsoft.Quantum.Canon.ApplyToTailCA + operation ApplyToTailA<'T>(op : ('T => Unit is Adj), targets : 'T[]) : Unit is Adj { + op(Tail(targets)); + } + + /// # Summary + /// Applies an operation to the last element of an array. + /// + /// # Description + /// Given an operation `op` and an array of targets `targets`, + /// applies `op(Tail(targets))`. + /// + /// # Input + /// ## op + /// An operation to be applied. + /// ## target + /// An array of targets, of which the last will be applied to `op`. + /// + /// # Type Parameters + /// ## 'T + /// The input type of the operation to be applied. + /// + /// # See Also + /// - Microsoft.Quantum.Canon.ApplyToTail + /// - Microsoft.Quantum.Canon.ApplyToTailA + /// - Microsoft.Quantum.Canon.ApplyToTailCA + operation ApplyToTailC<'T>(op : ('T => Unit is Ctl), targets : 'T[]) : Unit is Ctl { + op(Tail(targets)); + } + + /// # Summary + /// Applies an operation to the last element of an array. + /// + /// # Description + /// Given an operation `op` and an array of targets `targets`, + /// applies `op(Tail(targets))`. + /// + /// # Input + /// ## op + /// An operation to be applied. + /// ## target + /// An array of targets, of which the last will be applied to `op`. + /// + /// # Type Parameters + /// ## 'T + /// The input type of the operation to be applied. + /// + /// # See Also + /// - Microsoft.Quantum.Canon.ApplyToTail + /// - Microsoft.Quantum.Canon.ApplyToTailA + /// - Microsoft.Quantum.Canon.ApplyToTailC + operation ApplyToTailCA<'T>(op : ('T => Unit is Adj+Ctl), targets : 'T[]) : Unit is Adj+Ctl { + op(Tail(targets)); + } + + /// # Summary + /// Applies an operation to all but the last element of an array. + /// + /// # Description + /// Given an operation `op` and an array of targets `targets`, + /// applies `op(Most(targets))`. + /// + /// # Input + /// ## op + /// An operation to be applied. + /// ## target + /// An array of targets, of which all but the last will be applied to `op`. + /// + /// # Type Parameters + /// ## 'T + /// The input type of the operation to be applied. + /// + /// # Example + /// The following Q# snippets are equivalent: + /// ```Q# + /// ApplyToMost(ApplyCNOTChain, register); + /// ApplyCNOTChain(Most(register)); + /// ``` + /// + /// # See Also + /// - Microsoft.Quantum.Canon.ApplyToMostA + /// - Microsoft.Quantum.Canon.ApplyToMostC + /// - Microsoft.Quantum.Canon.ApplyToMostCA + operation ApplyToMost<'T>(op : ('T[] => Unit), targets : 'T[]) : Unit { + op(Most(targets)); + } + + /// # Summary + /// Applies an operation to all but the last element of an array. + /// + /// # Description + /// Given an operation `op` and an array of targets `targets`, + /// applies `op(Most(targets))`. + /// + /// # Input + /// ## op + /// An operation to be applied. + /// ## target + /// An array of targets, of which all but the last will be applied to `op`. + /// + /// # Type Parameters + /// ## 'T + /// The input type of the operation to be applied. + /// + /// # See Also + /// - Microsoft.Quantum.Canon.ApplyToMost + /// - Microsoft.Quantum.Canon.ApplyToMostC + /// - Microsoft.Quantum.Canon.ApplyToMostCA + operation ApplyToMostA<'T>(op : ('T[] => Unit is Adj), targets : 'T[]) : Unit is Adj { + op(Most(targets)); + } + + /// # Summary + /// Applies an operation to all but the last element of an array. + /// + /// # Description + /// Given an operation `op` and an array of targets `targets`, + /// applies `op(Most(targets))`. + /// + /// # Input + /// ## op + /// An operation to be applied. + /// ## target + /// An array of targets, of which all but the last will be applied to `op`. + /// + /// # Type Parameters + /// ## 'T + /// The input type of the operation to be applied. + /// + /// # See Also + /// - Microsoft.Quantum.Canon.ApplyToMost + /// - Microsoft.Quantum.Canon.ApplyToMostA + /// - Microsoft.Quantum.Canon.ApplyToMostCA + operation ApplyToMostC<'T>(op : ('T[] => Unit is Ctl), targets : 'T[]) : Unit is Ctl { + op(Most(targets)); + } + + /// # Summary + /// Applies an operation to all but the last element of an array. + /// + /// # Description + /// Given an operation `op` and an array of targets `targets`, + /// applies `op(Most(targets))`. + /// + /// # Input + /// ## op + /// An operation to be applied. + /// ## target + /// An array of targets, of which all but the last will be applied to `op`. + /// + /// # Type Parameters + /// ## 'T + /// The input type of the operation to be applied. + /// + /// # See Also + /// - Microsoft.Quantum.Canon.ApplyToMost + /// - Microsoft.Quantum.Canon.ApplyToMostA + /// - Microsoft.Quantum.Canon.ApplyToMostC + operation ApplyToMostCA<'T>(op : ('T[] => Unit is Adj+Ctl), targets : 'T[]) : Unit is Adj+Ctl { + op(Most(targets)); + } +} diff --git a/Standard/src/Canon/Parity.qs b/Standard/src/Canon/Parity.qs index c0f0ced33b6..74e32a9b46f 100644 --- a/Standard/src/Canon/Parity.qs +++ b/Standard/src/Canon/Parity.qs @@ -23,7 +23,7 @@ namespace Microsoft.Quantum.Canon { /// ## qubits /// Array of qubits whose parity is to be computed and stored. operation ApplyCNOTChain(qubits : Qubit[]) : Unit is Adj + Ctl { - ApplyToEachCA(CNOT, Zip(Most(qubits), Rest(qubits))); + ApplyToEachCA(CNOT, Zipped(Most(qubits), Rest(qubits))); } /// # Summary diff --git a/Standard/src/Characterization/Distinguishability.qs b/Standard/src/Characterization/Distinguishability.qs index 6387314e836..3c7b733cf00 100644 --- a/Standard/src/Characterization/Distinguishability.qs +++ b/Standard/src/Characterization/Distinguishability.qs @@ -206,7 +206,7 @@ namespace Microsoft.Quantum.Characterization { } apply { preparation1(target1); preparation2(target2); - ApplyToEachCA(Controlled SWAP([control], _), Zip(target1, target2)); + ApplyToEachCA(Controlled SWAP([control], _), Zipped(target1, target2)); } } diff --git a/Standard/src/Diagnostics/Facts.qs b/Standard/src/Diagnostics/Facts.qs index eaa4461c5df..f947a6771e8 100644 --- a/Standard/src/Diagnostics/Facts.qs +++ b/Standard/src/Diagnostics/Facts.qs @@ -207,7 +207,7 @@ namespace Microsoft.Quantum.Diagnostics { FormattedFailure(actual, expected, message); } - Ignore(Mapped(EqualityFactB(_, _, message), Zip(actual, expected))); + Ignore(Mapped(EqualityFactB(_, _, message), Zipped(actual, expected))); } /// # Summary @@ -229,7 +229,7 @@ namespace Microsoft.Quantum.Diagnostics { FormattedFailure(actual, expected, message); } - Ignore(Mapped(EqualityFactI(_, _, message), Zip(actual, expected))); + Ignore(Mapped(EqualityFactI(_, _, message), Zipped(actual, expected))); } } diff --git a/Standard/src/Logical/Comparisons.qs b/Standard/src/Logical/Comparisons.qs new file mode 100644 index 00000000000..d0e4a153485 --- /dev/null +++ b/Standard/src/Logical/Comparisons.qs @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace Microsoft.Quantum.Logical { + open Microsoft.Quantum.Arrays; + open Microsoft.Quantum.Intrinsic; + open Microsoft.Quantum.Canon; + + /// # Summary + /// Given a comparison function, returns a new function that + /// lexographically compares two arrays. + /// + /// # Type Parameters + /// ## 'T + /// The type of the elements of the arrays being compared. + /// + /// # Input + /// ## elementComparison + /// A function that compares two elements `x` and `y` and returns if + /// `x` is less than or equal to `y`. + /// + /// # Output + /// A function that compares two arrays `xs` and `ys` and returns if + /// `xs` occurs before or equal to `ys` in lexographical ordering. + /// + /// # Remarks + /// The lexographic comparison between two arrays `xs` and `ys` is defined + /// by the following procedure. We say that two elements `x` and `y` + /// are equivalent if `elementComparison(x, y)` and `elementComparison(y, x)` + /// are both true. + /// + /// - Both arrays are compared element-by-element until the first pair of + /// elements that are not equivalent. The array containing the element + /// that occurs first according to `elementComparison` is said to occur + /// first in lexographical ordering. + /// - If no inequivalent elements are found, and one array is longer than + /// the other, the shorter array is said to occur first. + /// + /// # Examples + /// ```Q# + /// let arrayComparison = LexographicComparison(LessThanOrEqualD); + /// let data = [ + /// [1.1, 2.2, 3.3], + /// [1.1, 2.2], + /// [0.2, 2.2], + /// [1.1, 2.7] + /// ]; + /// let sorted = Sorted(arrayComparison, data); + /// // sorted: + /// // [ + /// // [0.2, 2.2], + /// // [1.1, 2.2], + /// // [1.1, 2.2, 3.3], + /// // [1.1, 2.7] + /// // ]; + /// ``` + /// + /// # See Also + /// - Microsoft.Quantum.Arrays.Sorted + function LexographicComparison<'T>(elementComparison : (('T, 'T) -> Bool)) : (('T[], 'T[]) -> Bool) { + return LessThanLexographic(elementComparison, _, _); + } + + /// # Summary + /// Used to implement `LexographicComparison`. + internal function LessThanLexographic<'T>(comparison : (('T, 'T) -> Bool), left : 'T[], right : 'T[]) : Bool { + for ((l, r) in Zipped(left, right)) { + let lessThanOrEqual = comparison(l, r); + let greaterThanOrEqual = comparison(r, l); + let equal = lessThanOrEqual and greaterThanOrEqual; + if (lessThanOrEqual and not equal) { + return true; + } elif (greaterThanOrEqual and not equal) { + return false; + } + } + + // At this point, all items in the common prefix of both arrays + // are equal to each other under comparison (l ≀ r and r ≀ l). + // Thus, if left is shorter than or equal to right, then left occurs + // at or before right in lexographical ordering. + return Length(left) <= Length(right); + } + +} diff --git a/Standard/src/Preparation/Reference.qs b/Standard/src/Preparation/Reference.qs index 9203f0439ec..74564a6c308 100644 --- a/Standard/src/Preparation/Reference.qs +++ b/Standard/src/Preparation/Reference.qs @@ -22,7 +22,7 @@ namespace Microsoft.Quantum.Preparation { fail $"Left and right registers must be the same length."; } - for ((leftQubit, rightQubit) in Zip(left, right)) { + for ((leftQubit, rightQubit) in Zipped(left, right)) { H(leftQubit); Controlled X([leftQubit], rightQubit); } diff --git a/Standard/src/Synthesis/DecompositionBased.qs b/Standard/src/Synthesis/DecompositionBased.qs index 3ad114f4af5..26a55f056ed 100644 --- a/Standard/src/Synthesis/DecompositionBased.qs +++ b/Standard/src/Synthesis/DecompositionBased.qs @@ -279,7 +279,7 @@ namespace Microsoft.Quantum.Synthesis { let register = qubits!; for ((func, target) in TruthTablesFromPermutation(perm, variableOrder)) { - ApplyXControlledOnTruthTable(func, Exclude([target], register), register[target]); + ApplyXControlledOnTruthTable(func, Excluding([target], register), register[target]); } } } diff --git a/Standard/src/Synthesis/Transposition.qs b/Standard/src/Synthesis/Transposition.qs index 9f7c1a81183..08c93b6f8ec 100644 --- a/Standard/src/Synthesis/Transposition.qs +++ b/Standard/src/Synthesis/Transposition.qs @@ -54,11 +54,11 @@ namespace Microsoft.Quantum.Synthesis { within { for (target in Most(diff)) { - (BitControlledX(bbits[...target - 1] + abits[target + 1...]))(Exclude([target], qs), qs[target]); + (BitControlledX(bbits[...target - 1] + abits[target + 1...]))(Excluding([target], qs), qs[target]); } } apply { let target = Tail(diff); - (BitControlledX(bbits[...target - 1] + abits[target + 1...]))(Exclude([target], qs), qs[target]); + (BitControlledX(bbits[...target - 1] + abits[target + 1...]))(Excluding([target], qs), qs[target]); } } } diff --git a/Standard/tests/ArrayTests.qs b/Standard/tests/ArrayTests.qs index 5dbadf4d724..3aa1b38be19 100644 --- a/Standard/tests/ArrayTests.qs +++ b/Standard/tests/ArrayTests.qs @@ -1,18 +1,19 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace Microsoft.Quantum.Tests { - open Microsoft.Quantum.Logical; - open Microsoft.Quantum.Diagnostics; + open Microsoft.Quantum.Arrays; open Microsoft.Quantum.Canon; + open Microsoft.Quantum.Diagnostics; open Microsoft.Quantum.Intrinsic; - open Microsoft.Quantum.Arrays; + open Microsoft.Quantum.Logical; + open Microsoft.Quantum.Math; @Test("QuantumSimulator") - function ZipTest() : Unit { + function TestZipped() : Unit { let left = [1, 2, 101]; let right = [PauliY, PauliI]; - let zipped = Zip(left, right); + let zipped = Zipped(left, right); let (leftActual1, rightActual1) = zipped[0]; if (leftActual1 != 1 or rightActual1 != PauliY) { @@ -26,9 +27,19 @@ namespace Microsoft.Quantum.Tests { } } + @Test("QuantumSimulator") + function TestUnzipped() : Unit { + let first = [6, 5, 5, 3, 2, 1]; + let second = [true, false, false, false, true, false]; + + let (first2, second2) = Unzipped(Zipped(first, second)); + AllEqualityFactI(first2, first, "Unexpected array of integers"); + AllEqualityFactB(second2, second, "Unexpected array of Booleans"); + } + @Test("QuantumSimulator") - function LookupTest () : Unit { + function TestLookup() : Unit { let array = [1, 12, 71, 103]; let fn = LookupFunction(array); @@ -41,21 +52,21 @@ namespace Microsoft.Quantum.Tests { } internal function AllEqualI(expected : Int[], actual : Int[]) : Bool { - return All(EqualI, Zip(expected, actual)); + return All(EqualI, Zipped(expected, actual)); } @Test("QuantumSimulator") - function ChunksTest() : Unit { + function TestChunks() : Unit { let data = [10, 11, 12, 13, 14, 15]; // 2 × 3 case. - Fact(All(AllEqualI, Zip( + Fact(All(AllEqualI, Zipped( [[10, 11], [12, 13], [14, 15]], Chunks(2, data) )), "Wrong chunks in 2x3 case."); // Case with some leftovers. - Fact(All(AllEqualI, Zip( + Fact(All(AllEqualI, Zipped( [[10, 11, 12, 13], [14, 15]], Chunks(4, data) )), "Wrong chunks in case with leftover elements."); @@ -65,13 +76,15 @@ namespace Microsoft.Quantum.Tests { return x * x; } - - function ConstantArrayTest () : Unit { - + @Test("QuantumSimulator") + function ConstantArrayOfDoublesIsCorrect() : Unit { let dblArray = ConstantArray(71, 2.17); EqualityFactI(Length(dblArray), 71, $"ConstantArray(Int, Double) had the wrong length."); let ignore = Mapped(NearEqualityFactD(_, 2.17), dblArray); + } + @Test("QuantumSimulator") + function ConstantArrayOfFunctionsIsCorrect() : Unit { // Stress test by making an array of Int -> Int. let fnArray = ConstantArray(7, Squared); EqualityFactI(Length(fnArray), 7, $"ConstantArray(Int, Int -> Int) had the wrong length."); @@ -80,36 +93,40 @@ namespace Microsoft.Quantum.Tests { function SubarrayTest () : Unit { - let array0 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let subarrayOdd = Subarray([1, 3, 5, 7, 9], array0); let subarrayEven = Subarray([0, 2, 4, 6, 8, 10], array0); Fact(All(IsEven, subarrayEven), $"the even elements of [1..10] were not correctly sliced."); Fact(not Any(IsEven, subarrayOdd), $"the odd elements of [1..10] were not correctly sliced."); let array1 = [10, 11, 12, 13]; - Ignore(Mapped(EqualityFactI(_, _, $"Subarray failed: subpermutation case."), Zip([12, 11], Subarray([2, 1], array1)))); + Ignore(Mapped(EqualityFactI(_, _, $"Subarray failed: subpermutation case."), Zipped([12, 11], Subarray([2, 1], array1)))); } - - function FilterTest () : Unit { - + @Test("QuantumSimulator") + function FilteredIsEvenHasNoOdds() : Unit { let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let evenArray = Filtered(IsEven, array); - EqualityFactB(All(IsEven, evenArray), true, $"the even elements of [1..10] were not correctly filtered."); + Fact(All(IsEven, evenArray), $"the even elements of [1..10] were not correctly filtered."); + } + + @Test("QuantumSimulator") + function CountOfIsEvenIsCorrect() : Unit { + let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + let countEvens = Count(IsEven, array); + EqualityFactI(countEvens, 5, $"the even elements of [1..10] were not correctly counted."); } function ReverseTest () : Unit { let array = [1, 2, 3]; - Ignore(Mapped(EqualityFactI(_, _, $"Reversed failed."), Zip([3, 2, 1], Reversed(array)))); + Ignore(Mapped(EqualityFactI(_, _, $"Reversed failed."), Zipped([3, 2, 1], Reversed(array)))); } - function ExcludeTest () : Unit { - + function ExcludingTest () : Unit { let array = [10, 11, 12, 13, 14, 15]; - Ignore(Mapped(EqualityFactI(_, _, $"Exclude failed."), Zip([10, 11, 13, 14], Exclude([2, 5], array)))); + Ignore(Mapped(EqualityFactI(_, _, $"Excluding failed."), Zipped([10, 11, 13, 14], Excluding([2, 5], array)))); } @@ -120,7 +137,7 @@ namespace Microsoft.Quantum.Tests { for (idxTest in IndexRange(arrayTestCase)) { let (nElementsTotal, defaultElement, inputArray, outputArray) = arrayTestCase[idxTest]; let paddedArray = Padded(nElementsTotal, defaultElement, inputArray); - Ignore(Mapped(EqualityFactI(_, _, $"Padded failed."), Zip(outputArray, paddedArray))); + Ignore(Mapped(EqualityFactI(_, _, $"Padded failed."), Zipped(outputArray, paddedArray))); } } @@ -129,7 +146,7 @@ namespace Microsoft.Quantum.Tests { let expected = [(0, 37), (1, 12)]; let actual = Enumerated(example); - for ((actualElement, expectedElement) in Zip(actual, expected)) { + for ((actualElement, expectedElement) in Zipped(actual, expected)) { EqualityFactI(Fst(actualElement), Fst(expectedElement), "Indices did not match."); EqualityFactI(Snd(actualElement), Snd(expectedElement), "Elements did not match."); } @@ -140,9 +157,9 @@ namespace Microsoft.Quantum.Tests { let expected = [[0, 1, 2, 3], [23, 24, 25, 26, 27, 28, 29], [-5, -4, -3, -2]]; let actual = Mapped(SequenceI, example); - for ((exp, act) in Zip(expected, actual)) { + for ((exp, act) in Zipped(expected, actual)) { EqualityFactI(Length(exp), Length(act), "Lengths of arrays did not match."); - for ((i, j) in Zip(exp, act)) { + for ((i, j) in Zipped(exp, act)) { EqualityFactI(i, j, "Elements did not match."); } } @@ -153,9 +170,9 @@ namespace Microsoft.Quantum.Tests { let expected = [[0L, 1L, 2L, 3L], [23L, 24L, 25L, 26L, 27L, 28L, 29L], [-5L, -4L, -3L, -2L]]; let actual = Mapped(SequenceL, example); - for ((exp, act) in Zip(expected, actual)) { + for ((exp, act) in Zipped(expected, actual)) { EqualityFactI(Length(exp), Length(act), "Lengths of arrays did not match."); - for ((i, j) in Zip(exp, act)) { + for ((i, j) in Zipped(exp, act)) { EqualityFactL(i, j, "Elements did not match."); } } @@ -166,9 +183,9 @@ namespace Microsoft.Quantum.Tests { let expected = [[0, 1, 2, 3], [0, 1, 2, 3, 4, 5], [0]]; let actual = Mapped(SequenceI(0, _), example); - for ((exp, act) in Zip(expected, actual)) { + for ((exp, act) in Zipped(expected, actual)) { EqualityFactI(Length(exp), Length(act), "Lengths of arrays did not match."); - for ((i, j) in Zip(exp, act)) { + for ((i, j) in Zipped(exp, act)) { EqualityFactI(i, j, "Elements did not match."); } } @@ -188,7 +205,7 @@ namespace Microsoft.Quantum.Tests { let actual = _SwapOrderToPermuteArray(newOrder); EqualityFactI(Length(expected), Length(actual), "Number of swaps does not match"); - for ((exp, act) in Zip(expected, actual)) { + for ((exp, act) in Zipped(expected, actual)) { let (leftExp, rightExp) = exp; let (leftAct, rightAct) = act; @@ -205,7 +222,7 @@ namespace Microsoft.Quantum.Tests { let newArray = Swapped(leftIndex, rightIndex, example); EqualityFactI(Length(expected), Length(newArray), "Swapped array is a different size than original"); - for ((exp, act) in Zip(expected, newArray)) { + for ((exp, act) in Zipped(expected, newArray)) { EqualityFactI(exp, act, "Elements did not match"); } } @@ -216,8 +233,8 @@ namespace Microsoft.Quantum.Tests { let actual = TupleArrayAsNestedArray(example); EqualityFactI(Length(expected), Length(actual), "Arrays are of different sizes"); - for ((exp, act) in Zip(expected, actual)) { - for ((elementExp, elementAct) in Zip(exp, act)) { + for ((exp, act) in Zipped(expected, actual)) { + for ((elementExp, elementAct) in Zipped(exp, act)) { EqualityFactI(elementExp, elementAct, "Elements did not match"); } } @@ -237,6 +254,109 @@ namespace Microsoft.Quantum.Tests { let differentElements = EqualA(EqualR, [One, Zero], [One, One]); Fact(not differentElements, "Arrays with different elements were reported as equal"); } -} + @Test("QuantumSimulator") + operation TestInterleaved() : Unit { + AllEqualityFactI(Interleaved([1, 2, 3], [-1, -2, -3]), [1, -1, 2, -2, 3, -3], "Interleaving failed"); + AllEqualityFactB(Interleaved(ConstantArray(3, false), ConstantArray(2, true)), [false, true, false, true, false], "Interleaving failed"); + } + + @Test("QuantumSimulator") + operation TestCumulativeFolded() : Unit { + AllEqualityFactI(CumulativeFolded(PlusI, 0, SequenceI(1, 5)), [1, 3, 6, 10, 15], "CumulativeFolded failed"); + } + @Test("QuantumSimulator") + operation TestTransposed() : Unit { + for ((actual, expected) in Zipped(Transposed([[1, 2, 3], [4, 5, 6]]), [[1, 4], [2, 5], [3, 6]])) { + AllEqualityFactI(actual, expected, "Transposed failed"); + } + } + + @Test("QuantumSimulator") + operation TestColumnAt() : Unit { + let matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; + AllEqualityFactI(ColumnAt(0, matrix), [1, 4, 7], "ColumnAt failed"); + AllEqualityFactI(ColumnAt(1, matrix), [2, 5, 8], "ColumnAt failed"); + AllEqualityFactI(ColumnAt(2, matrix), [3, 6, 9], "ColumnAt failed"); + } + + @Test("QuantumSimulator") + operation TestElementAt() : Unit { + let lucas = [2, 1, 3, 4, 7, 11, 18, 29, 47, 76]; + let prime = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]; + let fibonacci = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]; + let catalan = [1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862]; + let famous2 = Mapped(ElementAt(2, _), [lucas, prime, fibonacci, catalan]); + AllEqualityFactI(famous2, [3, 5, 1, 2], "ElementAt failed"); + } + + @Test("QuantumSimulator") + operation TestElementsAt() : Unit { + let lucas = [2, 1, 3, 4, 7, 11, 18, 29, 47, 76]; + let prime = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]; + let fibonacci = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]; + let catalan = [1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862]; + let famousOdd = Mapped(ElementsAt(0..2..9, _), [lucas, prime, fibonacci, catalan]); + for ((actual, expected) in Zipped(famousOdd, [[2, 3, 7, 18, 47], [2, 5, 11, 17, 23], [0, 1, 3, 8, 21], [1, 2, 14, 132, 1430]])) { + AllEqualityFactI(actual, expected, "ElementsAt failed"); + } + } + + @Test("QuantumSimulator") + operation TestDiagonal() : Unit { + AllEqualityFactI(Diagonal([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), [1, 5, 9], "Diagonal failed"); + AllEqualityFactI(Diagonal([[1, 2, 3], [4, 5, 6]]), [1, 5], "Diagonal failed"); + AllEqualityFactI(Diagonal([[1, 2], [4, 5], [7, 8]]), [1, 5], "Diagonal failed"); + } + + @Test("QuantumSimulator") + operation TestWindows() : Unit { + let EqualIntA = EqualA(EqualI, _, _); + let EqualIntAA = EqualA(EqualIntA, _, _); + + Fact(EqualIntAA(Windows(-1, [1, 2, 3]), new Int[][0]), "unexpected windows"); + Fact(EqualIntAA(Windows(0, [1, 2, 3]), new Int[][0]), "unexpected windows"); + Fact(EqualIntAA(Windows(1, [1, 2, 3]), [[1], [2], [3]]), "unexpected windows"); + Fact(EqualIntAA(Windows(2, [1, 2, 3]), [[1, 2], [2, 3]]), "unexpected windows"); + Fact(EqualIntAA(Windows(3, [1, 2, 3]), [[1, 2, 3]]), "unexpected windows"); + Fact(EqualIntAA(Windows(4, [1, 2, 3]), new Int[][0]), "unexpected windows"); + } + + @Test("QuantumSimulator") + operation TestPrefixes() : Unit { + let array = [0, 1, 1, 2, 3, 5]; + let prefixes = Prefixes(array); + + EqualityFactI(Length(prefixes), Length(array), "unexpected length for prefixes"); + AllEqualityFactI(prefixes[0], [0], "unexpected prefix"); + AllEqualityFactI(prefixes[1], [0, 1], "unexpected prefix"); + AllEqualityFactI(prefixes[2], [0, 1, 1], "unexpected prefix"); + AllEqualityFactI(prefixes[3], [0, 1, 1, 2], "unexpected prefix"); + AllEqualityFactI(prefixes[4], [0, 1, 1, 2, 3], "unexpected prefix"); + AllEqualityFactI(prefixes[5], [0, 1, 1, 2, 3, 5], "unexpected prefix"); + } + + @Test("QuantumSimulator") + operation TestSuccessfulRectangularFact() : Unit { + RectangularArrayFact([[1, 2], [3, 4]], "Array is not rectangular"); + RectangularArrayFact([[1, 2, 3], [4, 5, 6]], "Array is not rectangular"); + } + + operation RectangularFactTestShouldFail() : Unit { + RectangularArrayFact([[1, 2], [3, 4, 5]], "Array is not rectangular"); + } + + @Test("QuantumSimulator") + operation TestSuccessfulSquareFact() : Unit { + SquareArrayFact([[1, 2], [3, 4]], "Array is not a square"); + } + + operation SquareFact1TestShouldFail() : Unit { + SquareArrayFact([[1, 2, 3], [4, 5, 6]], "Array is not a square"); + } + + operation SquareFact2TestShouldFail() : Unit { + SquareArrayFact([[1, 2], [3, 4, 5]], "Array is not a square"); + } +} diff --git a/Standard/tests/Arrays/SortedTests.qs b/Standard/tests/Arrays/SortedTests.qs new file mode 100644 index 00000000000..a0dbc5fdd37 --- /dev/null +++ b/Standard/tests/Arrays/SortedTests.qs @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace Microsoft.Quantum.Arrays { + open Microsoft.Quantum.Random; + open Microsoft.Quantum.Diagnostics; + open Microsoft.Quantum.Logical; + + @Test("QuantumSimulator") + function IntsAreSorted() : Unit { + Fact(IsSorted(LessThanOrEqualI, [1, 10, 100]), "[1, 10, 100] was marked as unsorted."); + } + + @Test("QuantumSimulator") + function DoublesAreSorted() : Unit { + Fact(IsSorted(LessThanOrEqualD, [1.0, 10.1, 100.2]), "[1.0, 10.1, 100.2] was marked as unsorted."); + } + + @Test("QuantumSimulator") + function IntsAreNotSorted() : Unit { + Contradiction(IsSorted(LessThanOrEqualI, [100, 10, 3]), "[100, 10, 3] was marked as sorted."); + } + + @Test("QuantumSimulator") + function SortedIntsAreSorted() : Unit { + Fact(IsSorted(LessThanOrEqualI, + Sorted(LessThanOrEqualI, [100, 10, 3])), + "Sorted(<=, [100, 10, 3]) was marked as unsorted." + ); + } + + @Test("QuantumSimulator") + function SortedDoublesAreSorted() : Unit { + Fact(IsSorted(LessThanOrEqualD, + Sorted(LessThanOrEqualD, [100.0, 10.1, 3.14])), + "Sorted(<=, [100.0, 10.1, 3.14]) was marked as unsorted." + ); + } + + @Test("QuantumSimulator") + operation CheckRandomArraysAreSortedWhenSorted() : Unit { + let nItems = 100; + let nTrials = 10; + let maxItem = 1000; + for (_ in 0..nTrials - 1) { + let data = DrawMany((DiscreteUniformDistribution(0, maxItem))::Sample, nItems, ()); + Fact(IsSorted(LessThanOrEqualI, Sorted(LessThanOrEqualI, data)), $"{data} was not sorted after running Sorted."); + } + } + + @Test("QuantumSimulator") + function LexographicSortIsCorrect() : Unit { + let arrayComparison = LexographicComparison(LessThanOrEqualI); + let data = [ + [1, 2, 3], + [1, 2], + [0, 2], + [1, 3] + ]; + let sorted = Sorted(arrayComparison, data); + + AllEqualityFactI( + sorted[0], [0, 2], "0th item was not correct." + ); + AllEqualityFactI( + sorted[1], [1, 2], "1st item was not correct." + ); + AllEqualityFactI( + sorted[2], [1, 2, 3], "2nd item was not correct." + ); + AllEqualityFactI( + sorted[3], [1, 3], "3rd item was not correct." + ); + } + +} diff --git a/Standard/tests/Arrays/UniqueTests.qs b/Standard/tests/Arrays/UniqueTests.qs new file mode 100644 index 00000000000..4309359bcf8 --- /dev/null +++ b/Standard/tests/Arrays/UniqueTests.qs @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace Microsoft.Quantum.Arrays { + open Microsoft.Quantum.Diagnostics; + open Microsoft.Quantum.Logical; + + @Test("QuantumSimulator") + operation UniqueInts() : Unit { + AllEqualityFactI(Unique(EqualI, [0, 0, 1, 2, 2, 3, 4, 5, 5, 8, 42, 42, 39]), [0, 1, 2, 3, 4, 5, 8, 42, 39], "Data is not unique"); + AllEqualityFactI(Unique(EqualI, [0, 1, 1, 0, 0, 1, 1, 0]), [0, 1, 0, 1, 0], "Data is not unique"); + AllEqualityFactI(Unique(EqualI, Sorted(LessThanOrEqualI, [2, 2, 1, 1, 2, 2, 1, 1])), [1, 2], "Sorted data is not unique"); + } + + @Test("QuantumSimulator") + operation UniqueDoubles() : Unit { + let unique = Unique(EqualD, [1.1, 1.1, 2.2, 2.2, 2.2, 3.3, 0.5, 42.0]); + EqualityFactI(Length(unique), 5, "Unexpected length of unique data"); + Fact(unique[0] == 1.1, "Unexpected element in unique data"); + Fact(unique[1] == 2.2, "Unexpected element in unique data"); + Fact(unique[2] == 3.3, "Unexpected element in unique data"); + Fact(unique[3] == 0.5, "Unexpected element in unique data"); + Fact(unique[4] == 42.0, "Unexpected element in unique data"); + } +} diff --git a/Standard/tests/CombinatorTests.qs b/Standard/tests/CombinatorTests.qs index 9834abaec41..ad06f1803d7 100644 --- a/Standard/tests/CombinatorTests.qs +++ b/Standard/tests/CombinatorTests.qs @@ -134,14 +134,14 @@ namespace Microsoft.Quantum.Tests { operation CControlledActual (op : (Qubit => Unit), target : Qubit[]) : Unit { - ApplyToEach(CControlled(op), Zip([true, false, true], target)); + ApplyToEach(CControlled(op), Zipped([true, false, true], target)); } operation CControlledActualC (op : (Qubit => Unit is Ctl), target : Qubit[]) : Unit { body (...) { - ApplyToEachC(CControlledC(op), Zip([true, false, true], target)); + ApplyToEachC(CControlledC(op), Zipped([true, false, true], target)); } controlled distribute; @@ -151,7 +151,7 @@ namespace Microsoft.Quantum.Tests { operation CControlledActualA (op : (Qubit => Unit is Adj), target : Qubit[]) : Unit { body (...) { - ApplyToEachA(CControlledA(op), Zip([true, false, true], target)); + ApplyToEachA(CControlledA(op), Zipped([true, false, true], target)); } adjoint invert; @@ -161,7 +161,7 @@ namespace Microsoft.Quantum.Tests { operation CControlledActualCA (op : (Qubit => Unit is Adj + Ctl), target : Qubit[]) : Unit { body (...) { - ApplyToEachCA(CControlledCA(op), Zip([true, false, true], target)); + ApplyToEachCA(CControlledCA(op), Zipped([true, false, true], target)); } adjoint invert; diff --git a/Standard/tests/EnumerationTests.qs b/Standard/tests/EnumerationTests.qs index 48e23694f9d..5e9db499f26 100644 --- a/Standard/tests/EnumerationTests.qs +++ b/Standard/tests/EnumerationTests.qs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace Microsoft.Quantum.Tests { open Microsoft.Quantum.Math; @@ -59,6 +59,33 @@ namespace Microsoft.Quantum.Tests { EqualityFactI(Fold(Add, 0, squaredArray), 30, $"the sum of the squares of [1, 2, 3, 4] was not found to be 30."); } + @Test("QuantumSimulator") + function TestMappedOverNonEmptyRange() : Unit { + AllEqualityFactI(MappedOverRange(PlusI(_, 2), 1..5), [3, 4, 5, 6, 7], "MappedOverRange failed."); + } + + @Test("QuantumSimulator") + function TestMappedOverReversedRange() : Unit { + AllEqualityFactI(MappedOverRange(TimesI(_, 2), 4..-2..-4), [8, 4, 0, -4, -8], "MappedOverRange failed."); + } + + @Test("QuantumSimulator") + function TestMappedOverEmpty() : Unit { + AllEqualityFactI(MappedOverRange(TimesI(_, 2), 1..-1..2), new Int[0], "MappedOverRange failed."); + } + + @Test("QuantumSimulator") + function TestFlatMapped() : Unit { + let numbers = FlatMapped(SequenceI(1, _), SequenceI(1, 5)); + AllEqualityFactI(numbers, [1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5], "FlatMapped failed"); + } + + @Test("QuantumSimulator") + function TestFlattened() : Unit { + let numbers = Flattened(ConstantArray(3, SequenceI(1, 3))); + AllEqualityFactI(numbers, [1, 2, 3, 1, 2, 3, 1, 2, 3], "Flattened failed"); + } + function ExtremaTest () : Unit { let array = [-10, 10, 7, 0]; EqualityFactI(-10, Min(array), $"Min failed."); diff --git a/Standard/tests/Logical/ComparisonTests.qs b/Standard/tests/Logical/ComparisonTests.qs new file mode 100644 index 00000000000..9afd776c33d --- /dev/null +++ b/Standard/tests/Logical/ComparisonTests.qs @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +namespace Microsoft.Quantum.Tests { + open Microsoft.Quantum.Logical; + open Microsoft.Quantum.Diagnostics; + open Microsoft.Quantum.Math; + open Microsoft.Quantum.Arrays; + + function LexographicComparisonIsCorrect() : Unit { + let lexographicComparison = LexographicComparison(LessThanOrEqualD); + Fact( + lexographicComparison( + [1.1, 2.2], [1.1, 2.2, 3.3] + ), + "Shorter array should have occured first." + ); + Fact( + lexographicComparison( + [0.7, 2.2], [1.1, 2.2] + ), + "Array with smaller first element should have occured first." + ); + Fact( + lexographicComparison( + [1.1, 2.2], [1.1, 2.2] + ), + "Identical arrays should be marked as less than or equal." + ); + Contradiction( + lexographicComparison( + [1.1, 2.7], [1.1, 2.2, 3.3] + ), + "Array with larger second element should have occured second." + ); + } + +} diff --git a/Standard/tests/QubitizationTests.qs b/Standard/tests/QubitizationTests.qs index ef418797699..ff3f330e267 100644 --- a/Standard/tests/QubitizationTests.qs +++ b/Standard/tests/QubitizationTests.qs @@ -145,7 +145,7 @@ namespace Microsoft.Quantum.Tests { for (idxTest in IndexRange(testCases)) { let (expected, range) = testCases[idxTest]; let output = RangeAsIntArray(range); - Ignore(Mapped(EqualityFactI(_, _, "Padded failed."), Zip(output, expected))); + Ignore(Mapped(EqualityFactI(_, _, "Padded failed."), Zipped(output, expected))); } } From 9888bbb0721fbfb0579e6ded4bc90b1771f3523d Mon Sep 17 00:00:00 2001 From: Ryan Shaffer Date: Thu, 15 Oct 2020 16:01:29 -0400 Subject: [PATCH 05/15] Add PrivateAssets="All" to IQ# package reference (#351) --- Visualization/src/Visualization.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Visualization/src/Visualization.csproj b/Visualization/src/Visualization.csproj index cf3f41e5537..65f339d8b4a 100644 --- a/Visualization/src/Visualization.csproj +++ b/Visualization/src/Visualization.csproj @@ -34,7 +34,7 @@ - + From ab760b7ea20e7e08646886b55a9db1505e778a75 Mon Sep 17 00:00:00 2001 From: Ryan Shaffer Date: Fri, 16 Oct 2020 08:53:27 -0400 Subject: [PATCH 06/15] Add links to PyPI package descriptions (#352) --- Python/qsharp-chemistry/README.md | 6 ++++++ Python/qsharp/README.md | 8 +++++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/Python/qsharp-chemistry/README.md b/Python/qsharp-chemistry/README.md index 20b4829784a..02a19367ecc 100644 --- a/Python/qsharp-chemistry/README.md +++ b/Python/qsharp-chemistry/README.md @@ -6,6 +6,8 @@ For details on how to get started with Python and Q#, please see the [Getting St For details about the Quantum Chemistry Library, please see the [Introduction to the Quantum Chemistry Library article](https://docs.microsoft.com/quantum/user-guide/libraries/chemistry/) in our online documentation. +You can also try our [Quantum Computing Fundamentals](https://aka.ms/learnqc) learning path to get familiar with the basic concepts of quantum computing, build quantum programs, and identify the kind of problems that can be solved. + ## Installing with Anaconda ## If you use Anaconda or Miniconda, installing the `qsharp` package will automatically include all dependencies: @@ -36,3 +38,7 @@ python setup.py bdist_wheel By default, this will create a `qsharp-chemistry` wheel in `dist/` with the version number set to 0.0.0.1. To provide a more useful version number, set the `PYTHON_VERSION` environment variable before running `setup.py`. + +## Support and Q&A + +If you have questions about the Quantum Development Kit and the Q# language, or if you encounter issues while using any of the components of the kit, you can reach out to the quantum team and the community of users in [Stack Overflow](https://stackoverflow.com/questions/tagged/q%23) and in [Quantum Computing Stack Exchange](https://quantumcomputing.stackexchange.com/questions/tagged/q%23) tagging your questions with **q#**. diff --git a/Python/qsharp/README.md b/Python/qsharp/README.md index 599228d2ffc..fb521c9049a 100644 --- a/Python/qsharp/README.md +++ b/Python/qsharp/README.md @@ -4,6 +4,8 @@ The `qsharp` package for Python provides interoperability with the Quantum Devel For details on how to get started with Python and Q#, please see the [Getting Started with Python guide](https://docs.microsoft.com/quantum/install-guide/python). +You can also try our [Quantum Computing Fundamentals](https://aka.ms/learnqc) learning path to get familiar with the basic concepts of quantum computing, build quantum programs, and identify the kind of problems that can be solved. + ## Installing with Anaconda ## If you use Anaconda or Miniconda, installing the `qsharp` package will automatically include all dependencies: @@ -22,7 +24,7 @@ cd Python/qsharp python setup.py install ``` -## Building the `qsharp-chemistry` Package ## +## Building the `qsharp` Package ## The Python interoperability feature uses a standard `setuptools`-based packaging strategy. To build a platform-independent wheel, run the setup script with `bdist_wheel` instead: @@ -34,3 +36,7 @@ python setup.py bdist_wheel By default, this will create a `qsharp` wheel in `dist/` with the version number set to 0.0.0.1. To provide a more useful version number, set the `PYTHON_VERSION` environment variable before running `setup.py`. + +## Support and Q&A + +If you have questions about the Quantum Development Kit and the Q# language, or if you encounter issues while using any of the components of the kit, you can reach out to the quantum team and the community of users in [Stack Overflow](https://stackoverflow.com/questions/tagged/q%23) and in [Quantum Computing Stack Exchange](https://quantumcomputing.stackexchange.com/questions/tagged/q%23) tagging your questions with **q#**. From 481e363528dcc5d79fd73e6eb976ce9eb2054d6a Mon Sep 17 00:00:00 2001 From: Mathias Soeken Date: Sat, 17 Oct 2020 19:10:51 +0200 Subject: [PATCH 07/15] Fix #347. (#348) Co-authored-by: Mathias Soeken Co-authored-by: Chris Granade --- Standard/src/Canon/Utils/Multiplexer.qs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Standard/src/Canon/Utils/Multiplexer.qs b/Standard/src/Canon/Utils/Multiplexer.qs index 3206175f2ce..e6ec81b1bb7 100644 --- a/Standard/src/Canon/Utils/Multiplexer.qs +++ b/Standard/src/Canon/Utils/Multiplexer.qs @@ -21,7 +21,7 @@ namespace Microsoft.Quantum.Canon { /// \begin{align} /// U = \sum^{2^n - 1}_{j=0} \ket{j}\bra{j} \otimes e^{i P \theta_j}. /// \end{align} - /// ## + /// $$ /// /// # Input /// ## coefficients From 543b2402a571c85f077a48cfa052482f3324efa5 Mon Sep 17 00:00:00 2001 From: Irina Hristova Date: Tue, 20 Oct 2020 10:43:23 +0300 Subject: [PATCH 08/15] Fix #278 CX truth table (#345) * Update CommonGates.qs * Update Standard/src/Canon/CommonGates.qs * Update Standard/src/Canon/CommonGates.qs Co-authored-by: Chris Granade Co-authored-by: Mathias Soeken Co-authored-by: Chris Granade Co-authored-by: Chris Granade Co-authored-by: Mathias Soeken --- Standard/src/Canon/CommonGates.qs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/Standard/src/Canon/CommonGates.qs b/Standard/src/Canon/CommonGates.qs index 65e755f6bd5..64315547131 100644 --- a/Standard/src/Canon/CommonGates.qs +++ b/Standard/src/Canon/CommonGates.qs @@ -12,10 +12,12 @@ namespace Microsoft.Quantum.Canon { /// /// $$ /// \begin{align} - /// 1 & 0 & 0 & 0 \\\\ - /// 0 & 1 & 0 & 0 \\\\ - /// 0 & 0 & 0 & 1 \\\\ - /// 0 & 0 & 1 & 0 + /// \left(\begin{matrix} + /// 1 & 0 & 0 & 0 \\\\ + /// 0 & 1 & 0 & 0 \\\\ + /// 0 & 0 & 0 & 1 \\\\ + /// 0 & 0 & 1 & 0 + /// \end{matrix}\right) /// \end{align}, /// $$ /// where rows and columns are organized as in the quantum concepts guide. From ac2e60b3d858f97d61f862b5532382c31e7d83f5 Mon Sep 17 00:00:00 2001 From: Chris Granade Date: Wed, 21 Oct 2020 08:49:33 -0700 Subject: [PATCH 09/15] Merge work on new documentation generation tool into main. (#354) * Add metadata needed for improved documentation generation (#342) * Fix documentation warnings (#353) --- Build/props/tests.props | 3 +- Chemistry/src/Jupyter/BroombridgeMagic.cs | 2 +- Chemistry/src/Jupyter/ChemistryEncodeMagic.cs | 2 +- .../src/Jupyter/FermionHamiltonianMagic.cs | 7 +- Chemistry/src/Jupyter/WavefunctionMagic.cs | 2 +- Chemistry/src/Runtime/Runtime.csproj | 9 +- .../tests/ChemistryTests/QSharpTests.csproj | 3 +- .../tests/SystemTests/SystemTests.csproj | 3 +- MachineLearning/src/MachineLearning.csproj | 3 +- MachineLearning/src/Types.qs | 12 +- .../tests/MachineLearningTests.csproj | 2 +- Numerics/src/Numerics.csproj | 6 +- Numerics/tests/NumericsTests.csproj | 2 +- .../AmplitudeAmplification.qs | 8 +- Standard/src/AmplitudeAmplification/Types.qs | 11 +- Standard/src/Arithmetic/ApplyDual.qs | 6 +- Standard/src/Arithmetic/ApplyReversed.qs | 114 +++++++++--------- Standard/src/Arithmetic/Arithmetic.qs | 2 +- Standard/src/Arithmetic/Comparators.qs | 4 +- Standard/src/Arithmetic/Increment.qs | 5 +- Standard/src/Arithmetic/Modular.qs | 6 +- Standard/src/Arithmetic/Types.qs | 6 +- Standard/src/Arrays/Arrays.qs | 4 +- Standard/src/Arrays/EqualA.qs | 4 +- Standard/src/Arrays/Map.qs | 2 +- .../Canon/Combinators/ApplyRepeatedOver.qs | 8 +- .../src/Canon/Combinators/ApplyToArray.qs | 32 ++--- .../src/Canon/Combinators/ApplyToElement.qs | 10 +- .../src/Canon/Combinators/ApplyToFirst.qs | 26 ++-- .../src/Canon/Combinators/ApplyToPartition.qs | 16 +-- Standard/src/Canon/Combinators/Curry.qs | 12 +- Standard/src/Canon/Combinators/Delay.qs | 9 +- .../src/Canon/Combinators/OperationPow.qs | 12 +- .../Combinators/RestrictedToSubregister.qs | 24 ++-- Standard/src/Canon/Combinators/Transformed.qs | 74 ++++++------ Standard/src/Canon/Combinators/With.qs | 59 ++++----- Standard/src/Canon/CommonGates.qs | 3 +- Standard/src/Canon/Enumeration/Trotter.qs | 14 +-- Standard/src/Canon/Parity.qs | 2 +- Standard/src/Canon/QFT.qs | 2 +- Standard/src/Canon/Utils/Multiplexer.qs | 19 ++- Standard/src/Convert/Convert.qs | 2 - Standard/src/ErrorCorrection/5QubitCode.qs | 16 ++- Standard/src/ErrorCorrection/7QubitCode.qs | 22 ++-- Standard/src/ErrorCorrection/BitFlipCode.qs | 8 +- Standard/src/ErrorCorrection/Types.qs | 4 +- Standard/src/ErrorCorrection/Utils.qs | 12 +- Standard/src/Math/Complex.qs | 30 ++--- Standard/src/Math/Functions.qs | 19 ++- Standard/src/Math/Types.qs | 12 ++ Standard/src/Optimization/Univariate.qs | 2 +- Standard/src/Oracles/Convert.qs | 12 +- Standard/src/Preparation/Arbitrary.qs | 2 +- Standard/src/Preparation/Mixed.qs | 2 +- Standard/src/Preparation/Reference.qs | 14 +-- Standard/src/Simulation/BlockEncoding.qs | 22 ++-- .../Data/GeneratorRepresentation.qs | 31 +++-- .../QubitizationPauliEvolutionSet.qs | 11 +- Standard/src/Simulation/Techniques.qs | 4 +- Standard/src/Simulation/Types.qs | 4 +- Standard/src/Standard.csproj | 13 +- Standard/tests/Standard.Tests.csproj | 2 +- Visualization/src/Visualization.csproj | 4 +- 63 files changed, 403 insertions(+), 395 deletions(-) diff --git a/Build/props/tests.props b/Build/props/tests.props index 1c76f5de1e9..93da9885b9e 100644 --- a/Build/props/tests.props +++ b/Build/props/tests.props @@ -6,7 +6,7 @@ - + @@ -14,4 +14,3 @@ - diff --git a/Chemistry/src/Jupyter/BroombridgeMagic.cs b/Chemistry/src/Jupyter/BroombridgeMagic.cs index abf5f8f5340..d3bbcc3bf9d 100644 --- a/Chemistry/src/Jupyter/BroombridgeMagic.cs +++ b/Chemistry/src/Jupyter/BroombridgeMagic.cs @@ -16,7 +16,7 @@ public class BroombridgeMagic : MagicSymbol public BroombridgeMagic() { this.Name = $"%chemistry.broombridge"; - this.Documentation = new Documentation() { Summary = "Loads and returns Broombridge electronic structure problem representation from a given .yaml file." }; + this.Documentation = new Microsoft.Jupyter.Core.Documentation() { Summary = "Loads and returns Broombridge electronic structure problem representation from a given .yaml file." }; this.Kind = SymbolKind.Magic; this.Execute = this.Run; } diff --git a/Chemistry/src/Jupyter/ChemistryEncodeMagic.cs b/Chemistry/src/Jupyter/ChemistryEncodeMagic.cs index 8eac3a69ca3..6e88be2b0be 100644 --- a/Chemistry/src/Jupyter/ChemistryEncodeMagic.cs +++ b/Chemistry/src/Jupyter/ChemistryEncodeMagic.cs @@ -17,7 +17,7 @@ public class ChemistryEncodeMagic : MagicSymbol public ChemistryEncodeMagic() { this.Name = $"%chemistry.encode"; - this.Documentation = new Documentation() { Summary = "Encodes a fermion Hamiltonian to a format consumable by Q#." }; + this.Documentation = new Microsoft.Jupyter.Core.Documentation() { Summary = "Encodes a fermion Hamiltonian to a format consumable by Q#." }; this.Kind = SymbolKind.Magic; this.Execute = this.Run; } diff --git a/Chemistry/src/Jupyter/FermionHamiltonianMagic.cs b/Chemistry/src/Jupyter/FermionHamiltonianMagic.cs index b61954ed4e0..07e3583bd37 100644 --- a/Chemistry/src/Jupyter/FermionHamiltonianMagic.cs +++ b/Chemistry/src/Jupyter/FermionHamiltonianMagic.cs @@ -26,7 +26,7 @@ public class FermionHamiltonianLoadMagic : MagicSymbol public FermionHamiltonianLoadMagic() { this.Name = $"%chemistry.fh.load"; - this.Documentation = new Documentation() { Summary = "Loads the fermion Hamiltonian for an electronic structure problem. The problem is loaded from a file or passed as an argument." }; + this.Documentation = new Microsoft.Jupyter.Core.Documentation() { Summary = "Loads the fermion Hamiltonian for an electronic structure problem. The problem is loaded from a file or passed as an argument." }; this.Kind = SymbolKind.Magic; this.Execute = this.Run; } @@ -113,7 +113,10 @@ public class FermionHamiltonianAddTermsMagic : MagicSymbol public FermionHamiltonianAddTermsMagic() { this.Name = $"%chemistry.fh.add_terms"; - this.Documentation = new Documentation() { Summary = "Adds terms to a fermion Hamiltonian." }; + this.Documentation = new Microsoft.Jupyter.Core.Documentation + { + Summary = "Adds terms to a fermion Hamiltonian." + }; this.Kind = SymbolKind.Magic; this.Execute = this.Run; } diff --git a/Chemistry/src/Jupyter/WavefunctionMagic.cs b/Chemistry/src/Jupyter/WavefunctionMagic.cs index bed1d935b78..f32b2bf538e 100644 --- a/Chemistry/src/Jupyter/WavefunctionMagic.cs +++ b/Chemistry/src/Jupyter/WavefunctionMagic.cs @@ -20,7 +20,7 @@ public class WavefunctionMagic : MagicSymbol public WavefunctionMagic() { this.Name = $"%chemistry.inputstate.load"; - this.Documentation = new Documentation() { Summary = "Loads Broombridge electronic structure problem and returns selected input state." }; + this.Documentation = new Microsoft.Jupyter.Core.Documentation() { Summary = "Loads Broombridge electronic structure problem and returns selected input state." }; this.Kind = SymbolKind.Magic; this.Execute = this.Run; } diff --git a/Chemistry/src/Runtime/Runtime.csproj b/Chemistry/src/Runtime/Runtime.csproj index 902c0c66483..3c6a82671de 100644 --- a/Chemistry/src/Runtime/Runtime.csproj +++ b/Chemistry/src/Runtime/Runtime.csproj @@ -1,4 +1,4 @@ - + netstandard2.1 @@ -6,6 +6,10 @@ true false True + + Microsoft.Quantum.Chemistry @@ -36,7 +40,7 @@ - + @@ -44,4 +48,3 @@ - diff --git a/Chemistry/tests/ChemistryTests/QSharpTests.csproj b/Chemistry/tests/ChemistryTests/QSharpTests.csproj index 0c32a5c7541..812d30ef794 100644 --- a/Chemistry/tests/ChemistryTests/QSharpTests.csproj +++ b/Chemistry/tests/ChemistryTests/QSharpTests.csproj @@ -1,4 +1,4 @@ - + @@ -12,4 +12,3 @@ - diff --git a/Chemistry/tests/SystemTests/SystemTests.csproj b/Chemistry/tests/SystemTests/SystemTests.csproj index 27269417885..83495463ace 100644 --- a/Chemistry/tests/SystemTests/SystemTests.csproj +++ b/Chemistry/tests/SystemTests/SystemTests.csproj @@ -1,4 +1,4 @@ - + @@ -39,4 +39,3 @@ - diff --git a/MachineLearning/src/MachineLearning.csproj b/MachineLearning/src/MachineLearning.csproj index 73b86c36b20..6ffd2451c74 100644 --- a/MachineLearning/src/MachineLearning.csproj +++ b/MachineLearning/src/MachineLearning.csproj @@ -1,8 +1,9 @@ - + netstandard2.1 Microsoft.Quantum.MachineLearning true + Microsoft.Quantum.MachineLearning 1591 + + + true + + + + Microsoft Microsoft's Quantum standard libraries. @@ -30,7 +37,7 @@ - + diff --git a/Standard/tests/Standard.Tests.csproj b/Standard/tests/Standard.Tests.csproj index 5bf903caf46..c7fdb20e54c 100644 --- a/Standard/tests/Standard.Tests.csproj +++ b/Standard/tests/Standard.Tests.csproj @@ -1,4 +1,4 @@ - + diff --git a/Visualization/src/Visualization.csproj b/Visualization/src/Visualization.csproj index 65f339d8b4a..5ad41e9f98d 100644 --- a/Visualization/src/Visualization.csproj +++ b/Visualization/src/Visualization.csproj @@ -32,9 +32,9 @@ - + - + From 2fc255bf0e339329b8fadc289ca3793abf6f92cd Mon Sep 17 00:00:00 2001 From: Andres Paz Date: Tue, 27 Oct 2020 00:51:03 -0700 Subject: [PATCH 10/15] Update manifest for signed builds (#357) --- Build/manifest.ps1 | 44 +++++++++++++++++++++++++++++++++++--------- Build/steps.yml | 6 ++++++ 2 files changed, 41 insertions(+), 9 deletions(-) diff --git a/Build/manifest.ps1 b/Build/manifest.ps1 index fe82d57e8ef..2e86b8dc423 100644 --- a/Build/manifest.ps1 +++ b/Build/manifest.ps1 @@ -1,16 +1,35 @@ -#!/usr/bin/env pwsh -#Requires -PSEdition Core +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +<# + .SYNOPSIS + Provides the list of artifacts (Packages and Assemblies) generated by this repository. + + .PARAMETER OutputFormat + Specifies if the output of this script should be a hashtable with the artifacts + as strings with the absolute path (AbsolutePath) or FileInfo structures. +#> +param( + [ValidateSet('FileInfo','AbsolutePath')] + [string] $OutputFormat = 'FileInfo' +); + & "$PSScriptRoot/set-env.ps1" -@{ +$artifacts = @{ Packages = @( - "Microsoft.Quantum.Standard", - "Microsoft.Quantum.Standard.Visualization", "Microsoft.Quantum.Chemistry", + "Microsoft.Quantum.Chemistry.DataModel", + "Microsoft.Quantum.Chemistry.Jupyter", + "Microsoft.Quantum.Chemistry.Runtime", + "Microsoft.Quantum.Chemistry.Tools", + "Microsoft.Quantum.MachineLearning", "Microsoft.Quantum.Numerics", - "Microsoft.Quantum.MachineLearning" - ); + "Microsoft.Quantum.Standard", + "Microsoft.Quantum.Standard.Visualization" + ) | ForEach-Object { Join-Path $Env:NUGET_OUTDIR "$_.$Env:NUGET_VERSION.nupkg" }; + Assemblies = @( ".\Standard\src\bin\$Env:BUILD_CONFIGURATION\netstandard2.1\Microsoft.Quantum.Standard.dll", ".\Visualization\src\bin\$Env:BUILD_CONFIGURATION\netstandard2.1\Microsoft.Quantum.Standard.Visualization.dll", @@ -19,5 +38,12 @@ ".\Chemistry\src\DataModel\bin\$Env:BUILD_CONFIGURATION\netstandard2.1\Microsoft.Quantum.Chemistry.DataModel.dll", ".\Chemistry\src\Runtime\bin\$Env:BUILD_CONFIGURATION\netstandard2.1\Microsoft.Quantum.Chemistry.Runtime.dll", ".\Chemistry\src\Tools\bin\$Env:BUILD_CONFIGURATION\netcoreapp3.1\qdk-chem.dll" - ) | ForEach-Object { Get-Item (Join-Path $PSScriptRoot ".." $_) }; -} | Write-Output; + ) | ForEach-Object { Join-Path $PSScriptRoot (Join-Path ".." $_) }; +} + +if ($OutputFormat -eq 'FileInfo') { + $artifacts.Packages = $artifacts.Packages | ForEach-Object { Get-Item $_ }; + $artifacts.Assemblies = $artifacts.Assemblies | ForEach-Object { Get-Item $_ }; +} + +$artifacts | Write-Output; diff --git a/Build/steps.yml b/Build/steps.yml index 2f386fd117b..4e6aebbfbe2 100644 --- a/Build/steps.yml +++ b/Build/steps.yml @@ -36,4 +36,10 @@ steps: workingDirectory: $(System.DefaultWorkingDirectory)/Build +- pwsh: .\manifest.ps1 + displayName: "List built packages & assemblies" + workingDirectory: '$(System.DefaultWorkingDirectory)/Build' + condition: succeededOrFailed() + + - template: step-wrap-up.yml From 0a84a07d721700b06750f245de3a192c4e5b9b1c Mon Sep 17 00:00:00 2001 From: Andres Paz Date: Wed, 28 Oct 2020 20:52:33 -0700 Subject: [PATCH 11/15] Missed dll for signing (#361) --- Build/manifest.ps1 | 1 + 1 file changed, 1 insertion(+) diff --git a/Build/manifest.ps1 b/Build/manifest.ps1 index 2e86b8dc423..9765de673a3 100644 --- a/Build/manifest.ps1 +++ b/Build/manifest.ps1 @@ -36,6 +36,7 @@ $artifacts = @{ ".\Numerics\src\bin\$Env:BUILD_CONFIGURATION\netstandard2.1\Microsoft.Quantum.Numerics.dll", ".\MachineLearning\src\bin\$Env:BUILD_CONFIGURATION\netstandard2.1\Microsoft.Quantum.MachineLearning.dll", ".\Chemistry\src\DataModel\bin\$Env:BUILD_CONFIGURATION\netstandard2.1\Microsoft.Quantum.Chemistry.DataModel.dll", + ".\Chemistry\src\Jupyter\bin\$Env:BUILD_CONFIGURATION\netstandard2.1\Microsoft.Quantum.Chemistry.Jupyter.dll", ".\Chemistry\src\Runtime\bin\$Env:BUILD_CONFIGURATION\netstandard2.1\Microsoft.Quantum.Chemistry.Runtime.dll", ".\Chemistry\src\Tools\bin\$Env:BUILD_CONFIGURATION\netcoreapp3.1\qdk-chem.dll" ) | ForEach-Object { Join-Path $PSScriptRoot (Join-Path ".." $_) }; From 50dd29b7c863e8ca5a0697ffad9e76ac012dc473 Mon Sep 17 00:00:00 2001 From: Irina Hristova Date: Fri, 30 Oct 2020 08:15:50 +0200 Subject: [PATCH 12/15] Update unit tests to use @Test attribute (#350) * Update tests using the @Test attribute. * Update tests using the @Test() attribute. * Flip actual and expected. * Update Standard/tests/Math/OperatorFunctionTests.qs Co-authored-by: Chris Granade Co-authored-by: Chris Granade Co-authored-by: Chris Granade Co-authored-by: Mathias Soeken --- Standard/tests/AmplitudeAmplificationTests.qs | 11 +- Standard/tests/ApplyMultiControlledTests.qs | 3 +- Standard/tests/ApplyRepeatedOverTests.qs | 10 +- Standard/tests/Arithmetic/ReflectionTests.qs | 3 +- Standard/tests/ArithmeticTests.qs | 14 +-- Standard/tests/ArrayTests.qs | 46 ++++---- Standard/tests/AssertTests.qs | 13 +-- Standard/tests/BitwiseTests.qs | 3 +- Standard/tests/CombinatorTests.qs | 101 ++++++++++-------- Standard/tests/CommonGateTests.qs | 15 ++- Standard/tests/ConversionTests.qs | 6 +- Standard/tests/EnumerationTests.qs | 24 +++-- Standard/tests/Logical/BooleanTests.qs | 15 ++- Standard/tests/Logical/ComparisonTests.qs | 1 + Standard/tests/Logical/PredicateTests.qs | 22 ++-- Standard/tests/Math/MathTests.qs | 50 ++++----- Standard/tests/Math/OperatorFunctionTests.qs | 91 ++++++++-------- Standard/tests/Measurement/ResetTests.qs | 7 +- Standard/tests/MultiplexerTests.qs | 11 +- .../tests/Optimization/UnivariateTests.qs | 4 +- Standard/tests/PairTests.qs | 5 +- Standard/tests/PauliTests.qs | 7 +- Standard/tests/QFTTests.qs | 3 +- Standard/tests/QcvvTests.qs | 19 ++-- Standard/tests/QeccTests.qs | 42 ++++---- Standard/tests/QuantumPhaseEstimationTests.qs | 3 +- Standard/tests/QubitizationTests.qs | 21 ++-- Standard/tests/StatePreparationTests.qs | 13 ++- Standard/tests/TypeConversionTests.qs | 6 +- .../UniformSuperpositionPreparationTests.qs | 4 +- 30 files changed, 326 insertions(+), 247 deletions(-) diff --git a/Standard/tests/AmplitudeAmplificationTests.qs b/Standard/tests/AmplitudeAmplificationTests.qs index 4f731c119e8..f25ebe30718 100644 --- a/Standard/tests/AmplitudeAmplificationTests.qs +++ b/Standard/tests/AmplitudeAmplificationTests.qs @@ -31,7 +31,8 @@ namespace Microsoft.Quantum.Tests { /// In this minimal example, there are no system qubits, only a single flag qubit. /// ExampleStatePrep is already of type StateOracle, so we call /// StandardAmplitudeAmplification(iterations: Int, stateOracle : StateOracle, idxFlagQubit : Int startQubits: Qubit[]) : () - operation AmpAmpByOracleTest () : Unit { + @Test("QuantumSimulator") + operation CheckAmpAmpByOracle () : Unit { using (qubits = Qubit[1]) { ResetAll(qubits); @@ -54,8 +55,8 @@ namespace Microsoft.Quantum.Tests { } } - - operation AmpAmpObliviousByOraclePhasesTest () : Unit { + @Test("QuantumSimulator") + operation CheckAmpAmpObliviousByOraclePhases () : Unit { using (qubits = Qubit[1]) { ResetAll(qubits); @@ -80,8 +81,8 @@ namespace Microsoft.Quantum.Tests { } } - - operation AmpAmpTargetStateReflectionOracleTest () : Unit { + @Test("QuantumSimulator") + operation CheckAmpAmpTargetStateReflectionOracle () : Unit { using (qubits = Qubit[1]) { ResetAll(qubits); diff --git a/Standard/tests/ApplyMultiControlledTests.qs b/Standard/tests/ApplyMultiControlledTests.qs index e05139732bd..e5ef7cbe1c4 100644 --- a/Standard/tests/ApplyMultiControlledTests.qs +++ b/Standard/tests/ApplyMultiControlledTests.qs @@ -11,7 +11,8 @@ namespace Microsoft.Quantum.Tests { /// Tests multiply controlled not implementation that uses /// ApplyMultiControlledCA against multiply controlled version of /// the Microsoft.Quantum.Intrinsic.X - operation ApplyMultiControlledTest () : Unit { + @Test("QuantumSimulator") + operation CheckApplyMultiControlled() : Unit { let twoQubitOp = CNOT; diff --git a/Standard/tests/ApplyRepeatedOverTests.qs b/Standard/tests/ApplyRepeatedOverTests.qs index 51594b46a3e..7bb4220d151 100644 --- a/Standard/tests/ApplyRepeatedOverTests.qs +++ b/Standard/tests/ApplyRepeatedOverTests.qs @@ -8,8 +8,8 @@ namespace Microsoft.Quantum.Tests { open Microsoft.Quantum.Diagnostics; open Microsoft.Quantum.Arrays; - - operation ApplySeriesOfOpsTest() : Unit { + @Test("QuantumSimulator") + operation CheckApplySeriesOfOps() : Unit { // create the sample ops + their targets here let op1 = ApplyToFirstQubit(X, _); let op2 = ApplyToFirstTwoQubits(CNOT, _); @@ -34,7 +34,8 @@ namespace Microsoft.Quantum.Tests { ApplyToEachCA(H, Subarray([1, 2, 3, 4], register)); } - operation ApplyRepeatedOpTest() : Unit { + @Test("QuantumSimulator") + operation CheckApplyRepeatedOp() : Unit { let op = ApplyToFirstThreeQubits(CCNOT, _); let targets = [[0, 1, 2], [2, 1, 0], [3, 4, 5], [2, 4, 0], [5, 3, 1]]; AssertOperationsEqualReferenced(6, ApplyOpRepeatedlyOver(op, targets, _), SampleApplyRepeatedOp(_)); @@ -49,7 +50,8 @@ namespace Microsoft.Quantum.Tests { CCNOT(register[5], register[3], register[1]); } - operation PermuteQubitsTest() : Unit { + @Test("QuantumSimulator") + operation CheckPermuteQubits() : Unit { let sampleOrder = [5, 3, 2, 0, 1, 4]; AssertOperationsEqualReferenced(6, PermuteQubits(sampleOrder, _) , SamplePermuteQubits); } diff --git a/Standard/tests/Arithmetic/ReflectionTests.qs b/Standard/tests/Arithmetic/ReflectionTests.qs index 5002490cd97..7f87f7dfb5f 100644 --- a/Standard/tests/Arithmetic/ReflectionTests.qs +++ b/Standard/tests/Arithmetic/ReflectionTests.qs @@ -19,7 +19,8 @@ namespace Microsoft.Quantum.Tests { ReflectAboutInteger(5, littleEndian); } - operation ReflectAboutIntegerTest() : Unit { + @Test("QuantumSimulator") + operation CheckReflectAboutInteger() : Unit { AssertOperationsEqualReferenced(3, ReflectAboutFiveUsingLibrary, ManuallyReflectAboutFive diff --git a/Standard/tests/ArithmeticTests.qs b/Standard/tests/ArithmeticTests.qs index e841a3092c3..e15edf9a6c9 100644 --- a/Standard/tests/ArithmeticTests.qs +++ b/Standard/tests/ArithmeticTests.qs @@ -18,9 +18,9 @@ namespace Microsoft.Quantum.ArithmeticTests { } } - - operation ApplyXorInPlaceTest () : Unit { - + @Test("QuantumSimulator") + operation CheckApplyXorInPlace() : Unit { + ApplyToEach(InPlaceXorTestHelper, [(63, 6), (42, 6)]); } @@ -42,7 +42,7 @@ namespace Microsoft.Quantum.ArithmeticTests { /// Exhaustively tests Microsoft.Quantum.Artihmetic.IncrementByInteger /// on 4 qubits @Test("QuantumSimulator") - operation IncrementByIntegerTest () : Unit { + operation CheckIncrementByInteger() : Unit { let numberOfQubits = 4; @@ -86,7 +86,7 @@ namespace Microsoft.Quantum.ArithmeticTests { /// Tests Microsoft.Quantum.Arithmetic.IncrementByModularInteger /// on 4 qubits with modulus 13 @Test("QuantumSimulator") - operation IncrementByModularIntegerTest () : Unit { + operation CheckIncrementByModularInteger() : Unit { let numberOfQubits = 4; let modulus = 13; @@ -122,7 +122,7 @@ namespace Microsoft.Quantum.ArithmeticTests { /// Tests Microsoft.Quantum.Canon.ModularAddProductLE /// on 4 qubits with modulus 13 @Test("QuantumSimulator") - operation MultiplyAndAddByModularIntegerTest () : Unit { + operation CheckMultiplyAndAddByModularInteger() : Unit { let numberOfQubits = 4; let modulus = 13; @@ -160,7 +160,7 @@ namespace Microsoft.Quantum.ArithmeticTests { /// Tests Microsoft.Quantum.Canon.ModularMultiplyByConstantLE /// on 4 qubits with modulus 13 @Test("QuantumSimulator") - operation MultiplyByModularIntegerTest () : Unit { + operation CheckMultiplyByModularInteger() : Unit { let numberOfQubits = 4; let modulus = 13; diff --git a/Standard/tests/ArrayTests.qs b/Standard/tests/ArrayTests.qs index 3aa1b38be19..71f5ecc8777 100644 --- a/Standard/tests/ArrayTests.qs +++ b/Standard/tests/ArrayTests.qs @@ -91,8 +91,8 @@ namespace Microsoft.Quantum.Tests { EqualityFactI(fnArray[3](7), 49, $"ConstantArray(Int, Int -> Int) had the wrong value."); } - - function SubarrayTest () : Unit { + @Test("QuantumSimulator") + function SubarrayIsCorrect () : Unit { let array0 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let subarrayOdd = Subarray([1, 3, 5, 7, 9], array0); let subarrayEven = Subarray([0, 2, 4, 6, 8, 10], array0); @@ -116,21 +116,20 @@ namespace Microsoft.Quantum.Tests { EqualityFactI(countEvens, 5, $"the even elements of [1..10] were not correctly counted."); } - - function ReverseTest () : Unit { - + @Test("QuantumSimulator") + function ReversedIsCorrect() : Unit { let array = [1, 2, 3]; Ignore(Mapped(EqualityFactI(_, _, $"Reversed failed."), Zipped([3, 2, 1], Reversed(array)))); } - - function ExcludingTest () : Unit { + @Test("QuantumSimulator") + function ExcludingIsCorrect() : Unit { let array = [10, 11, 12, 13, 14, 15]; Ignore(Mapped(EqualityFactI(_, _, $"Excluding failed."), Zipped([10, 11, 13, 14], Excluding([2, 5], array)))); } - - function PadTest () : Unit { + @Test("QuantumSimulator") + function PaddedIsCorrect() : Unit { mutable arrayTestCase = [(-5, 2, [10, 11, 12], [10, 11, 12, 2, 2]), (5, 2, [10, 11, 12], [2, 2, 10, 11, 12]), (-3, -2, [10, 11, 12], [10, 11, 12])]; @@ -141,7 +140,8 @@ namespace Microsoft.Quantum.Tests { } } - function EnumeratedTest() : Unit { + @Test("QuantumSimulator") + function EnumeratedIsCorrect() : Unit { let example = [37, 12]; let expected = [(0, 37), (1, 12)]; let actual = Enumerated(example); @@ -152,7 +152,8 @@ namespace Microsoft.Quantum.Tests { } } - function SequenceITest() : Unit { + @Test("QuantumSimulator") + function SequenceIIsCorrect() : Unit { let example = [(0, 3), (23, 29), (-5, -2)]; let expected = [[0, 1, 2, 3], [23, 24, 25, 26, 27, 28, 29], [-5, -4, -3, -2]]; let actual = Mapped(SequenceI, example); @@ -165,7 +166,8 @@ namespace Microsoft.Quantum.Tests { } } - function SequenceLTest() : Unit { + @Test("QuantumSimulator") + function SequenceLIsCorrect() : Unit { let example = [(0L, 3L), (23L, 29L), (-5L, -2L)]; let expected = [[0L, 1L, 2L, 3L], [23L, 24L, 25L, 26L, 27L, 28L, 29L], [-5L, -4L, -3L, -2L]]; let actual = Mapped(SequenceL, example); @@ -177,8 +179,8 @@ namespace Microsoft.Quantum.Tests { } } } - - function SequenceForNumbersTest() : Unit { + @Test("QuantumSimulator") + function SequenceForNumbersIsCorrect() : Unit { let example = [3, 5, 0]; let expected = [[0, 1, 2, 3], [0, 1, 2, 3, 4, 5], [0]]; let actual = Mapped(SequenceI(0, _), example); @@ -191,7 +193,8 @@ namespace Microsoft.Quantum.Tests { } } - function IsEmptyTest() : Unit { + @Test("QuantumSimulator") + function IsEmptyIsCorrect() : Unit { Fact(IsEmpty(new Int[0]), "Empty array marked as non-empty."); Fact(IsEmpty(new Qubit[0]), "Empty array marked as non-empty."); Fact(IsEmpty(new (Double, (Int -> String))[0]), "Empty array marked as non-empty."); @@ -199,7 +202,8 @@ namespace Microsoft.Quantum.Tests { Fact(not IsEmpty([""]), "Non-empty array marked as empty."); } - function SwapOrderToPermuteArrayTest() : Unit { + @Test("QuantumSimulator") + function SwapOrderToPermuteArrayIsCorrect() : Unit { let newOrder = [0, 4, 2, 1, 3]; let expected = [(1, 4), (1, 3)]; let actual = _SwapOrderToPermuteArray(newOrder); @@ -214,7 +218,8 @@ namespace Microsoft.Quantum.Tests { } } - function SwappedTest() : Unit { + @Test("QuantumSimulator") + function SwappedIsCorrect() : Unit { let example = [2, 4, 6, 8, 10]; let expected = [2, 8, 6, 4, 10]; let leftIndex = 1; @@ -227,7 +232,8 @@ namespace Microsoft.Quantum.Tests { } } - function TupleArrayAsNestedArrayTest() : Unit { + @Test("QuantumSimulator") + function TupleArrayAsNestedArrayIsCorrect() : Unit { let example = [(0, 1), (2, 3), (4, 5), (6, 7)]; let expected = [[0, 1], [2, 3], [4, 5], [6, 7]]; @@ -240,8 +246,8 @@ namespace Microsoft.Quantum.Tests { } } - - function EqualATest() : Unit { + @Test("QuantumSimulator") + function EqualAIsCorrect() : Unit { // arrays of integers let equalArrays = EqualA(EqualI, [2, 3, 4], [2, 3, 4]); Fact(equalArrays, "Equal arrays were not reported as equal"); diff --git a/Standard/tests/AssertTests.qs b/Standard/tests/AssertTests.qs index 30e8eb2ea76..945435f038f 100644 --- a/Standard/tests/AssertTests.qs +++ b/Standard/tests/AssertTests.qs @@ -12,7 +12,7 @@ namespace Microsoft.Quantum.Tests { // with the intent of testing the assert and testing harness mechanisms themselves. operation EmptyTest() : Unit { } - operation PreparationTest() : Unit { + operation TestPreparation() : Unit { using (qubit = Qubit()) { Diag.AssertMeasurementProbability([PauliZ], [qubit], Zero, 1.0, $"Freshly prepared qubit was not in |0âŒȘ state.", 1E-10); } @@ -56,7 +56,8 @@ namespace Microsoft.Quantum.Tests { /// These tests are already performed in Solid itself, such that /// this operation tests whether we can reproduce that using our /// operation equality assertions. - operation SelfAdjointOperationsTest() : Unit { + @Diag.Test("QuantumSimulator") + operation TestSelfAdjointOperations() : Unit { for (op in [I, X, Y, Z, H]) { Diag.AssertOperationsEqualReferenced(3, ApplyToEach(op, _), ApplyToEachA(op, _)); } @@ -77,8 +78,8 @@ namespace Microsoft.Quantum.Tests { } } - - operation AssertProbIntTest() : Unit { + @Diag.Test("QuantumSimulator") + operation TestAssertProbInt() : Unit { let theta = 0.123; let prob = 0.015052858190174602; let tolerance = 1E-09; @@ -93,8 +94,8 @@ namespace Microsoft.Quantum.Tests { } } - - operation AssertPhaseTest() : Unit { + @Diag.Test("QuantumSimulator") + operation TestAssertPhase() : Unit { let phase = 0.456; let tolerance = 1E-09; diff --git a/Standard/tests/BitwiseTests.qs b/Standard/tests/BitwiseTests.qs index f20aca9a954..2dd8401f608 100644 --- a/Standard/tests/BitwiseTests.qs +++ b/Standard/tests/BitwiseTests.qs @@ -5,7 +5,8 @@ namespace Microsoft.Quantum.Tests { open Microsoft.Quantum.Bitwise; open Microsoft.Quantum.Diagnostics; - function ShiftTest() : Unit { + @Test("QuantumSimulator") + function ShiftIsCorrect() : Unit { let smallValue = 5; // 0b101 EqualityFactI(20, LeftShiftedI(smallValue, 2), "Shifted values incorrect."); EqualityFactI(2, RightShiftedI(smallValue, 1), "Shifted values incorrect."); diff --git a/Standard/tests/CombinatorTests.qs b/Standard/tests/CombinatorTests.qs index ad06f1803d7..cf9c7e3d267 100644 --- a/Standard/tests/CombinatorTests.qs +++ b/Standard/tests/CombinatorTests.qs @@ -8,14 +8,14 @@ namespace Microsoft.Quantum.Tests { open Microsoft.Quantum.Diagnostics; open Microsoft.Quantum.Arrays; - - function ComposeTest () : Unit { + @Test("QuantumSimulator") + function ComposeIsCorrect() : Unit { let target = [3, 17, 2]; EqualityFactI((Compose(ModulusI(_, 14), Max))(target), 3, $"Compose(ModulusI(_, 14), Max) did not return expected result."); } - - operation WithTest () : Unit { + @Test("QuantumSimulator") + operation TestWith() : Unit { let actual = ApplyWith(H, X, _); let expected = Z; @@ -25,22 +25,23 @@ namespace Microsoft.Quantum.Tests { // Make sure that if CurryTest fails, it's because of Curry and not // something else. - operation CurryPreTest () : Unit { + @Test("QuantumSimulator") + operation PreTestCurried() : Unit { AssertOperationsEqualInPlace(1, Exp([PauliZ], 1.7, _), Exp([PauliZ], 1.7, _)); AssertOperationsEqualReferenced(1, Exp([PauliZ], 1.7, _), Exp([PauliZ], 1.7, _)); } - - operation CurryTest () : Unit { + @Test("QuantumSimulator") + operation TestCurried() : Unit { let curried = CurriedOp(Exp([PauliZ], _, _)); AssertOperationsEqualInPlace(1, curried(1.7), Exp([PauliZ], 1.7, _)); AssertOperationsEqualReferenced(1, curried(1.7), Exp([PauliZ], 1.7, _)); } - - operation BindTest () : Unit { + @Test("QuantumSimulator") + operation TestBind() : Unit { let bound = BoundCA([H, X, H]); AssertOperationsEqualReferenced(3, ApplyToEach(bound, _), ApplyToEachA(Z, _)); @@ -52,8 +53,8 @@ namespace Microsoft.Quantum.Tests { return op; } - - operation BindATest () : Unit { + @Test("QuantumSimulator") + operation TestBindA() : Unit { let bound = BoundA(Mapped(StripControlled, [T, T])); AssertOperationsEqualReferenced(3, ApplyToEach(bound, _), ApplyToEachA(S, _)); @@ -80,8 +81,8 @@ namespace Microsoft.Quantum.Tests { return op; } - - operation BindCTest () : Unit { + @Test("QuantumSimulator") + operation TestBindC() : Unit { let stripped = Mapped(StripAdjoint, [T, T]); let bound = BoundC(stripped); @@ -91,8 +92,8 @@ namespace Microsoft.Quantum.Tests { AssertOperationsEqualReferenced(6, op, target); } - - operation BindCATest () : Unit { + @Test("QuantumSimulator") + operation TestBindCA() : Unit { let bound = BoundCA([T, T]); AssertOperationsEqualReferenced(3, ApplyToEach(bound, _), ApplyToEachA(S, _)); AssertOperationsEqualReferenced(3, ApplyToEach(Adjoint bound, _), ApplyToEachA(Adjoint S, _)); @@ -101,8 +102,8 @@ namespace Microsoft.Quantum.Tests { AssertOperationsEqualReferenced(4, op, target); } - - operation OperationPowTest () : Unit { + @Test("QuantumSimulator") + operation TestOperationPow() : Unit { AssertOperationsEqualReferenced(3, ApplyToEach(OperationPow(H, 2), _), NoOp); AssertOperationsEqualReferenced(3, ApplyToEach(OperationPow(Z, 2), _), NoOp); @@ -110,8 +111,8 @@ namespace Microsoft.Quantum.Tests { AssertOperationsEqualReferenced(3, ApplyToEach(OperationPow(T, 8), _), NoOp); } - - operation ApplyToSubregisterTest () : Unit { + @Test("QuantumSimulator") + operation TestApplyToSubregister() : Unit { let bigOp = ApplyPauli([PauliI, PauliX, PauliY, PauliZ, PauliI], _); let smallOp = ApplyPauli([PauliX, PauliY, PauliZ], _); @@ -169,8 +170,8 @@ namespace Microsoft.Quantum.Tests { controlled adjoint distribute; } - - operation CControlledTest () : Unit { + @Test("QuantumSimulator") + operation TestCControlled() : Unit { AssertOperationsEqualReferenced(3, CControlledActual(H, _), CControlledExpected(H, _)); AssertOperationsEqualReferenced(3, CControlledActual(Z, _), CControlledExpected(Z, _)); @@ -178,7 +179,7 @@ namespace Microsoft.Quantum.Tests { AssertOperationsEqualReferenced(3, CControlledActual(T, _), CControlledExpected(T, _)); } - + @Test("QuantumSimulator") operation CControlledTestC () : Unit { AssertOperationsEqualReferenced(3, CControlledActualC(H, _), CControlledExpected(H, _)); @@ -187,7 +188,7 @@ namespace Microsoft.Quantum.Tests { AssertOperationsEqualReferenced(3, CControlledActualC(T, _), CControlledExpected(T, _)); } - + @Test("QuantumSimulator") operation CControlledTestA () : Unit { AssertOperationsEqualReferenced(3, CControlledActualA(H, _), CControlledExpected(H, _)); @@ -196,7 +197,7 @@ namespace Microsoft.Quantum.Tests { AssertOperationsEqualReferenced(3, CControlledActualA(T, _), CControlledExpected(T, _)); } - + @Test("QuantumSimulator") operation CControlledTestCA () : Unit { AssertOperationsEqualReferenced(3, CControlledActualCA(H, _), CControlledExpected(H, _)); @@ -205,43 +206,50 @@ namespace Microsoft.Quantum.Tests { AssertOperationsEqualReferenced(3, CControlledActualCA(T, _), CControlledExpected(T, _)); } - operation ApplyIfZeroTest() : Unit { + @Test("QuantumSimulator") + operation TestApplyIfZero() : Unit { AssertOperationsEqualReferenced(2, ApplyIfZero(One, (ApplyToEach(H, _), _)), ApplyToEachA(I, _)); AssertOperationsEqualReferenced(2, ApplyIfZero(Zero, (ApplyToEach(H, _), _)), ApplyToEachA(H, _)); } - operation ApplyIfOneTest() : Unit { + @Test("QuantumSimulator") + operation TestApplyIfOne() : Unit { AssertOperationsEqualReferenced(2, ApplyIfOne(One, (ApplyToEach(H, _), _)), ApplyToEachA(H, _)); AssertOperationsEqualReferenced(2, ApplyIfOne(Zero, (ApplyToEach(H, _), _)), ApplyToEachA(I, _)); } - - operation ApplyIfZeroCTest() : Unit { + @Test("QuantumSimulator") + operation TestApplyIfZeroC() : Unit { AssertOperationsEqualReferenced(2, ApplyIfZeroC(One, (ApplyToEachC(H, _), _)), ApplyToEachA(I, _)); AssertOperationsEqualReferenced(2, ApplyIfZeroC(Zero, (ApplyToEachC(H, _), _)), ApplyToEachA(H, _)); } - operation ApplyIfOneCTest() : Unit { + @Test("QuantumSimulator") + operation TestApplyIfOneC() : Unit { AssertOperationsEqualReferenced(2, ApplyIfOneC(One, (ApplyToEachC(H, _), _)), ApplyToEachA(H, _)); AssertOperationsEqualReferenced(2, ApplyIfOneC(Zero, (ApplyToEachC(H, _), _)), ApplyToEachA(I, _)); } - operation ApplyIfZeroCATest() : Unit { + @Test("QuantumSimulator") + operation TestApplyIfZeroCA() : Unit { AssertOperationsEqualReferenced(2, ApplyIfZeroCA(One, (ApplyToEachCA(H, _), _)), ApplyToEachA(I, _)); AssertOperationsEqualReferenced(2, ApplyIfZeroCA(Zero, (ApplyToEachCA(H, _), _)), ApplyToEachA(H, _)); } - operation ApplyIfOneCATest() : Unit { + @Test("QuantumSimulator") + operation TestApplyIfOneCA() : Unit { AssertOperationsEqualReferenced(2, ApplyIfOneCA(One, (ApplyToEachCA(H, _), _)), ApplyToEachA(H, _)); AssertOperationsEqualReferenced(2, ApplyIfOneCA(Zero, (ApplyToEachCA(H, _), _)), ApplyToEachA(I, _)); } - operation ApplyIfZeroATest() : Unit { + @Test("QuantumSimulator") + operation TestApplyIfZeroA() : Unit { AssertOperationsEqualReferenced(2, ApplyIfZeroA(One, (ApplyToEachA(H, _), _)), ApplyToEachA(I, _)); AssertOperationsEqualReferenced(2, ApplyIfZeroA(Zero, (ApplyToEachA(H, _), _)), ApplyToEachA(H, _)); } - operation ApplyIfOneATest() : Unit { + @Test("QuantumSimulator") + operation TestApplyIfOneA() : Unit { AssertOperationsEqualReferenced(2, ApplyIfOneA(One, (ApplyToEachA(H, _), _)), ApplyToEachA(H, _)); AssertOperationsEqualReferenced(2, ApplyIfOneA(Zero, (ApplyToEachA(H, _), _)), ApplyToEachA(I, _)); } @@ -254,7 +262,8 @@ namespace Microsoft.Quantum.Tests { ); } - operation ApplyIfElseRTest() : Unit { + @Test("QuantumSimulator") + operation TestApplyIfElseR() : Unit { AssertOperationsEqualReferenced(2, ApplyIfElseRCase(Zero, _), ApplyToEachA(H, _)); AssertOperationsEqualReferenced(2, ApplyIfElseRCase(One, _), ApplyToEachA(X, _)); } @@ -267,7 +276,8 @@ namespace Microsoft.Quantum.Tests { ); } - operation ApplyIfElseRATest() : Unit { + @Test("QuantumSimulator") + operation TestApplyIfElseRA() : Unit { AssertOperationsEqualReferenced(2, ApplyIfElseRACase(Zero, _), ApplyToEachA(H, _)); AssertOperationsEqualReferenced(2, ApplyIfElseRACase(One, _), ApplyToEachA(X, _)); } @@ -280,7 +290,8 @@ namespace Microsoft.Quantum.Tests { ); } - operation ApplyIfElseRCTest() : Unit { + @Test("QuantumSimulator") + operation TestApplyIfElseRC() : Unit { AssertOperationsEqualReferenced(2, ApplyIfElseRCCase(Zero, _), ApplyToEachA(H, _)); AssertOperationsEqualReferenced(2, ApplyIfElseRCCase(One, _), ApplyToEachA(X, _)); } @@ -293,7 +304,8 @@ namespace Microsoft.Quantum.Tests { ); } - operation ApplyIfElseRCATest() : Unit { + @Test("QuantumSimulator") + operation TestApplyIfElseRCA() : Unit { AssertOperationsEqualReferenced(2, ApplyIfElseRCACase(Zero, _), ApplyToEachA(H, _)); AssertOperationsEqualReferenced(2, ApplyIfElseRCACase(One, _), ApplyToEachA(X, _)); } @@ -306,7 +318,8 @@ namespace Microsoft.Quantum.Tests { ); } - operation ApplyIfElseBTest() : Unit { + @Test("QuantumSimulator") + operation TestApplyIfElseB() : Unit { AssertOperationsEqualReferenced(2, ApplyIfElseBCase(true, _), ApplyToEachA(H, _)); AssertOperationsEqualReferenced(2, ApplyIfElseBCase(false, _), ApplyToEachA(X, _)); } @@ -319,7 +332,8 @@ namespace Microsoft.Quantum.Tests { ); } - operation ApplyIfElseBATest() : Unit { + @Test("QuantumSimulator") + operation TestApplyIfElseBA() : Unit { AssertOperationsEqualReferenced(2, ApplyIfElseBACase(true, _), ApplyToEachA(H, _)); AssertOperationsEqualReferenced(2, ApplyIfElseBACase(false, _), ApplyToEachA(X, _)); } @@ -332,7 +346,8 @@ namespace Microsoft.Quantum.Tests { ); } - operation ApplyIfElseBCTest() : Unit { + @Test("QuantumSimulator") + operation TestApplyIfElseBC() : Unit { AssertOperationsEqualReferenced(2, ApplyIfElseBCCase(true, _), ApplyToEachA(H, _)); AssertOperationsEqualReferenced(2, ApplyIfElseBCCase(false, _), ApplyToEachA(X, _)); } @@ -345,7 +360,8 @@ namespace Microsoft.Quantum.Tests { ); } - operation ApplyIfElseBCATest() : Unit { + @Test("QuantumSimulator") + operation TestApplyIfElseBCA() : Unit { AssertOperationsEqualReferenced(2, ApplyIfElseBCACase(true, _), ApplyToEachA(H, _)); AssertOperationsEqualReferenced(2, ApplyIfElseBCACase(false, _), ApplyToEachA(X, _)); } @@ -354,7 +370,8 @@ namespace Microsoft.Quantum.Tests { X(qubits[1]); } - operation ApplyToElementTest() : Unit { + @Test("QuantumSimulator") + operation TestApplyToElement() : Unit { AssertOperationsEqualReferenced(3, ApplyToElement(X, 1, _), ApplyXToSecondQubit diff --git a/Standard/tests/CommonGateTests.qs b/Standard/tests/CommonGateTests.qs index dbe41666f3f..946f759e836 100644 --- a/Standard/tests/CommonGateTests.qs +++ b/Standard/tests/CommonGateTests.qs @@ -17,26 +17,30 @@ namespace Microsoft.Quantum.Tests { adjoint auto; } - operation CXTest() : Unit { + @Test("QuantumSimulator") + operation TestCX() : Unit { let actual = ApplyCShorthandToRegister(CX, _); let expected = ApplyControlledOpToRegister(X, _); AssertOperationsEqualReferenced(2, actual, expected); } - operation CYTest() : Unit { + @Test("QuantumSimulator") + operation TestCY() : Unit { let actual = ApplyCShorthandToRegister(CY, _); let expected = ApplyControlledOpToRegister(Y, _); AssertOperationsEqualReferenced(2, actual, expected); } - operation CZTest() : Unit { + @Test("QuantumSimulator") + operation TestCZ() : Unit { let actual = ApplyCShorthandToRegister(CZ, _); let expected = ApplyControlledOpToRegister(Z, _); AssertOperationsEqualReferenced(2, actual, expected); } // Verify Fermionic SWAP gives the correct qubit values - operation ApplyFermionicSWAPValueTest() : Unit { + @Test("QuantumSimulator") + operation CheckApplyFermionicSWAPValue() : Unit { using ((left, right) = (Qubit(), Qubit())) { // 00 ApplyFermionicSWAP(left, right); @@ -69,7 +73,8 @@ namespace Microsoft.Quantum.Tests { } // Verify Fermionic SWAP gives the correct phase change - operation ApplyFermionicSWAPPhaseTest() : Unit { + @Test("QuantumSimulator") + operation CheckApplyFermionicSWAPPhase() : Unit { using ((left, right) = (Qubit(), Qubit())) { // 00 VerifyFermionicSWAPPhaseHelper(Zero, left, right); diff --git a/Standard/tests/ConversionTests.qs b/Standard/tests/ConversionTests.qs index b60833f6fb1..328ad1eb322 100644 --- a/Standard/tests/ConversionTests.qs +++ b/Standard/tests/ConversionTests.qs @@ -5,14 +5,16 @@ namespace Microsoft.Quantum.Tests { open Microsoft.Quantum.Canon; open Microsoft.Quantum.Convert; - function ResultArrayAsIntTest () : Unit { + @Test("QuantumSimulator") + function ResultArrayAsIntIsCorrect() : Unit { EqualityFactI(ResultArrayAsInt([Zero, Zero]), 0, $"Expected [Zero, Zero] to be represented by 0."); EqualityFactI(ResultArrayAsInt([One, Zero]), 1, $"Expected [One, Zero] to be represented by 1."); EqualityFactI(ResultArrayAsInt([Zero, One]), 2, $"Expected [Zero, One] to be represented by 2."); EqualityFactI(ResultArrayAsInt([One, One]), 3, $"Expected [One, One] to be represented by 3."); } - function BoolArrFromPositiveIntTest () : Unit { + @Test("QuantumSimulator") + function BoolArrFromPositiveIntIsCorrect() : Unit { for (number in 0 .. 100) { let bits = IntAsBoolArray(number, 9); let inte = BoolArrayAsInt(bits); diff --git a/Standard/tests/EnumerationTests.qs b/Standard/tests/EnumerationTests.qs index 5e9db499f26..05c32f3e5ed 100644 --- a/Standard/tests/EnumerationTests.qs +++ b/Standard/tests/EnumerationTests.qs @@ -30,29 +30,29 @@ namespace Microsoft.Quantum.Tests { return a * a; } - - function ForAllTest () : Unit { + @Test("QuantumSimulator") + function ForAllIsCorrect() : Unit { EqualityFactB(All(IsSingleDigit, [3, 4, 7, 8]), true, $"the elements [3, 4, 7, 8] were not found to be single digit numbers."); EqualityFactB(All(IsSingleDigit, [3, 4, 7, 18]), false, $"the elements [3, 4, 7, 18] were found to be single digit numbers."); } - - - function ForAnyTest () : Unit { + + @Test("QuantumSimulator") + function ForAnyIsCorrect() : Unit { EqualityFactB(Any(IsEven, [3, 7, 99, -4]), true, $"the elements [3, 7, 99, -4] were not found to contain at least one even number."); EqualityFactB(Any(IsEven, [3, 7, 99, -41]), false, $"the elements [3, 7, 99, -4] were not found to contain at least one even number."); } - - function FoldTest () : Unit { + @Test("QuantumSimulator") + function FoldIsCorrect() : Unit { let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; EqualityFactI(Fold(Add, 0, array), 55, $"folding the summation over [1..10] did not yield 55."); } - - function MapTest () : Unit { + @Test("QuantumSimulator") + function MapIsCorrect() : Unit { let array = [1, 2, 3, 4]; let squaredArray = Mapped(Squarer, array); @@ -86,13 +86,15 @@ namespace Microsoft.Quantum.Tests { AllEqualityFactI(numbers, [1, 2, 3, 1, 2, 3, 1, 2, 3], "Flattened failed"); } - function ExtremaTest () : Unit { + @Test("QuantumSimulator") + function ExtremaIsCorrect() : Unit { let array = [-10, 10, 7, 0]; EqualityFactI(-10, Min(array), $"Min failed."); EqualityFactI(10, Max(array), $"Max failed."); } - function IndexOfTest() : Unit { + @Test("QuantumSimulator") + function IndexOfIsCorrect() : Unit { let array = [1, 3, 21, -7, 2, 19]; let actual = IndexOf(IsEven, array); EqualityFactI(4, actual, $"Expected 4, got {actual}."); diff --git a/Standard/tests/Logical/BooleanTests.qs b/Standard/tests/Logical/BooleanTests.qs index 9900278fd75..ebc6f73855a 100644 --- a/Standard/tests/Logical/BooleanTests.qs +++ b/Standard/tests/Logical/BooleanTests.qs @@ -5,32 +5,37 @@ namespace Microsoft.Quantum.Tests { open Microsoft.Quantum.Logical; open Microsoft.Quantum.Diagnostics; - function NotTest() : Unit { + @Test("QuantumSimulator") + function NotIsCorrect() : Unit { Fact(Not(false), "Not returned wrong output."); } - function AndTest() : Unit { + @Test("QuantumSimulator") + function AndIsCorrect() : Unit { Fact(not And(false, false), "And returned wrong output."); Fact(not And(false, true), "And returned wrong output."); Fact(not And(true, false), "And returned wrong output."); Fact(And(true, true), "And returned wrong output."); } - function OrTest() : Unit { + @Test("QuantumSimulator") + function OrIsCorrect() : Unit { Fact(not Or(false, false), "Or returned wrong output."); Fact(Or(false, true), "Or returned wrong output."); Fact(Or(true, false), "Or returned wrong output."); Fact(Or(true, true), "Or returned wrong output."); } - function XorTest() : Unit { + @Test("QuantumSimulator") + function XorIsCorrect() : Unit { Fact(not Xor(false, false), "Xor returned wrong output."); Fact(Xor(false, true), "Xor returned wrong output."); Fact(Xor(true, false), "Xor returned wrong output."); Fact(not Xor(true, true), "Xor returned wrong output."); } - function ConditionedTest() : Unit { + @Test("QuantumSimulator") + function ConditionedIsCorrect() : Unit { EqualityFactI(Conditioned(true, 42, -1), 42, "Conditioned returned wrong output."); EqualityFactL(Conditioned(false, 42L, -1L), -1L, "Conditioned returned wrong output."); } diff --git a/Standard/tests/Logical/ComparisonTests.qs b/Standard/tests/Logical/ComparisonTests.qs index 9afd776c33d..a426c729396 100644 --- a/Standard/tests/Logical/ComparisonTests.qs +++ b/Standard/tests/Logical/ComparisonTests.qs @@ -7,6 +7,7 @@ namespace Microsoft.Quantum.Tests { open Microsoft.Quantum.Math; open Microsoft.Quantum.Arrays; + @Test("QuantumSimulator") function LexographicComparisonIsCorrect() : Unit { let lexographicComparison = LexographicComparison(LessThanOrEqualD); Fact( diff --git a/Standard/tests/Logical/PredicateTests.qs b/Standard/tests/Logical/PredicateTests.qs index 5c970d97e46..b27b3b6936f 100644 --- a/Standard/tests/Logical/PredicateTests.qs +++ b/Standard/tests/Logical/PredicateTests.qs @@ -6,7 +6,8 @@ namespace Microsoft.Quantum.Tests { open Microsoft.Quantum.Diagnostics; open Microsoft.Quantum.Math; - function EqualTest() : Unit { + @Test("QuantumSimulator") + function EqualIsCorrect() : Unit { Fact(EqualI(42, 42), "EqualI returned wrong output."); Fact(not EqualI(42, 73), "EqualI returned wrong output."); @@ -29,7 +30,8 @@ namespace Microsoft.Quantum.Tests { Fact(not EqualCP(ComplexPolar(1.0, 2.0), ComplexPolar(1.0, 73.0)), "EqualCP returned wrong output."); } - function NotEqualTest() : Unit { + @Test("QuantumSimulator") + function NotEqualIsCorrect() : Unit { Fact(not NotEqualI(42, 42), "NotEqualI returned wrong output."); Fact(NotEqualI(42, 73), "NotEqualI returned wrong output."); @@ -52,7 +54,8 @@ namespace Microsoft.Quantum.Tests { Fact(NotEqualCP(ComplexPolar(1.0, 2.0), ComplexPolar(1.0, 73.0)), "NotEqualCP returned wrong output."); } - function GreaterThanTest() : Unit { + @Test("QuantumSimulator") + function GreaterThanIsCorrect() : Unit { Fact(GreaterThanI(75, 32), "GreaterThanI returned wrong output."); Fact(not GreaterThanI(-13, 32), "GreaterThanI returned wrong output."); @@ -63,7 +66,8 @@ namespace Microsoft.Quantum.Tests { Fact(not GreaterThanL(-13L, 32L), "GreaterThanL returned wrong output."); } - function LessThanTest() : Unit { + @Test("QuantumSimulator") + function LessThanIsCorrect() : Unit { Fact(not LessThanI(75, 32), "LessThanI returned wrong output."); Fact(LessThanI(-13, 32), "LessThanI returned wrong output."); @@ -74,7 +78,8 @@ namespace Microsoft.Quantum.Tests { Fact(LessThanL(-13L, 32L), "LessThanL returned wrong output."); } - function GreaterThanOrEqualTest() : Unit { + @Test("QuantumSimulator") + function GreaterThanOrEqualIsCorrect() : Unit { Fact(GreaterThanOrEqualI(75, 75), "GreaterThanOrEqualI returned wrong output."); Fact(not GreaterThanOrEqualI(-13, 32), "GreaterThanOrEqualI returned wrong output."); @@ -85,7 +90,8 @@ namespace Microsoft.Quantum.Tests { Fact(not GreaterThanOrEqualL(-13L, 32L), "GreaterThanOrEqualL returned wrong output."); } - function LessThanOrEqualTest() : Unit { + @Test("QuantumSimulator") + function LessThanOrEqualIsCorrect() : Unit { Fact(LessThanOrEqualI(75, 75), "LessThanOrEqualI returned wrong output."); Fact(not LessThanOrEqualI(32, -13), "LessThanOrEqualI returned wrong output."); @@ -96,10 +102,10 @@ namespace Microsoft.Quantum.Tests { Fact(not LessThanOrEqualL(32L, -13L), "LessThanOrEqualL returned wrong output."); } - function NearlyEqualDTest() : Unit { + @Test("QuantumSimulator") + function NearlyEqualDIsCorrect() : Unit { Fact(NearlyEqualD(1.0, 1.0), "Exactly equal numbers marked as not nearly equal."); Fact(NearlyEqualD(1.0, 1.0 + 1e-15), "Nearly equal numbers marked as not nearly equal."); Fact(not NearlyEqualD(1.0, 1000.0), "Not nearly equal numbers marked as nearly equal."); } - } diff --git a/Standard/tests/Math/MathTests.qs b/Standard/tests/Math/MathTests.qs index 3a8c27b1321..b4fd41dfb35 100644 --- a/Standard/tests/Math/MathTests.qs +++ b/Standard/tests/Math/MathTests.qs @@ -6,7 +6,8 @@ namespace Microsoft.Quantum.Canon { open Microsoft.Quantum.Diagnostics; open Microsoft.Quantum.Arrays; - function NativeFnsAreCallableTest () : Unit { + @Test("QuantumSimulator") + function NativeFnsAreCallable () : Unit { let arg = PI() / 2.0; NearEqualityFactD(Sin(arg), 1.0); @@ -16,15 +17,15 @@ namespace Microsoft.Quantum.Canon { NearEqualityFactD(ArcSin(arcArg), arg); } - - function RealModTest () : Unit { + @Test("QuantumSimulator") + function RealModIsCorrect () : Unit { NearEqualityFactD(RealMod(5.5 * PI(), 2.0 * PI(), 0.0), 1.5 * PI()); NearEqualityFactD(RealMod(0.5 * PI(), 2.0 * PI(), -PI() / 2.0), 0.5 * PI()); } - - function ArcHyperbolicFnsTest () : Unit { + @Test("QuantumSimulator") + function ArcHyperbolicFnsAreCorrect () : Unit { // These tests were generated using NumPy's implementations // of the inverse hyperbolic functions. @@ -33,7 +34,6 @@ namespace Microsoft.Quantum.Canon { NearEqualityFactD(ArcSinh(-0.7), -0.65266656608235574); } - function ExtendedGreatestCommonDivisorITestHelper (a : Int, b : Int, gcd : Int) : Unit { Message($"Testing {a}, {b}, {gcd} "); @@ -43,14 +43,15 @@ namespace Microsoft.Quantum.Canon { EqualityFactI(expected, actual, $"Expected absolute value of gcd to be {expected}, got {actual}"); } - - function ExtendedGreatestCommonDivisorITest () : Unit { + @Test("QuantumSimulator") + function ExtendedGreatestCommonDivisorIIsCorrect () : Unit { let testTuples = [(1, 1, 1), (1, -1, 1), (-1, 1, 1), (-1, -1, 1), (5, 7, 1), (-5, 7, 1), (3, 15, 3)]; Ignore(Mapped(ExtendedGreatestCommonDivisorITestHelper, testTuples)); } - function GreatestCommonDivisorLTest() : Unit { + @Test("QuantumSimulator") + function GreatestCommonDivisorLIsCorrect() : Unit { EqualityFactL( GreatestCommonDivisorL( 44958225298979240833230460209285719018635426448048959524915L, @@ -60,24 +61,22 @@ namespace Microsoft.Quantum.Canon { "GCD returned wrong result for BigInt inputs." ); } - - - function BitSizeTest () : Unit { + @Test("QuantumSimulator") + function BitSizeIsCorrect () : Unit { EqualityFactI(BitSizeI(3), 2, $"BitSizeI(3) must be 2"); EqualityFactI(BitSizeI(7), 3, $"BitSizeI(7) must be 2"); } - - function ExpModTest () : Unit { + @Test("QuantumSimulator") + function ExpModIsCorrect () : Unit { // this test is generated using Mathematica PowerMod function let result = ExpModI(5, 4611686018427387903, 7); EqualityFactI(result, 6, $"The result must be 6, got {result}"); } - - + function ContinuedFractionConvergentTestHelper (numerator : Int, denominator : Int) : Unit { let bitSize = 2 * BitSizeI(denominator); @@ -86,15 +85,14 @@ namespace Microsoft.Quantum.Canon { EqualityFactB(AbsI(u) == numerator and AbsI(v) == denominator, true, $"The result must be ±{numerator}/±{denominator} got {u}/{v}"); } - function ContinuedFractionConvergentEdgeCaseTestHelper (numerator : Int, denominator : Int, bound : Int) : Unit { let (num, denom) = (ContinuedFractionConvergentI(Fraction(numerator, denominator), bound))!; EqualityFactB(AbsI(num) == numerator and AbsI(denom) == denominator, true, $"The result must be ±{numerator}/±{denominator} got {num}/{denom}"); } - - function ContinuedFractionConvergentTest () : Unit { + @Test("QuantumSimulator") + function ContinuedFractionConvergentIsCorrect () : Unit { let testTuples = [(29, 47), (17, 37), (15, 67)]; Ignore(Mapped(ContinuedFractionConvergentTestHelper, testTuples)); @@ -102,8 +100,8 @@ namespace Microsoft.Quantum.Canon { Ignore(Mapped(ContinuedFractionConvergentEdgeCaseTestHelper, edgeCaseTestTuples)); } - - function ComplexMathTest () : Unit { + @Test("QuantumSimulator") + function ComplexMathIsCorrect () : Unit { mutable complexCases = [(0.123, 0.321), (0.123, -0.321), (-0.123, 0.321), (-0.123, -0.321)]; @@ -128,8 +126,8 @@ namespace Microsoft.Quantum.Canon { } } - - function PNormTest () : Unit { + @Test("QuantumSimulator") + function PNormIsCorrect () : Unit { mutable testCases = [ (1.0, [-0.1, 0.2, 0.3], 0.6), @@ -151,12 +149,10 @@ namespace Microsoft.Quantum.Canon { } } - function SquaredNormTest() : Unit { + @Test("QuantumSimulator") + function SquaredNormIsCorrect() : Unit { NearEqualityFactD(SquaredNorm([2.0]), 4.0); NearEqualityFactD(SquaredNorm([1.0, 1.0]), 2.0); NearEqualityFactD(SquaredNorm([3.0, 4.0]), 25.0); } - } - - diff --git a/Standard/tests/Math/OperatorFunctionTests.qs b/Standard/tests/Math/OperatorFunctionTests.qs index 10c36d3eb85..f155ce01dfc 100644 --- a/Standard/tests/Math/OperatorFunctionTests.qs +++ b/Standard/tests/Math/OperatorFunctionTests.qs @@ -17,64 +17,67 @@ namespace Microsoft.Quantum.Tests { function TWO_PI_4_C() : Complex { return ComplexPolarAsComplex(TWO_PI_4_CP()); } function TWO_PI_4_CP() : ComplexPolar { return ComplexPolar(2.0, PI() / 4.0); } - // FIXME: expected and actual are flipped uniformly in this file. - // this has no effect other than making unit test failures slightly - // harder to read. - - function NegationTest() : Unit { - EqualityFactI(-42, NegationI(42), "NegationI returned wrong output."); - NearEqualityFactD(-42.0, NegationD(42.0)); - EqualityFactL(-42L, NegationL(42L), "NegationI returned wrong output."); - NearEqualityFactC(Complex(1.0, 2.0), NegationC(Complex(-1.0, -2.0))); + @Test("QuantumSimulator") + function NegationIsCorrect() : Unit { + EqualityFactI(NegationI(42), -42, "NegationI returned wrong output."); + NearEqualityFactD(NegationD(42.0), -42.0); + EqualityFactL(NegationL(42L), -42L, "NegationI returned wrong output."); + NearEqualityFactC(NegationC(Complex(-1.0, -2.0)), Complex(1.0, 2.0)); NearEqualityFactCP( - ComplexPolar(1.0, PI() / 4.0), - NegationCP(ComplexPolar(1.0, 5.0 * PI() / 4.0)) + NegationCP(ComplexPolar(1.0, 5.0 * PI() / 4.0)), + ComplexPolar(1.0, PI() / 4.0) ); } - function PlusTest() : Unit { - EqualityFactI(-40, PlusI(-72, 32), "PlusI returned wrong output."); - NearEqualityFactD(-40.0, PlusD(-72.0, 32.0)); - EqualityFactL(-40L, PlusL(-72L, 32L), "PlusL returned wrong output."); - NearEqualityFactC(TWO_C(), PlusC(ONE_C(), ONE_C())); - NearEqualityFactCP(TWO_CP(), PlusCP(ONE_CP(), ONE_CP())); + @Test("QuantumSimulator") + function PlusIsCorrect() : Unit { + EqualityFactI(PlusI(-72, 32), -40, "PlusI returned wrong output."); + NearEqualityFactD(PlusD(-72.0, 32.0), -40.0); + EqualityFactL(PlusL(-72L, 32L), -40L, "PlusL returned wrong output."); + NearEqualityFactC(PlusC(ONE_C(), ONE_C()), TWO_C()); + NearEqualityFactCP(PlusCP(ONE_CP(), ONE_CP()), TWO_CP()); } - function MinusTest() : Unit { - EqualityFactI(40, MinusI(72, 32), "MinusI returned wrong output."); - NearEqualityFactD(40.0, MinusD(72.0, 32.0)); - EqualityFactL(40L, MinusL(72L, 32L), "MinusL returned wrong output."); - NearEqualityFactC(ONE_C(), MinusC(TWO_C(), ONE_C())); - NearEqualityFactCP(ONE_CP(), MinusCP(TWO_CP(), ONE_CP())); + @Test("QuantumSimulator") + function MinusIsCorrect() : Unit { + EqualityFactI(MinusI(72, 32), 40, "MinusI returned wrong output."); + NearEqualityFactD(MinusD(72.0, 32.0), 40.0); + EqualityFactL(MinusL(72L, 32L), 40L, "MinusL returned wrong output."); + NearEqualityFactC(MinusC(TWO_C(), ONE_C()), ONE_C()); + NearEqualityFactCP(MinusCP(TWO_CP(), ONE_CP()), ONE_CP()); } - function TimesTest() : Unit { - EqualityFactI(40, TimesI(-10, -4), "TimesI returned wrong output."); - NearEqualityFactD(40.0, TimesD(-10.0, -4.0)); - EqualityFactL(40L, TimesL(-10L, -4L), "TimesL returned wrong output."); - NearEqualityFactC(TWO_C(), TimesC(TWO_C(), ONE_C())); - NearEqualityFactCP(TWO_CP(), TimesCP(TWO_CP(), ONE_CP())); + @Test("QuantumSimulator") + function TimesIsCorrect() : Unit { + EqualityFactI(TimesI(-10, -4), 40, "TimesI returned wrong output."); + NearEqualityFactD(TimesD(-10.0, -4.0), 40.0); + EqualityFactL(TimesL(-10L, -4L), 40L, "TimesL returned wrong output."); + NearEqualityFactC(TimesC(TWO_C(), ONE_C()), TWO_C()); + NearEqualityFactCP(TimesCP(TWO_CP(), ONE_CP()), TWO_CP()); } - function DivdedByTest() : Unit { - EqualityFactI(10, DividedByI(-40, -4), "DividedByI returned wrong output."); - NearEqualityFactD(10.0, DividedByD(-40.0, -4.0)); - EqualityFactL(10L, DividedByL(-40L, -4L), "DividedByL returned wrong output."); - NearEqualityFactC(PI_4_C(), DividedByC(TWO_PI_4_C(), TWO_C())); - NearEqualityFactCP(PI_4_CP(), DividedByCP(TWO_PI_4_CP(), TWO_CP())); + @Test("QuantumSimulator") + function DividedByIsCorrect() : Unit { + EqualityFactI(DividedByI(-40, -4), 10, "DividedByI returned wrong output."); + NearEqualityFactD(DividedByD(-40.0, -4.0), 10.0); + EqualityFactL(DividedByL(-40L, -4L), 10L, "DividedByL returned wrong output."); + NearEqualityFactC(DividedByC(TWO_PI_4_C(), TWO_C()), PI_4_C()); + NearEqualityFactCP(DividedByCP(TWO_PI_4_CP(), TWO_CP()), PI_4_CP()); } - function ModTest() : Unit { - EqualityFactI(2, ModI(17, 5), "ModI returned wrong output."); - EqualityFactL(2L, ModL(17L, 5L), "ModL returned wrong output."); + @Test("QuantumSimulator") + function ModIsCorrect() : Unit { + EqualityFactI(ModI(17, 5), 2, "ModI returned wrong output."); + EqualityFactL(ModL(17L, 5L), 2L, "ModL returned wrong output."); } - function PowTest() : Unit { - EqualityFactI(6561, PowI(3, 8), "PowI returned wrong output."); - NearEqualityFactD(157.58648490814928441592231285347, PowD(2.0, 7.3)); - EqualityFactL(239072435685151324847153L, PowL(17L, 19), "PowL returned wrong output."); - NearEqualityFactC(PI_2_C(), PowC(PI_4_C(), TWO_C())); - NearEqualityFactCP(PI_2_CP(), PowCP(PI_4_CP(), TWO_CP())); + @Test("QuantumSimulator") + function PowIsCorrect() : Unit { + EqualityFactI(PowI(3, 8), 6561, "PowI returned wrong output."); + NearEqualityFactD(PowD(2.0, 7.3), 157.58648490814928441592231285347); + EqualityFactL(PowL(17L, 19), 239072435685151324847153L, "PowL returned wrong output."); + NearEqualityFactC(PowC(PI_4_C(), TWO_C()), PI_2_C()); + NearEqualityFactCP(PowCP(PI_4_CP(), TWO_CP()), PI_2_CP()); } } diff --git a/Standard/tests/Measurement/ResetTests.qs b/Standard/tests/Measurement/ResetTests.qs index 45056d785e2..aaf98e2cc60 100644 --- a/Standard/tests/Measurement/ResetTests.qs +++ b/Standard/tests/Measurement/ResetTests.qs @@ -6,7 +6,7 @@ namespace Microsoft.Quantum.Tests { open Microsoft.Quantum.Intrinsic; open Microsoft.Quantum.Diagnostics; - operation CheckSetToBasisState(desired : Result) : Unit { + operation CheckSetToBasisStateHelper(desired : Result) : Unit { using (q = Qubit()) { Ry(0.1234, q); SetToBasisState(desired, q); @@ -15,9 +15,10 @@ namespace Microsoft.Quantum.Tests { } } - operation SetToBasisStateTest() : Unit { + @Test("QuantumSimulator") + operation CheckSetToBasisState() : Unit { for (desired in [Zero, One]) { - CheckSetToBasisState(desired); + CheckSetToBasisStateHelper(desired); } } diff --git a/Standard/tests/MultiplexerTests.qs b/Standard/tests/MultiplexerTests.qs index 9e166c30956..f23a680eb9a 100644 --- a/Standard/tests/MultiplexerTests.qs +++ b/Standard/tests/MultiplexerTests.qs @@ -147,8 +147,8 @@ namespace Microsoft.Quantum.Tests { } } - - operation ApplyDiagonalUnitaryTest () : Unit { + @Diag.Test("QuantumSimulator") + operation TestApplyDiagonalUnitary() : Unit { let maxQubits = 4; @@ -331,8 +331,8 @@ namespace Microsoft.Quantum.Tests { return result; } - - operation MultiplexOperationsTest () : Unit { + @Diag.Test("QuantumSimulator") + operation TestMultiplexOperations() : Unit { mutable result = Zero; @@ -505,7 +505,8 @@ namespace Microsoft.Quantum.Tests { } } - operation MultiplexOperationsFromGeneratorTest() : Unit{ + @Diag.Test("QuantumSimulator") + operation TestMultiplexOperationsFromGenerator() : Unit{ body (...) { mutable result = Zero; diff --git a/Standard/tests/Optimization/UnivariateTests.qs b/Standard/tests/Optimization/UnivariateTests.qs index 73301bcb343..d43d988e53e 100644 --- a/Standard/tests/Optimization/UnivariateTests.qs +++ b/Standard/tests/Optimization/UnivariateTests.qs @@ -10,8 +10,8 @@ namespace Microsoft.Quantum.Tests { return PowD((x - minima), 2.0); } - // @Test("QuantumSimulator") - function MinimizedParabolaTest() : Unit { + @Test("QuantumSimulator") + function MinimizedParabolaIsCorrect() : Unit { let optimum = LocalUnivariateMinimum(ParabolaCase(3.14, _), (-7.0, +12.0), 1e-10); NearEqualityFactD(optimum::Coordinate, 3.14); NearEqualityFactD(optimum::Value, 0.0); diff --git a/Standard/tests/PairTests.qs b/Standard/tests/PairTests.qs index 0f70826bbcd..e4dca98a3e6 100644 --- a/Standard/tests/PairTests.qs +++ b/Standard/tests/PairTests.qs @@ -3,9 +3,10 @@ namespace Microsoft.Quantum.Tests { open Microsoft.Quantum.Canon; + open Microsoft.Quantum.Diagnostics; - - function PairTest () : Unit { + @Test("QuantumSimulator") + function PairIsCorrect() : Unit { let pair = (12, PauliZ); diff --git a/Standard/tests/PauliTests.qs b/Standard/tests/PauliTests.qs index e2911973dec..a60e8447b31 100644 --- a/Standard/tests/PauliTests.qs +++ b/Standard/tests/PauliTests.qs @@ -5,9 +5,10 @@ namespace Microsoft.Quantum.Tests { open Microsoft.Quantum.Intrinsic; open Microsoft.Quantum.Canon; open Microsoft.Quantum.Measurement; - - - operation MeasureWithScratchTest () : Unit { + open Microsoft.Quantum.Diagnostics; + + @Test("QuantumSimulator") + operation TestMeasureWithScratch() : Unit { using (register = Qubit[2]) { PrepareEntangledState([register[0]], [register[1]]); diff --git a/Standard/tests/QFTTests.qs b/Standard/tests/QFTTests.qs index 40be1c455fe..e0eeee11696 100644 --- a/Standard/tests/QFTTests.qs +++ b/Standard/tests/QFTTests.qs @@ -93,7 +93,8 @@ namespace Microsoft.Quantum.Tests { /// # Summary /// Compares QFT to the hard-coded implementations - operation QFTTest () : Unit { + @Test("QuantumSimulator") + operation TestQFT() : Unit { let testFunctions = [QFT1, QFT2, QFT3, QFT4]; for (i in IndexRange(testFunctions)) { diff --git a/Standard/tests/QcvvTests.qs b/Standard/tests/QcvvTests.qs index bb7a85ccced..cbc35f9bbe4 100644 --- a/Standard/tests/QcvvTests.qs +++ b/Standard/tests/QcvvTests.qs @@ -12,7 +12,8 @@ namespace Microsoft.Quantum.Tests { open Microsoft.Quantum.Math; open Microsoft.Quantum.Measurement as Meas; - operation ChoiStateTest () : Unit { + @Test("QuantumSimulator") + operation TestChoiState() : Unit { using (register = Qubit[2]) { PrepareChoiStateCA(NoOp, [register[0]], [register[1]]); @@ -28,7 +29,8 @@ namespace Microsoft.Quantum.Tests { Message("stage prepared"); } - operation EstimateFrequencyTest () : Unit { + @Test("QuantumSimulator") + operation TestEstimateFrequency() : Unit { let freq1 = EstimateFrequency(ApplyToEach(H, _), Meas.MeasureAllZ, 1, 1000); EqualityWithinToleranceFact(freq1, 0.5, 0.1); @@ -55,7 +57,8 @@ namespace Microsoft.Quantum.Tests { EqualityWithinToleranceFact(expectation, actualFreq, tolerance); } - operation EstimateFrequencyBinomialTest() : Unit { + @Test("QuantumSimulator") + operation TestEstimateFrequencyBinomial() : Unit { // If this is larger, tests fail less often, but more false negatives // slip through. let nStdDevs = 3.0; @@ -98,7 +101,8 @@ namespace Microsoft.Quantum.Tests { } // Probabilistic test. Might fail occasionally - operation RobustPhaseEstimationTest () : Unit { + @Test("QuantumSimulator") + operation TestRobustPhaseEstimation() : Unit { let bitsPrecision = 10; @@ -109,8 +113,8 @@ namespace Microsoft.Quantum.Tests { } } - - operation PrepareQubitTest () : Unit { + @Test("QuantumSimulator") + operation TestPrepareQubit() : Unit { using (qubit = Qubit()) { let bases = [PauliI, PauliX, PauliY, PauliZ]; @@ -122,7 +126,8 @@ namespace Microsoft.Quantum.Tests { } } - operation SingleQubitProcessTomographyMeasurementTest () : Unit { + @Test("QuantumSimulator") + operation TestSingleQubitProcessTomographyMeasurement() : Unit { EqualityFactR(SingleQubitProcessTomographyMeasurement(PauliI, PauliI, H), Zero, $"Failed at âŸȘI | H | I⟫."); EqualityFactR(SingleQubitProcessTomographyMeasurement(PauliX, PauliI, H), Zero, $"Failed at âŸȘI | H | X⟫."); EqualityFactR(SingleQubitProcessTomographyMeasurement(PauliY, PauliI, H), Zero, $"Failed at âŸȘI | H | Y⟫."); diff --git a/Standard/tests/QeccTests.qs b/Standard/tests/QeccTests.qs index ed2670db7bb..8827115e78e 100644 --- a/Standard/tests/QeccTests.qs +++ b/Standard/tests/QeccTests.qs @@ -57,7 +57,8 @@ namespace Microsoft.Quantum.Tests { /// # Summary /// Ensures that the bit flip code can correct a single arbitrary /// bit-flip ($X$) error. - operation BitFlipTest () : Unit { + @Test("QuantumSimulator") + operation TestBitFlip() : Unit { let code = BitFlipCode(); let fn = BitFlipRecoveryFn(); @@ -71,7 +72,8 @@ namespace Microsoft.Quantum.Tests { /// # Summary /// Ensures that the 5-qubit perfect code can correct an arbitrary /// single-qubit error. - operation FiveQubitCodeTest () : Unit { + @Test("QuantumSimulator") + operation TestFiveQubitCode() : Unit { let code = FiveQubitCode(); let fn = FiveQubitCodeRecoveryFn(); @@ -83,7 +85,8 @@ namespace Microsoft.Quantum.Tests { // TODO: split this test up into several smaller tests. - operation FiveQubitTediousTest () : Unit { + @Test("QuantumSimulator") + operation TestFiveQubitTedious() : Unit { let s = SyndromeMeasOp(MeasureStabilizerGenerators([[PauliX, PauliZ, PauliZ, PauliX, PauliI], [PauliI, PauliX, PauliZ, PauliZ, PauliX], [PauliX, PauliI, PauliX, PauliZ, PauliZ], [PauliZ, PauliX, PauliI, PauliX, PauliZ]], _, MeasureWithScratch)); @@ -164,8 +167,8 @@ namespace Microsoft.Quantum.Tests { } } - - operation FiveQubitTest () : Unit { + @Test("QuantumSimulator") + operation TestFiveQubit() : Unit { let s = SyndromeMeasOp(MeasureStabilizerGenerators([[PauliX, PauliZ, PauliZ, PauliX, PauliI], [PauliI, PauliX, PauliZ, PauliZ, PauliX], [PauliX, PauliI, PauliX, PauliZ, PauliZ], [PauliZ, PauliX, PauliI, PauliX, PauliZ]], _, MeasureWithScratch)); @@ -212,8 +215,8 @@ namespace Microsoft.Quantum.Tests { } } - - operation SteaneCodeEncoderTest () : Unit { + @Test("QuantumSimulator") + operation TestSteaneCodeEncoder() : Unit { using (aux = Qubit[7]) { SteaneCodeEncoderImpl(aux[0 .. 0], aux[1 .. 6]); @@ -246,8 +249,8 @@ namespace Microsoft.Quantum.Tests { } } - - operation Pi4YInjectionTest () : Unit { + @Test("QuantumSimulator") + operation TestPi4YInjection() : Unit { using (anc = Qubit[2]) { @@ -266,8 +269,8 @@ namespace Microsoft.Quantum.Tests { } } - - operation Pi4YInjectionAdjointTest () : Unit { + @Test("QuantumSimulator") + operation TestPi4YInjectionAdjoint() : Unit { using (anc = Qubit[2]) { @@ -290,7 +293,8 @@ namespace Microsoft.Quantum.Tests { /// # Summary /// Applies logical operators before and after the encoding circuit, /// that as a whole acts as identity. - operation KDLogicalOperatorTest () : Unit { + @Test("QuantumSimulator") + operation TestKDLogicalOperator() : Unit { using (anc = Qubit[7]) { X(anc[0]); @@ -317,8 +321,8 @@ namespace Microsoft.Quantum.Tests { } } - - operation KDSyndromeTest () : Unit { + @Test("QuantumSimulator") + operation TestKDSyndrome() : Unit { using (anc = Qubit[7]) { @@ -339,8 +343,8 @@ namespace Microsoft.Quantum.Tests { } } - - operation KnillDistillationNoErrorTest () : Unit { + @Test("QuantumSimulator") + operation TestKnillDistillationNoError() : Unit { using (register = Qubit[15]) { @@ -363,7 +367,8 @@ namespace Microsoft.Quantum.Tests { /// Here we do not attempt to correct detected errors, /// since corrections would make the output magic state /// less accurate, compared to post-selection on zero syndrome. - operation KDTest () : Unit { + @Test("QuantumSimulator") + operation TestKD() : Unit { using (rm = Qubit[15]) { ApplyToEach(Ry(PI() / 4.0, _), rm); @@ -446,7 +451,8 @@ namespace Microsoft.Quantum.Tests { /// # Summary /// Ensures that the 7-qubit Steane code can correct an arbitrary /// single-qubit error. - operation SteaneCodeTest () : Unit { + @Test("QuantumSimulator") + operation TestSteaneCode() : Unit { let code = SteaneCode(); let (fnX, fnZ) = SteaneCodeRecoveryFns(); diff --git a/Standard/tests/QuantumPhaseEstimationTests.qs b/Standard/tests/QuantumPhaseEstimationTests.qs index 352839d20c7..e4c9f4e1f9f 100644 --- a/Standard/tests/QuantumPhaseEstimationTests.qs +++ b/Standard/tests/QuantumPhaseEstimationTests.qs @@ -14,7 +14,8 @@ namespace Microsoft.Quantum.Tests { /// Assert that the QuantumPhaseEstimation operation for the T gate /// return 0000 in the controlRegister when targetState is 0 and /// return 0010 when the targetState is 1 - operation QuantumPhaseEstimationTest () : Unit { + @Test("QuantumSimulator") + operation TestQuantumPhaseEstimation() : Unit { let oracle = DiscreteOracle(ApplyTOracle); diff --git a/Standard/tests/QubitizationTests.qs b/Standard/tests/QubitizationTests.qs index ff3f330e267..1e625c7da07 100644 --- a/Standard/tests/QubitizationTests.qs +++ b/Standard/tests/QubitizationTests.qs @@ -25,7 +25,8 @@ namespace Microsoft.Quantum.Tests { } // This checks that BlockEncodingByLCU encodes the correct Hamiltonian. - operation BlockEncodingByLCUTest() : Unit { + @Test("QuantumSimulator") + operation TestBlockEncodingByLCU() : Unit { body (...) { let (eigenvalues, prob, inverseAngle, statePreparation, selector) = LCUTestHelper(); let LCU = BlockEncodingByLCU(statePreparation, selector); @@ -48,7 +49,8 @@ namespace Microsoft.Quantum.Tests { } // This checks that BlockEncodingReflectionByLCU encodes the correct Hamiltonian. - operation BlockEncodingReflectionByLCUTest() : Unit { + @Test("QuantumSimulator") + operation TestBlockEncodingReflectionByLCU() : Unit { body (...) { let (eigenvalues, prob, inverseAngle, statePreparation, selector) = LCUTestHelper(); let LCU = BlockEncodingReflectionByLCU(statePreparation, selector); @@ -74,7 +76,8 @@ namespace Microsoft.Quantum.Tests { } // This checks that QuantumWalkByQubitization encodes the correct Hamiltonian. - operation QuantumWalkByQubitizationTest() : Unit { + @Test("QuantumSimulator") + operation TestQuantumWalkByQubitization() : Unit { body (...) { let (eigenvalues, prob, inverseAngle, statePreparation, selector) = LCUTestHelper(); let LCU = QuantumWalkByQubitization(BlockEncodingReflectionByLCU(statePreparation, selector)); @@ -101,7 +104,8 @@ namespace Microsoft.Quantum.Tests { // QubitizationPauliEvolutionSet.qs tests // This encodes the Hamiltonian (cos^2(angle) I+sin^2(angle) X)/2. - operation PauliBlockEncodingLCUTest() : Unit { + @Test("QuantumSimulator") + operation TestPauliBlockEncodingLCU() : Unit { body (...) { let angle = 0.123; let cosSquared = Cos(angle) * Cos(angle); @@ -135,7 +139,8 @@ namespace Microsoft.Quantum.Tests { } // Array.qs tests - function RangeAsIntArrayTest() : Unit { + @Test("QuantumSimulator") + function TestRangeAsIntArray() : Unit { mutable testCases = new (Int[], Range)[4]; let e = new Int[0]; set testCases w/= 0 <- ([1, 3, 5, 7], 1..2..8); @@ -149,7 +154,8 @@ namespace Microsoft.Quantum.Tests { } } - operation InPlaceMajorityTest() : Unit { + @Test("QuantumSimulator") + operation TestInPlaceMajority() : Unit { body (...) { // Majority function truth table: x;y;z | output let testCases = [[false, false, false, false], @@ -183,7 +189,8 @@ namespace Microsoft.Quantum.Tests { } } - operation ApplyRippleCarryComparatorTest() : Unit{ + @Test("QuantumSimulator") + operation TestApplyRippleCarryComparator() : Unit{ body (...) { let nQubits = 4; let intMax = 2^nQubits-1; diff --git a/Standard/tests/StatePreparationTests.qs b/Standard/tests/StatePreparationTests.qs index 8cb1b5be137..5c37e4f817e 100644 --- a/Standard/tests/StatePreparationTests.qs +++ b/Standard/tests/StatePreparationTests.qs @@ -14,8 +14,8 @@ namespace Microsoft.Quantum.Tests { // number of qubits, abs(amplitude), phase newtype StatePreparationTestCase = (Int, Double[], Double[]); - - operation StatePreparationPositiveCoefficientsTest () : Unit { + @Diag.Test("QuantumSimulator") + operation TestStatePreparationPositiveCoefficients() : Unit { let tolerance = 1E-09; mutable testCases = new StatePreparationTestCase[100]; @@ -74,7 +74,8 @@ namespace Microsoft.Quantum.Tests { // Test phase factor on 1-qubit uniform superposition. - operation StatePreparationComplexCoefficientsQubitPhaseTest () : Unit { + @Diag.Test("QuantumSimulator") + operation TestStatePreparationComplexCoefficientsQubitPhase() : Unit { let tolerance = 1E-09; mutable testCases = new StatePreparationTestCase[10]; @@ -120,7 +121,8 @@ namespace Microsoft.Quantum.Tests { // Test probabilities and phases factor of multi-qubit uniform superposition. - operation StatePreparationComplexCoefficientsMultiQubitPhaseTest () : Unit { + @Diag.Test("QuantumSimulator") + operation TestStatePreparationComplexCoefficientsMultiQubitPhase() : Unit { let tolerance = 1E-09; mutable testCases = new StatePreparationTestCase[10]; @@ -198,7 +200,8 @@ namespace Microsoft.Quantum.Tests { // Test probabilities and phases of arbitrary multi-qubit superposition. - operation StatePreparationComplexCoefficientsArbitraryMultiQubitPhaseTest () : Unit { + @Diag.Test("QuantumSimulator") + operation TestStatePreparationComplexCoefficientsArbitraryMultiQubitPhase() : Unit { let tolerance = 1E-09; mutable testCases = new StatePreparationTestCase[10]; diff --git a/Standard/tests/TypeConversionTests.qs b/Standard/tests/TypeConversionTests.qs index 669d78d7f6d..5c6f7c07f4a 100644 --- a/Standard/tests/TypeConversionTests.qs +++ b/Standard/tests/TypeConversionTests.qs @@ -14,11 +14,13 @@ namespace Microsoft.Quantum.Tests { return op(input); } - operation CallTest() : Unit { + @Test("ToffoliSimulator") + operation TestCall() : Unit { EqualityFactI(Call(Square, 4), 16, "Call failed with Square."); } - operation ToOperationTest() : Unit { + @Test("ToffoliSimulator") + operation TestToOperation() : Unit { let op = FunctionAsOperation(Square); EqualityFactI(ApplyOp(op, 3), 9, "ToOperation failed with Square."); } diff --git a/Standard/tests/UniformSuperpositionPreparationTests.qs b/Standard/tests/UniformSuperpositionPreparationTests.qs index e2c3da7545b..6e1edda3347 100644 --- a/Standard/tests/UniformSuperpositionPreparationTests.qs +++ b/Standard/tests/UniformSuperpositionPreparationTests.qs @@ -11,8 +11,8 @@ namespace Microsoft.Quantum.Tests { open Microsoft.Quantum.Measurement; open Microsoft.Quantum.Arrays; - - operation PrepareUniformSuperpositionTest() : Unit { + @Test("QuantumSimulator") + operation TestPrepareUniformSuperposition() : Unit { body (...) { let nQubits = 5; using(qubits = Qubit[nQubits]) { From 1218ec1f9daf1e98e7d51da7487607c68b76329f Mon Sep 17 00:00:00 2001 From: Andres Paz Date: Fri, 30 Oct 2020 00:54:46 -0700 Subject: [PATCH 13/15] signing for magic (#362) --- Chemistry/src/Jupyter/Jupyter.csproj | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Chemistry/src/Jupyter/Jupyter.csproj b/Chemistry/src/Jupyter/Jupyter.csproj index c949abacfd0..79cd4321aea 100644 --- a/Chemistry/src/Jupyter/Jupyter.csproj +++ b/Chemistry/src/Jupyter/Jupyter.csproj @@ -29,6 +29,10 @@ + + + + From e7fb6ef0534eb27e0055ee3e04f0913f1f300bfa Mon Sep 17 00:00:00 2001 From: Ryan Shaffer Date: Wed, 4 Nov 2020 17:15:37 -0500 Subject: [PATCH 14/15] Build 0.13.2010.2604. (#364) Co-authored-by: Ricardo Espinoza Co-authored-by: Andres Paz --- Build/props/tests.props | 2 +- Chemistry/src/Runtime/Runtime.csproj | 4 ++-- Chemistry/tests/ChemistryTests/QSharpTests.csproj | 2 +- Chemistry/tests/SystemTests/SystemTests.csproj | 2 +- MachineLearning/src/MachineLearning.csproj | 2 +- MachineLearning/tests/MachineLearningTests.csproj | 2 +- Numerics/src/Numerics.csproj | 4 ++-- Numerics/tests/NumericsTests.csproj | 2 +- Standard/src/Standard.csproj | 4 ++-- Standard/tests/Standard.Tests.csproj | 2 +- Visualization/src/Visualization.csproj | 4 ++-- 11 files changed, 15 insertions(+), 15 deletions(-) diff --git a/Build/props/tests.props b/Build/props/tests.props index 93da9885b9e..42d54c268c2 100644 --- a/Build/props/tests.props +++ b/Build/props/tests.props @@ -6,7 +6,7 @@ - + diff --git a/Chemistry/src/Runtime/Runtime.csproj b/Chemistry/src/Runtime/Runtime.csproj index 3c6a82671de..efeb34ff5a0 100644 --- a/Chemistry/src/Runtime/Runtime.csproj +++ b/Chemistry/src/Runtime/Runtime.csproj @@ -1,4 +1,4 @@ - + netstandard2.1 @@ -40,7 +40,7 @@ - + diff --git a/Chemistry/tests/ChemistryTests/QSharpTests.csproj b/Chemistry/tests/ChemistryTests/QSharpTests.csproj index 812d30ef794..fcbb8e7e1dd 100644 --- a/Chemistry/tests/ChemistryTests/QSharpTests.csproj +++ b/Chemistry/tests/ChemistryTests/QSharpTests.csproj @@ -1,4 +1,4 @@ - + diff --git a/Chemistry/tests/SystemTests/SystemTests.csproj b/Chemistry/tests/SystemTests/SystemTests.csproj index 83495463ace..f133cd8fabd 100644 --- a/Chemistry/tests/SystemTests/SystemTests.csproj +++ b/Chemistry/tests/SystemTests/SystemTests.csproj @@ -1,4 +1,4 @@ - + diff --git a/MachineLearning/src/MachineLearning.csproj b/MachineLearning/src/MachineLearning.csproj index 6ffd2451c74..999b34d9ca0 100644 --- a/MachineLearning/src/MachineLearning.csproj +++ b/MachineLearning/src/MachineLearning.csproj @@ -1,4 +1,4 @@ - + netstandard2.1 Microsoft.Quantum.MachineLearning diff --git a/MachineLearning/tests/MachineLearningTests.csproj b/MachineLearning/tests/MachineLearningTests.csproj index d883fd37d5c..fbbc152c906 100644 --- a/MachineLearning/tests/MachineLearningTests.csproj +++ b/MachineLearning/tests/MachineLearningTests.csproj @@ -1,4 +1,4 @@ - + diff --git a/Numerics/src/Numerics.csproj b/Numerics/src/Numerics.csproj index 6a96efeb443..561b715307d 100644 --- a/Numerics/src/Numerics.csproj +++ b/Numerics/src/Numerics.csproj @@ -1,4 +1,4 @@ - + netstandard2.1 @@ -41,7 +41,7 @@ - + diff --git a/Numerics/tests/NumericsTests.csproj b/Numerics/tests/NumericsTests.csproj index 312522abe65..39deb1b2374 100644 --- a/Numerics/tests/NumericsTests.csproj +++ b/Numerics/tests/NumericsTests.csproj @@ -1,4 +1,4 @@ - + diff --git a/Standard/src/Standard.csproj b/Standard/src/Standard.csproj index 17f676aed0f..21410763c29 100644 --- a/Standard/src/Standard.csproj +++ b/Standard/src/Standard.csproj @@ -1,4 +1,4 @@ - + netstandard2.1 @@ -37,7 +37,7 @@ - + diff --git a/Standard/tests/Standard.Tests.csproj b/Standard/tests/Standard.Tests.csproj index c7fdb20e54c..76379e68e2c 100644 --- a/Standard/tests/Standard.Tests.csproj +++ b/Standard/tests/Standard.Tests.csproj @@ -1,4 +1,4 @@ - + diff --git a/Visualization/src/Visualization.csproj b/Visualization/src/Visualization.csproj index 5ad41e9f98d..53f1fbfd2d9 100644 --- a/Visualization/src/Visualization.csproj +++ b/Visualization/src/Visualization.csproj @@ -32,9 +32,9 @@ - + - + From eec61bc3ceac472b84fd5edf93877d987143c2e1 Mon Sep 17 00:00:00 2001 From: bettinaheim <34236215+bettinaheim@users.noreply.github.com> Date: Wed, 4 Nov 2020 21:28:59 -0800 Subject: [PATCH 15/15] Adapting to API update in qsharp-runtime/#370 (#363) --- Build/props/tests.props | 2 +- Chemistry/src/Runtime/Runtime.csproj | 4 +-- .../tests/ChemistryTests/QSharpTests.csproj | 2 +- .../tests/SystemTests/SystemTests.csproj | 2 +- MachineLearning.sln | 31 ++++++++++++++----- MachineLearning/src/MachineLearning.csproj | 2 +- .../tests/MachineLearningTests.csproj | 2 +- Numerics/src/Numerics.csproj | 4 +-- Numerics/tests/NumericsTests.csproj | 2 +- .../Emulation/AllowQubitAllocations.cs | 14 ++++----- .../src/Diagnostics/Emulation/Internal.cs | 2 +- Standard/src/Standard.csproj | 4 +-- Standard/tests/Standard.Tests.csproj | 2 +- Visualization/src/Visualization.csproj | 4 +-- 14 files changed, 47 insertions(+), 30 deletions(-) diff --git a/Build/props/tests.props b/Build/props/tests.props index 42d54c268c2..5cc3d169a4a 100644 --- a/Build/props/tests.props +++ b/Build/props/tests.props @@ -6,7 +6,7 @@ - + diff --git a/Chemistry/src/Runtime/Runtime.csproj b/Chemistry/src/Runtime/Runtime.csproj index efeb34ff5a0..af4bcb22167 100644 --- a/Chemistry/src/Runtime/Runtime.csproj +++ b/Chemistry/src/Runtime/Runtime.csproj @@ -1,4 +1,4 @@ - + netstandard2.1 @@ -40,7 +40,7 @@ - + diff --git a/Chemistry/tests/ChemistryTests/QSharpTests.csproj b/Chemistry/tests/ChemistryTests/QSharpTests.csproj index fcbb8e7e1dd..93341456f6e 100644 --- a/Chemistry/tests/ChemistryTests/QSharpTests.csproj +++ b/Chemistry/tests/ChemistryTests/QSharpTests.csproj @@ -1,4 +1,4 @@ - + diff --git a/Chemistry/tests/SystemTests/SystemTests.csproj b/Chemistry/tests/SystemTests/SystemTests.csproj index f133cd8fabd..fb9aaedeaac 100644 --- a/Chemistry/tests/SystemTests/SystemTests.csproj +++ b/Chemistry/tests/SystemTests/SystemTests.csproj @@ -1,4 +1,4 @@ - + diff --git a/MachineLearning.sln b/MachineLearning.sln index a083c3f402f..adf6e4fcc2c 100644 --- a/MachineLearning.sln +++ b/MachineLearning.sln @@ -1,13 +1,15 @@ ï»ż Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.26124.0 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.30413.136 MinimumVisualStudioVersion = 15.0.26124.0 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "MachineLearning", "MachineLearning", "{D067C787-94C3-4DB8-9012-1F22AE784BEF}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MachineLearningTests", "MachineLearning\tests\MachineLearningTests.csproj", "{94EBDF5F-0A9D-4CE5-9D16-3FF323B8792C}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MachineLearningTests", "MachineLearning\tests\MachineLearningTests.csproj", "{94EBDF5F-0A9D-4CE5-9D16-3FF323B8792C}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MachineLearning", "MachineLearning\src\MachineLearning.csproj", "{B045BF35-6BE6-4982-9618-8725C70D3F91}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MachineLearning", "MachineLearning\src\MachineLearning.csproj", "{B045BF35-6BE6-4982-9618-8725C70D3F91}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Standard", "Standard\src\Standard.csproj", "{9907AAA7-10DA-470B-A154-5A19D1A831E6}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -18,9 +20,6 @@ Global Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {94EBDF5F-0A9D-4CE5-9D16-3FF323B8792C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {94EBDF5F-0A9D-4CE5-9D16-3FF323B8792C}.Debug|Any CPU.Build.0 = Debug|Any CPU @@ -46,9 +45,27 @@ Global {B045BF35-6BE6-4982-9618-8725C70D3F91}.Release|x64.Build.0 = Release|Any CPU {B045BF35-6BE6-4982-9618-8725C70D3F91}.Release|x86.ActiveCfg = Release|Any CPU {B045BF35-6BE6-4982-9618-8725C70D3F91}.Release|x86.Build.0 = Release|Any CPU + {9907AAA7-10DA-470B-A154-5A19D1A831E6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9907AAA7-10DA-470B-A154-5A19D1A831E6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9907AAA7-10DA-470B-A154-5A19D1A831E6}.Debug|x64.ActiveCfg = Debug|Any CPU + {9907AAA7-10DA-470B-A154-5A19D1A831E6}.Debug|x64.Build.0 = Debug|Any CPU + {9907AAA7-10DA-470B-A154-5A19D1A831E6}.Debug|x86.ActiveCfg = Debug|Any CPU + {9907AAA7-10DA-470B-A154-5A19D1A831E6}.Debug|x86.Build.0 = Debug|Any CPU + {9907AAA7-10DA-470B-A154-5A19D1A831E6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9907AAA7-10DA-470B-A154-5A19D1A831E6}.Release|Any CPU.Build.0 = Release|Any CPU + {9907AAA7-10DA-470B-A154-5A19D1A831E6}.Release|x64.ActiveCfg = Release|Any CPU + {9907AAA7-10DA-470B-A154-5A19D1A831E6}.Release|x64.Build.0 = Release|Any CPU + {9907AAA7-10DA-470B-A154-5A19D1A831E6}.Release|x86.ActiveCfg = Release|Any CPU + {9907AAA7-10DA-470B-A154-5A19D1A831E6}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution {94EBDF5F-0A9D-4CE5-9D16-3FF323B8792C} = {D067C787-94C3-4DB8-9012-1F22AE784BEF} {B045BF35-6BE6-4982-9618-8725C70D3F91} = {D067C787-94C3-4DB8-9012-1F22AE784BEF} EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {08B056E4-F7DA-4802-B23C-BB11D6616F5E} + EndGlobalSection EndGlobal diff --git a/MachineLearning/src/MachineLearning.csproj b/MachineLearning/src/MachineLearning.csproj index 999b34d9ca0..5017c5932ff 100644 --- a/MachineLearning/src/MachineLearning.csproj +++ b/MachineLearning/src/MachineLearning.csproj @@ -1,4 +1,4 @@ - + netstandard2.1 Microsoft.Quantum.MachineLearning diff --git a/MachineLearning/tests/MachineLearningTests.csproj b/MachineLearning/tests/MachineLearningTests.csproj index fbbc152c906..871614428cc 100644 --- a/MachineLearning/tests/MachineLearningTests.csproj +++ b/MachineLearning/tests/MachineLearningTests.csproj @@ -1,4 +1,4 @@ - + diff --git a/Numerics/src/Numerics.csproj b/Numerics/src/Numerics.csproj index 561b715307d..ce9c826d092 100644 --- a/Numerics/src/Numerics.csproj +++ b/Numerics/src/Numerics.csproj @@ -1,4 +1,4 @@ - + netstandard2.1 @@ -41,7 +41,7 @@ - + diff --git a/Numerics/tests/NumericsTests.csproj b/Numerics/tests/NumericsTests.csproj index 39deb1b2374..cca28980f6a 100644 --- a/Numerics/tests/NumericsTests.csproj +++ b/Numerics/tests/NumericsTests.csproj @@ -1,4 +1,4 @@ - + diff --git a/Standard/src/Diagnostics/Emulation/AllowQubitAllocations.cs b/Standard/src/Diagnostics/Emulation/AllowQubitAllocations.cs index 65d007010b3..96420b9a0eb 100644 --- a/Standard/src/Diagnostics/Emulation/AllowQubitAllocations.cs +++ b/Standard/src/Diagnostics/Emulation/AllowQubitAllocations.cs @@ -51,17 +51,17 @@ public Native(IOperationFactory m) : base(m) ); } }, - setup: handler => Simulator.OnAllocateQubits += handler, - cleanup: handler => Simulator.OnAllocateQubits -= handler + setup: handler => Simulator.BeforeAllocateQubits += handler, + cleanup: handler => Simulator.BeforeAllocateQubits -= handler ), - new ActionDisposer>>( - register => + new ActionDisposer>( + nQubits => { - nQubitsAllocated -= register.Length; + nQubitsAllocated -= nQubits; }, - setup: handler => Simulator.OnReleaseQubits += handler, - cleanup: handler => Simulator.OnReleaseQubits -= handler + setup: handler => Simulator.AfterReleaseQubits += handler, + cleanup: handler => Simulator.AfterReleaseQubits -= handler ) )); diff --git a/Standard/src/Diagnostics/Emulation/Internal.cs b/Standard/src/Diagnostics/Emulation/Internal.cs index b8c8fef117b..1480f962e37 100644 --- a/Standard/src/Diagnostics/Emulation/Internal.cs +++ b/Standard/src/Diagnostics/Emulation/Internal.cs @@ -33,7 +33,7 @@ public override bool Callback(uint idx, double real, double img) public override bool Dump(IQArray? qubits = null) { - var count = qubits?.Length ?? Simulator.QubitManager!.GetAllocatedQubitsCount(); + var count = qubits?.Length ?? Simulator.QubitManager!.AllocatedQubitsCount; var nQubitsPerRegister = ((int)count / 2); Data = np.empty(new Shape(1 << ((int)count), 2)); var result = base.Dump(qubits); diff --git a/Standard/src/Standard.csproj b/Standard/src/Standard.csproj index 21410763c29..8407e189ef5 100644 --- a/Standard/src/Standard.csproj +++ b/Standard/src/Standard.csproj @@ -1,4 +1,4 @@ - + netstandard2.1 @@ -37,7 +37,7 @@ - + diff --git a/Standard/tests/Standard.Tests.csproj b/Standard/tests/Standard.Tests.csproj index 76379e68e2c..0e9be961006 100644 --- a/Standard/tests/Standard.Tests.csproj +++ b/Standard/tests/Standard.Tests.csproj @@ -1,4 +1,4 @@ - + diff --git a/Visualization/src/Visualization.csproj b/Visualization/src/Visualization.csproj index 53f1fbfd2d9..f148ebf7929 100644 --- a/Visualization/src/Visualization.csproj +++ b/Visualization/src/Visualization.csproj @@ -32,9 +32,9 @@ - + - +