├── .devcontainer └── devcontainer.json ├── .gitattributes ├── .github ├── ISSUE_TEMPLATE │ ├── api_design_proposal.md │ ├── bug_report.md │ ├── config.yml │ └── feature_request.md └── workflows │ ├── devskim.yml │ ├── gh-sync.yml │ ├── qdk-sync.yml │ └── require-api-review.yml ├── .gitignore ├── .pre-commit-config.yaml ├── .sscignore ├── Build ├── assets │ └── qdk-nuget-icon.png ├── build.ps1 ├── check_indents.py ├── e2e.yml ├── manifest.ps1 ├── pack.ps1 ├── props │ └── tests.props ├── set-env.ps1 ├── step-wrap-up.yml ├── steps.yml └── test.ps1 ├── CONTRIBUTING.md ├── Chemistry.sln ├── Chemistry ├── Common │ └── DelaySign.cs ├── README.md ├── src │ ├── DataModel │ │ ├── Analysis │ │ │ └── README.txt │ │ ├── DataModel.csproj │ │ ├── Extensions.cs │ │ ├── Fermion │ │ │ ├── FermionExtensions.cs │ │ │ ├── FermionHamiltonian.cs │ │ │ ├── FermionTerm.cs │ │ │ ├── HermitianFermionTerm.cs │ │ │ ├── JordanWignerEncoding.cs │ │ │ └── Wavefunction │ │ │ │ ├── FermionWavefunctionContainer.cs │ │ │ │ ├── SingleCFWavefunction.cs │ │ │ │ ├── SparseMultiCFWavefunction.cs │ │ │ │ ├── UnitaryCCWavefunction.cs │ │ │ │ └── WavefunctionExtensions.cs │ │ ├── GenericHamiltonian │ │ │ └── Hamiltonian.cs │ │ ├── LadderOperator │ │ │ ├── IndexOrderedSequence.cs │ │ │ ├── LadderOperator.cs │ │ │ ├── LadderOperatorExtensions.cs │ │ │ ├── LadderSequence.cs │ │ │ └── NormalOrderedSequence.cs │ │ ├── OrbitalIntegral │ │ │ ├── Indices.cs │ │ │ ├── OrbitalIntegral.cs │ │ │ ├── OrbitalIntegralExtensions.cs │ │ │ ├── OrbitalIntegralHamiltonian.cs │ │ │ └── SpinOrbital.cs │ │ ├── Paulis │ │ │ ├── PauliHamiltonian.cs │ │ │ ├── PauliTerm.cs │ │ │ └── PauliTermExtensions.cs │ │ ├── ProblemDescription │ │ │ └── ElectronicStructureProblem.cs │ │ ├── Properties │ │ │ └── AssemblyInfo.cs │ │ ├── QSharpFormat │ │ │ ├── QSharpFormatExtensions.cs │ │ │ ├── QSharpFormatFermionWavefunction.cs │ │ │ └── QSharpFormatPauliHamiltonian.cs │ │ ├── Serialization │ │ │ ├── Broombridge │ │ │ │ ├── BroombridgeData.cs │ │ │ │ ├── BroombridgeDataStructurev0.1.cs │ │ │ │ ├── BroombridgeDataStructurev0.2.cs │ │ │ │ ├── BroombridgeDataStructurev0.3.cs │ │ │ │ ├── BroombridgeSerializer.cs │ │ │ │ ├── BroombridgeVersionUpdater.cs │ │ │ │ └── README.md │ │ │ ├── JsonConverters │ │ │ │ ├── FermionWavefunctionJsonConverter.cs │ │ │ │ ├── HamiltonianTermsJsonConverter.cs │ │ │ │ ├── LadderOperatorJsonConverter.cs │ │ │ │ └── LadderSequenceJsonConverter.cs │ │ │ └── LegacyFormats │ │ │ │ ├── FciDump.cs │ │ │ │ └── LiQuiD.cs │ │ ├── SerializationFormats.cs │ │ ├── TermTypes.cs │ │ └── Workflows │ │ │ ├── Convenience.cs │ │ │ └── WorkFlows.cs │ ├── Jupyter │ │ ├── BroombridgeMagic.cs │ │ ├── ChemistryEncodeMagic.cs │ │ ├── FermionHamiltonianMagic.cs │ │ ├── Jupyter.csproj │ │ └── WavefunctionMagic.cs │ ├── Metapackage │ │ └── Metapackage.csproj │ ├── Runtime │ │ ├── JordanWigner │ │ │ ├── Convenience.qs │ │ │ ├── ConvenienceVQE.qs │ │ │ ├── JordanWignerBlockEncoding.qs │ │ │ ├── JordanWignerClusterOperatorEvolutionSet.qs │ │ │ ├── JordanWignerEvolutionSet.qs │ │ │ ├── JordanWignerOptimizedBlockEncoding.qs │ │ │ ├── JordanWignerVQE.qs │ │ │ ├── OptimizedBEOperator.qs │ │ │ ├── StatePreparation.qs │ │ │ └── Utils.qs │ │ ├── Runtime.csproj │ │ └── Utils.qs │ └── Tools │ │ ├── Convert.cs │ │ ├── ExportJW.cs │ │ ├── Extensions.cs │ │ ├── Normalize.cs │ │ ├── Program.cs │ │ ├── README.md │ │ └── Tools.csproj └── tests │ ├── ChemistryTests │ ├── InitialStatePrepTests.qs │ ├── MajoranaOperatorTests.qs │ ├── QSharpTests.csproj │ ├── TestSuiteRunner.cs │ └── UnitaryCoupledClusterTests.qs │ ├── DataModelTests │ ├── ConversionTests │ │ └── OrbitalIntegralToFermionHamiltonianTests.cs │ ├── DataModelTests.csproj │ ├── DocumentationExample.cs │ ├── Extensions.cs │ ├── ExtensionsTest.cs │ ├── FermionTermTests │ │ ├── FermionHamiltonianTests.cs │ │ └── HermitianFermionTermTests.cs │ ├── LadderOperatorTests │ │ └── LadderOperatorTests.cs │ ├── OrbitalIntegralTests │ │ ├── OrbitalIntegralHamiltonianTests.cs │ │ ├── OrbitalIntegralTests.cs │ │ └── SpinOrbitalTests.cs │ ├── SerializationTests │ │ ├── BroombridgeTests.cs │ │ ├── FcidumpTests.cs │ │ ├── IntegrationTests.cs │ │ ├── LiQuiDTests.cs │ │ ├── SerializeFermionTests.cs │ │ ├── SerialzeWavefunctionTests.cs │ │ └── TestFixtures.cs │ ├── TermValueTests │ │ └── TermValueTests.cs │ ├── WavefunctionTests │ │ └── UCCTests.cs │ └── xunit.runner.json │ ├── JupyterTests │ ├── BroombridgeMagicTests.cs │ ├── ChemistryEncodeMagicTests.cs │ ├── FermionHamiltonianMagicTests.cs │ ├── InputStateMagicTests.cs │ ├── JupyterTests.csproj │ ├── MockChannel.cs │ └── sample.py │ ├── README.md │ ├── SamplesTests │ ├── CreateHubbardHamiltonianTests.cs │ ├── DocsInvokingChemistryLibrary.cs │ ├── DocsSecondQuantization.cs │ ├── DocsSimulating.cs │ ├── DocsWavefunction.cs │ ├── MolecularHydrogen.cs │ ├── SamplesTests.csproj │ ├── SimulateHubbardHamiltonianTests.cs │ └── xunit.runner.json │ ├── SystemTests │ ├── Molecules │ │ ├── LithiumHydride │ │ │ └── LithiumHydride.cs │ │ ├── MolecularHydrogen │ │ │ └── Hydrogen.cs │ │ ├── MoleculeTestHelpers.cs │ │ └── MoleculeTestHelpers.qs │ ├── SystemTest.cs │ ├── SystemTest.qs │ ├── SystemTestBlockEncoding.cs │ ├── SystemTestBlockEncoding.qs │ ├── SystemTestOptimizedBlockEncoding.cs │ ├── SystemTestOptimizedBlockEncoding.qs │ ├── SystemTests.csproj │ ├── ToQSharpTest.cs │ └── xunit.runner.json │ └── TestData │ ├── Broombridge │ ├── LiH_0.1.yaml │ ├── LiH_0.2.yaml │ ├── broombridge_v0.1.yaml │ ├── broombridge_v0.2.yaml │ ├── hydrogen_0.1.yaml │ └── hydrogen_0.2.yaml │ ├── FciDump │ ├── README.md │ ├── ethylene_ccpvdz.fcidump │ ├── h2_631g.yaml │ ├── h2_anorccmb.fcidump │ └── h2o_ccpvdz.fcidump │ └── LiQuiD │ └── B_sto6g.dat ├── Design ├── meetings │ ├── 2020 │ │ ├── api-design-2020-07-24.md │ │ ├── api-design-2020-09-10.md │ │ └── api-design-2020-11-05.md │ ├── 2021 │ │ ├── api-design-2021-01-07.md │ │ ├── api-design-2021-02-04.md │ │ ├── api-design-2021-03-04.md │ │ ├── api-design-2021-05-11.md │ │ └── api-design-deep-dive-2021-08-30.md │ └── 2022 │ │ ├── api-design-2022-03.md │ │ ├── api-design-2022-04.md │ │ ├── api-design-2022-05.md │ │ ├── api-design-2022-06.md │ │ └── api-design-2022-07.md └── notes │ ├── environment.yml │ └── sq-clifford-derivations.ipynb ├── Docs ├── README.md └── style-guide.md ├── LICENSE.txt ├── MachineLearning.sln ├── MachineLearning ├── Common │ └── DelaySign.cs ├── src │ ├── Classification.qs │ ├── Datasets │ │ ├── IrisDataset.qs │ │ ├── Properties │ │ │ └── NamespaceInfo.qs │ │ └── WineDataset.qs │ ├── GradientEstimation.qs │ ├── InputEncoding.qs │ ├── MachineLearning.csproj │ ├── Private.qs │ ├── Properties │ │ └── NamespaceInfo.qs │ ├── Structure.qs │ ├── Training.qs │ ├── Types.qs │ └── Validation.qs └── tests │ ├── ClassificationTests.qs │ ├── InputEncodingTests.qs │ ├── MachineLearningTests.csproj │ ├── StructureTests.qs │ ├── TypesTests.qs │ └── ValidationTests.qs ├── Magic.sln ├── NOTICE.txt ├── NuGet.Config ├── Numerics.sln ├── Numerics ├── Common │ └── DelaySign.cs ├── src │ ├── FixedPoint │ │ ├── Addition.qs │ │ ├── Comparison.qs │ │ ├── Convert.qs │ │ ├── Facts.qs │ │ ├── Init.qs │ │ ├── LookupTable.qs │ │ ├── Math.qs │ │ ├── Measurement.qs │ │ ├── Multiplication.qs │ │ ├── Polynomial.qs │ │ ├── Reciprocal.qs │ │ └── Types.qs │ ├── Integer │ │ ├── ArithmeticWrappers.qs │ │ ├── Division.qs │ │ ├── Inversion.qs │ │ ├── Multiplication.qs │ │ └── Types.qs │ └── Numerics.csproj └── tests │ ├── FixedPointTests.qs │ ├── IntegerHighLevelTests.qs │ ├── LookupTableTests.qs │ └── NumericsTests.csproj ├── Python ├── .gitignore ├── qsharp-chemistry │ ├── README.md │ ├── qsharp │ │ ├── chemistry │ │ │ └── __init__.py │ │ └── tests │ │ │ ├── __init__.py │ │ │ ├── broombridge.yaml │ │ │ └── test_chemistry.py │ └── setup.py └── qsharp │ ├── README.md │ └── setup.py ├── README.md ├── SECURITY.md ├── Standard.sln ├── Standard ├── Common │ └── DelaySign.cs ├── README.md ├── src │ ├── AmplitudeAmplification │ │ ├── AmplitudeAmplification.qs │ │ ├── CommonOracles.qs │ │ ├── Convert.qs │ │ ├── Deprecated.qs │ │ ├── Properties │ │ │ └── NamespaceInfo.qs │ │ ├── StandardAlgorithms.qs │ │ └── Types.qs │ ├── Arithmetic │ │ ├── ApplyDual.qs │ │ ├── ApplyReversed.qs │ │ ├── Arithmetic.qs │ │ ├── Asserts.qs │ │ ├── Comparators.qs │ │ ├── Convert.qs │ │ ├── Deprecated.qs │ │ ├── Increment.qs │ │ ├── Integer.qs │ │ ├── Measurement.qs │ │ ├── Modular.qs │ │ ├── Properties │ │ │ ├── BuildConfiguration.qs │ │ │ └── NamespaceInfo.qs │ │ ├── Reflections.qs │ │ ├── Shorthand.qs │ │ └── Types.qs │ ├── Arrays │ │ ├── All.qs │ │ ├── Any.qs │ │ ├── Arrays.qs │ │ ├── Deprecated.qs │ │ ├── DrawMany.qs │ │ ├── Enumeration.qs │ │ ├── EqualA.qs │ │ ├── Filter.qs │ │ ├── Fold.qs │ │ ├── ForEach.cs │ │ ├── Interleaved.qs │ │ ├── Map.qs │ │ ├── Multidimensional.qs │ │ ├── Properties │ │ │ └── NamespaceInfo.qs │ │ ├── Reductions.qs │ │ ├── Search.qs │ │ ├── Sequence.qs │ │ ├── Sorted.qs │ │ ├── Subarray.qs │ │ ├── Unique.qs │ │ ├── Windows.qs │ │ └── Zip.qs │ ├── Bitwise │ │ ├── Bitwise.qs │ │ └── Properties │ │ │ └── NamespaceInfo.qs │ ├── Canon │ │ ├── And.cs │ │ ├── And.qs │ │ ├── Combinators │ │ │ ├── ApplyIf.qs │ │ │ ├── ApplyMultiControlled.qs │ │ │ ├── ApplyRepeatedOver.qs │ │ │ ├── ApplyToArray.qs │ │ │ ├── ApplyToEach.cs │ │ │ ├── ApplyToEach.qs │ │ │ ├── ApplyToEachIndex.qs │ │ │ ├── ApplyToElement.qs │ │ │ ├── ApplyToFirst.qs │ │ │ ├── ApplyToPartition.qs │ │ │ ├── Bind.qs │ │ │ ├── CControlled.qs │ │ │ ├── Compose.qs │ │ │ ├── Curry.qs │ │ │ ├── Delay.qs │ │ │ ├── OperationPow.qs │ │ │ ├── RestrictedToSubregister.qs │ │ │ ├── SinglyControlled.qs │ │ │ ├── Transformed.qs │ │ │ └── With.qs │ │ ├── CommonGates.cs │ │ ├── CommonGates.qs │ │ ├── DataStructures │ │ │ └── Pairs.qs │ │ ├── Deprecated.qs │ │ ├── Enumeration │ │ │ ├── Deprecated.qs │ │ │ └── Trotter.qs │ │ ├── IterateThroughCartesianProduct.qs │ │ ├── Multiplexer.qs │ │ ├── Parity.qs │ │ ├── Properties │ │ │ └── NamespaceInfo.qs │ │ ├── QFT.qs │ │ ├── Range.qs │ │ ├── Registers.qs │ │ ├── Repeat.qs │ │ └── Utils │ │ │ ├── ControlledOnBitString.qs │ │ │ ├── Multiplexer.qs │ │ │ ├── Paulis.qs │ │ │ └── Predicates.qs │ ├── Characterization │ │ ├── Deprecated.qs │ │ ├── Distinguishability.qs │ │ ├── EstimateFrequency.cs │ │ ├── EstimateFrequency.qs │ │ ├── PhaseEstimation │ │ │ ├── Iterative.qs │ │ │ ├── Quantum.qs │ │ │ └── Robust.qs │ │ ├── ProcessTomography.qs │ │ └── Properties │ │ │ └── NamespaceInfo.qs │ ├── Convert │ │ ├── Convert.qs │ │ └── Properties │ │ │ └── NamespaceInfo.qs │ ├── Diagnostics │ │ ├── Allows.qs │ │ ├── Asserts.qs │ │ ├── Deprecated.qs │ │ ├── Dump.qs │ │ ├── Emulation │ │ │ ├── AllowOperationCalls.cs │ │ │ ├── AllowQubitAllocations.cs │ │ │ ├── DataStructures.cs │ │ │ ├── Extensions.cs │ │ │ └── Internal.cs │ │ ├── Facts.qs │ │ ├── Internal.qs │ │ └── Properties │ │ │ └── NamespaceInfo.qs │ ├── Emulation │ │ ├── Math.cs │ │ └── cgmanifest.json │ ├── ErrorCorrection │ │ ├── 5QubitCode.qs │ │ ├── 7QubitCode.qs │ │ ├── BitFlipCode.qs │ │ ├── KnillDistill.qs │ │ ├── Properties │ │ │ └── NamespaceInfo.qs │ │ ├── Types.qs │ │ └── Utils.qs │ ├── Logical │ │ ├── BooleanOperators.qs │ │ ├── Comparisons.qs │ │ ├── Predicates.qs │ │ └── Properties │ │ │ └── NamespaceInfo.qs │ ├── Math │ │ ├── Complex.qs │ │ ├── Constants.qs │ │ ├── Convert.qs │ │ ├── DeprecatedRandom.qs │ │ ├── Functions.qs │ │ ├── Operators.qs │ │ ├── Properties │ │ │ └── NamespaceInfo.qs │ │ ├── Random.qs │ │ └── Types.qs │ ├── Measurement │ │ ├── Properties │ │ │ └── NamespaceInfo.qs │ │ └── Registers.qs │ ├── Optimization │ │ ├── Properties │ │ │ └── NamespaceInfo.qs │ │ └── Univariate.qs │ ├── Oracles │ │ ├── Convert.qs │ │ ├── Properties │ │ │ └── NamespaceInfo.qs │ │ └── Types.qs │ ├── Preparation │ │ ├── Arbitrary.cs │ │ ├── Arbitrary.qs │ │ ├── Deprecated.qs │ │ ├── Mixed.qs │ │ ├── Properties │ │ │ └── NamespaceInfo.qs │ │ ├── QuantumROM.qs │ │ ├── Reference.qs │ │ ├── Types.qs │ │ └── UniformSuperposition.qs │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── Simulation │ │ ├── Algorithms.qs │ │ ├── BlockEncoding.qs │ │ ├── Data │ │ │ └── GeneratorRepresentation.qs │ │ ├── PauliEvolutionSet.qs │ │ ├── Properties │ │ │ └── NamespaceInfo.qs │ │ ├── QubitizationPauliEvolutionSet.qs │ │ ├── Techniques.qs │ │ └── Types.qs │ ├── Standard.csproj │ ├── Synthesis │ │ ├── ControlledOnTruthTable.qs │ │ ├── DecompositionBased.qs │ │ ├── MatrixUtils.cs │ │ ├── Properties │ │ │ └── NamespaceInfo.qs │ │ ├── SingleQubitCliffordGroup │ │ │ ├── Apply.qs │ │ │ ├── Diagnostics.qs │ │ │ ├── GroupProduct.qs │ │ │ └── Types.qs │ │ ├── TransformationBased.qs │ │ ├── Transposition.qs │ │ ├── TwoLevelUnitary.cs │ │ ├── UnitaryDecomposition.cs │ │ └── UnitaryDecomposition.qs │ └── app.config └── tests │ ├── ANDTests.qs │ ├── AmplitudeAmplificationTests.qs │ ├── ApplyMultiControlledTests.qs │ ├── ApplyRepeatedOverTests.qs │ ├── Arithmetic │ └── ReflectionTests.qs │ ├── ArithmeticTests.qs │ ├── ArrayTests.qs │ ├── Arrays │ ├── DrawManyTests.qs │ ├── MapTests.cs │ ├── SortedTests.qs │ └── UniqueTests.qs │ ├── AssertTests.qs │ ├── BitwiseTests.qs │ ├── Canon │ ├── ApplyToEachTests.cs │ ├── Combinators │ │ └── SinglyControlled.qs │ ├── CommonGatesTests.cs │ ├── RepeatTests.qs │ └── Utils │ │ └── ControlledOnBitStringTests.qs │ ├── Characterization │ └── DistinguishabilityTests.qs │ ├── CombinatorTests.qs │ ├── CommonGateTests.qs │ ├── ConversionTests.qs │ ├── Diagnostics │ ├── AllowTests.qs │ ├── DumpTests.cs │ └── DumpTests.qs │ ├── EnumerationTests.qs │ ├── IntegerTests.qs │ ├── Logical │ ├── BooleanTests.qs │ ├── ComparisonTests.qs │ └── PredicateTests.qs │ ├── Math │ ├── BinomialTests.cs │ ├── MathTests.qs │ ├── OperatorFunctionTests.qs │ └── SpecialFunctionTests.qs │ ├── Measurement │ └── ResetTests.qs │ ├── MultiplexerTests.qs │ ├── Optimization │ └── UnivariateTests.qs │ ├── PairTests.qs │ ├── PauliTests.qs │ ├── QFTTests.qs │ ├── QcvvTests.cs │ ├── QcvvTests.qs │ ├── QeccTests.qs │ ├── QuantumPhaseEstimationTests.qs │ ├── QuantumROMTests.qs │ ├── QubitizationTests.qs │ ├── SimulatorTestTargets.cs │ ├── Standard.Tests.csproj │ ├── StatePreparationTests.qs │ ├── Synthesis.qs │ ├── Synthesis │ ├── SingleQubitCliffordTests.qs │ └── UnitaryDecompositionTest.qs │ ├── TypeConversionTests.qs │ └── UniformSuperpositionPreparationTests.qs ├── Visualization ├── Common │ └── DelaySign.cs └── src │ ├── CallSiteEncoders.cs │ ├── DisplayableUnitaryEncoders.cs │ ├── Extensions.cs │ └── Visualization.csproj ├── build.yml ├── global.json └── sync.cmd /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "image": "mcr.microsoft.com/quantum/iqsharp-base:latest", 3 | "containerEnv": { 4 | "IQSHARP_HOSTING_ENVIRONMENT": "libraries-devcontainer" 5 | }, 6 | "extensions": [ 7 | "ms-dotnettools.csharp", 8 | "quantum.quantum-devkit-vscode", 9 | "ms-python.python" 10 | ] 11 | } -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: Kind-Bug 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is, and which package or packages you encountered the bug in. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **System information** 27 | - OS: [e.g. Windows, macOS, or Linux] 28 | - Version of affected NuGet or PyPI package or packages [e.g. [Microsoft.Quantum.Standard](https://www.nuget.org/packages/Microsoft.Quantum.Standard) 0.7.1905.3109] 29 | 30 | **Additional context** 31 | Add any other context about the problem here. 32 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: false 2 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for the Quantum Development Kit libraries 4 | title: '' 5 | labels: Kind-Enhancement 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/workflows/devskim.yml: -------------------------------------------------------------------------------- 1 | name: DevSkim 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | workflow_dispatch: 9 | schedule: 10 | # set schedule to run at 2AM PT on Saturdays 11 | - cron: '0 9 * * Sat' 12 | 13 | jobs: 14 | lint: 15 | name: DevSkim 16 | runs-on: ubuntu-latest 17 | permissions: 18 | actions: read 19 | contents: read 20 | security-events: write 21 | steps: 22 | - name: Checkout code 23 | uses: actions/checkout@v3 24 | 25 | - name: Run DevSkim scanner 26 | uses: microsoft/DevSkim-Action@v1 27 | 28 | - name: Upload DevSkim scan results to GitHub Security tab 29 | uses: github/codeql-action/upload-sarif@v2 30 | with: 31 | sarif_file: devskim-results.sarif 32 | -------------------------------------------------------------------------------- /.github/workflows/gh-sync.yml: -------------------------------------------------------------------------------- 1 | name: Sync GitHub with ADO 2 | 3 | on: 4 | issues: 5 | types: [closed, edited, deleted, reopened, assigned, unassigned, labeled, unlabeled] 6 | issue_comment: 7 | 8 | concurrency: 9 | group: ${{ github.event.issue.number }} 10 | cancel-in-progress: true 11 | 12 | jobs: 13 | sync-issues: 14 | name: Run gh-sync from GitHub action 15 | if: ${{ github.event.label.name == 'tracking' || contains(github.event.issue.labels.*.name, 'tracking') }} 16 | runs-on: ubuntu-latest 17 | steps: 18 | - name: Login to Azure 19 | uses: Azure/login@v1 20 | with: 21 | creds: ${{ secrets.AZURE_CREDENTIALS }} 22 | 23 | - id: AzureKeyVault 24 | uses: Azure/get-keyvault-secrets@v1 25 | with: 26 | keyvault: 'kv-qdk-build' 27 | secrets: 'ghSyncBuildPAT' 28 | 29 | - name: 'Trigger gh-sync' 30 | uses: microsoft/gh-sync@main 31 | with: 32 | ado-organization-url: ${{ secrets.ADO_URL }} 33 | ado-project: ${{ secrets.ADO_PROJECT }} 34 | ado-area-path: ${{ secrets.ADO_AREA_PATH }} 35 | github-repo: 'microsoft/QuantumLibraries' 36 | issue-number: ${{ github.event.issue.number }} 37 | ado-token: ${{ steps.AzureKeyVault.outputs.ghSyncBuildPAT }} 38 | github-token: ${{ secrets.GITHUB_TOKEN }} -------------------------------------------------------------------------------- /.github/workflows/qdk-sync.yml: -------------------------------------------------------------------------------- 1 | name: Sync QDK repos 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | 8 | jobs: 9 | sync-repos: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - name: Login to Azure 13 | uses: Azure/login@v1 14 | with: 15 | creds: ${{ secrets.AZURE_CREDENTIALS }} 16 | 17 | - id: AzureKeyVault 18 | uses: Azure/get-keyvault-secrets@v1 19 | with: 20 | keyvault: 'kv-qdk-build' 21 | secrets: 'qdkBuildPAT' 22 | 23 | - name: 'Trigger QDK sync build' 24 | uses: Azure/pipelines@releases/v1 25 | with: 26 | azure-devops-project-url: 'https://dev.azure.com/ms-quantum-public/Microsoft Quantum (public)' 27 | azure-pipeline-name: 'microsoft.qdk.sync' 28 | azure-devops-token: ${{ steps.AzureKeyVault.outputs.qdkBuildPAT }} 29 | -------------------------------------------------------------------------------- /.github/workflows/require-api-review.yml: -------------------------------------------------------------------------------- 1 | name: Require API Review 2 | 3 | on: 4 | pull_request: 5 | types: [labeled, unlabeled, opened, edited, synchronize] 6 | jobs: 7 | enforce-label: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: yogevbd/enforce-label-action@2.1.0 11 | with: 12 | BANNED_LABELS: "Status-NeedsAPIReview" 13 | BANNED_LABELS_DESCRIPTION: "PR blocked until required API review is completed. Please see https://aka.ms/qsharp-api-process." 14 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: https://github.com/pre-commit/pre-commit-hooks 3 | rev: v1.2.3 4 | hooks: 5 | - id: trailing-whitespace 6 | args: [--markdown-linebreak-ext=md] 7 | - id: no-commit-to-branch 8 | args: [-b, "main"] 9 | - id: check-yaml 10 | - repo: local 11 | hooks: 12 | - id: check_indents 13 | name: check_indents 14 | entry: python Build/check_indents.py 15 | language: system 16 | -------------------------------------------------------------------------------- /.sscignore: -------------------------------------------------------------------------------- 1 | { 2 | "cfs": ["CFS0012", "CFS0013"] 3 | } 4 | -------------------------------------------------------------------------------- /Build/assets/qdk-nuget-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoft/QuantumLibraries/f2f5e380225367ee4eb995d922067025dc77f0a0/Build/assets/qdk-nuget-icon.png -------------------------------------------------------------------------------- /Build/build.ps1: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. All rights reserved. 2 | # Licensed under the MIT License. 3 | 4 | $ErrorActionPreference = 'Stop' 5 | 6 | & "$PSScriptRoot/set-env.ps1" 7 | $all_ok = $True 8 | 9 | function Build-One { 10 | param( 11 | [string]$action, 12 | [string]$project 13 | ); 14 | 15 | dotnet $action (Join-Path $PSScriptRoot $project) ` 16 | -c $Env:BUILD_CONFIGURATION ` 17 | -v $Env:BUILD_VERBOSITY ` 18 | /property:DefineConstants=$Env:ASSEMBLY_CONSTANTS ` 19 | /property:Version=$Env:ASSEMBLY_VERSION ` 20 | /property:QsharpDocsOutputPath=$Env:DOCS_OUTDIR 21 | 22 | if ($LastExitCode -ne 0) { 23 | Write-Host "##vso[task.logissue type=error;]Failed to build $project." 24 | $script:all_ok = $False 25 | } 26 | } 27 | 28 | Write-Host "##[info]Build Standard library" 29 | Build-One 'publish' '../Standard.sln' 30 | 31 | Write-Host "##[info]Build Chemistry library" 32 | Build-One 'publish' '../Chemistry.sln' 33 | 34 | Write-Host "##[info]Build Numerics library" 35 | Build-One 'publish' '../Numerics.sln' 36 | 37 | Write-Host "##[info]Build QML library" 38 | Build-One 'publish' '../MachineLearning.sln' 39 | 40 | Write-Host "##[info]Build Jupyter magic library" 41 | Build-One 'publish' '../Magic.sln' 42 | 43 | if (-not $all_ok) { 44 | throw "At least one test failed execution. Check the logs." 45 | } -------------------------------------------------------------------------------- /Build/check_indents.py: -------------------------------------------------------------------------------- 1 | #!/bin/env python 2 | # -*- coding: utf-8 -*- 3 | ## 4 | # check_indents.py: If a file has both space and tab indenting, returns an exit 5 | # code and normalizes \t to four spaces. 6 | ## 7 | # Copyright (c) Microsoft Corporation. All rights reserved. 8 | # Licensed under the MIT License. 9 | ## 10 | 11 | import re 12 | from typing import Tuple 13 | 14 | def find_whitespace(string : str) -> Tuple[str, str]: 15 | groups = re.match(r'(\s*)([^\s].*$)?', string, flags=re.S).groups() 16 | return groups[0], groups[1] or '' 17 | 18 | def check_file(filename : str) -> bool: 19 | """ 20 | Checks a single file, returning True and writing a cleaned file if a mix 21 | of tabs and spaces was found. 22 | """ 23 | problem_found = False 24 | found_spaces = False 25 | found_tabs = False 26 | 27 | with open(filename, 'r', encoding='utf-8') as f: 28 | contents = list(f.readlines()) 29 | 30 | for line in contents: 31 | # Find the leading whitespace. 32 | whitespace, rest = find_whitespace(line) 33 | found_spaces = found_spaces or (' ' in whitespace) 34 | found_tabs = found_tabs or ('\t' in whitespace) 35 | 36 | problem_found = found_spaces and found_tabs 37 | 38 | if problem_found: 39 | print(f"Found mixed spaces and tabs in {filename}.") 40 | # Time to normalize! 41 | with open(filename, 'w', encoding='utf-8') as f: 42 | f.writelines( 43 | whitespace.replace('\t', ' ') + rest 44 | for whitespace, rest in map(find_whitespace, contents) 45 | ) 46 | 47 | return problem_found 48 | 49 | if __name__ == "__main__": 50 | import sys 51 | filenames = sys.argv[1:] 52 | exit_code = 0 53 | 54 | for filename in filenames: 55 | if check_file(filename): 56 | exit_code = -1 57 | 58 | sys.exit(exit_code) 59 | -------------------------------------------------------------------------------- /Build/e2e.yml: -------------------------------------------------------------------------------- 1 | name: $(Build.Major).$(Build.Minor).$(BuildId) 2 | 3 | parameters: 4 | - name: validation_level 5 | displayName: Validation Level 6 | type: string 7 | default: normal 8 | values: 9 | - minimal 10 | - normal 11 | - full 12 | 13 | trigger: none 14 | 15 | pr: 16 | - main 17 | - feature/* 18 | - features/* 19 | - release/* 20 | 21 | resources: 22 | repositories: 23 | - repository: qdk 24 | type: github 25 | endpoint: github 26 | name: microsoft/qdk 27 | ref: refs/heads/main 28 | 29 | extends: 30 | template: build/qdk-module-e2e.yml@qdk 31 | parameters: 32 | module: QuantumLibraries 33 | validation_level: ${{ parameters.validation_level }} 34 | -------------------------------------------------------------------------------- /Build/props/tests.props: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | false 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /Build/set-env.ps1: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. All rights reserved. 2 | # Licensed under the MIT License. 3 | 4 | $ErrorActionPreference = 'Stop' 5 | 6 | Write-Host "Setting up build environment variables" 7 | 8 | If ($Env:BUILD_BUILDNUMBER -eq $null) { $Env:BUILD_BUILDNUMBER ="0.0.1.0" } 9 | If ($Env:BUILD_CONFIGURATION -eq $null) { $Env:BUILD_CONFIGURATION ="Debug" } 10 | If ($Env:BUILD_VERBOSITY -eq $null) { $Env:BUILD_VERBOSITY ="m" } 11 | If ($Env:ASSEMBLY_VERSION -eq $null) { $Env:ASSEMBLY_VERSION ="$Env:BUILD_BUILDNUMBER" } 12 | If ($Env:NUGET_VERSION -eq $null) { $Env:NUGET_VERSION ="$Env:ASSEMBLY_VERSION-alpha" } 13 | 14 | If ($Env:DROPS_DIR -eq $null) { $Env:DROPS_DIR = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot "..\drops")) } 15 | 16 | If ($Env:NUGET_OUTDIR -eq $null) { $Env:NUGET_OUTDIR = (Join-Path $Env:DROPS_DIR "nugets") } 17 | If (-not (Test-Path -Path $Env:NUGET_OUTDIR)) { [IO.Directory]::CreateDirectory($Env:NUGET_OUTDIR) } 18 | 19 | If ($Env:DOCS_OUTDIR -eq $null) { $Env:DOCS_OUTDIR = (Join-Path $Env:DROPS_DIR "docs") } 20 | If (-not (Test-Path -Path $Env:DOCS_OUTDIR)) { [IO.Directory]::CreateDirectory($Env:DOCS_OUTDIR) } 21 | 22 | -------------------------------------------------------------------------------- /Build/step-wrap-up.yml: -------------------------------------------------------------------------------- 1 | ## 2 | # Wrap-up: copy files to artifacts directory and publish 3 | ## 4 | 5 | steps: 6 | - task: PublishTestResults@2 7 | displayName: 'Publish tests results' 8 | condition: succeededOrFailed() 9 | inputs: 10 | testResultsFormat: VSTest 11 | testResultsFiles: '$(System.DefaultWorkingDirectory)/**/*.trx' 12 | testRunTitle: 'Q# Libraries tests' 13 | 14 | - task: PublishSymbols@1 15 | displayName: 'Publish symbols' 16 | condition: and(succeeded(), eq(variables['Agent.OS'], 'Windows_NT')) 17 | inputs: 18 | SearchPattern: '$(System.DefaultWorkingDirectory)/src/**/*.pdb' 19 | 20 | - pwsh: ./manifest.ps1 21 | displayName: "List built assemblies" 22 | workingDirectory: $(System.DefaultWorkingDirectory)/Build 23 | condition: succeededOrFailed() 24 | 25 | - task: PublishBuildArtifacts@1 26 | displayName: 'Publish Artifact: qsharp-runtime' 27 | condition: succeededOrFailed() 28 | inputs: 29 | PathtoPublish: '$(Build.ArtifactStagingDirectory)' 30 | artifactName: QuantumLibraries 31 | 32 | 33 | -------------------------------------------------------------------------------- /Build/steps.yml: -------------------------------------------------------------------------------- 1 | steps: 2 | 3 | - task: UseDotNet@2 4 | displayName: 'Use .NET Core SDK 6.0.x' 5 | inputs: 6 | packageType: sdk 7 | version: '6.0.x' 8 | 9 | 10 | - task: UsePythonVersion@0 11 | inputs: 12 | versionSpec: '3.7' 13 | architecture: 'x64' 14 | displayName: 'Select Python version' 15 | condition: and(succeeded(), ne(variables['Enable.Python'], 'false')) 16 | continueOnError: true 17 | 18 | - script: pip install setuptools wheel pytest 19 | displayName: 'Install Python tools' 20 | condition: and(succeeded(), ne(variables['Enable.Python'], 'false')) 21 | 22 | 23 | - powershell: ./build.ps1 24 | displayName: "Building" 25 | workingDirectory: $(System.DefaultWorkingDirectory)/Build 26 | 27 | 28 | - powershell: ./test.ps1 29 | displayName: "Testing" 30 | workingDirectory: $(System.DefaultWorkingDirectory)/Build 31 | condition: and(succeeded(), ne(variables['Skip.Tests'], 'true')) 32 | 33 | 34 | - powershell: ./pack.ps1 35 | displayName: "Pack" 36 | workingDirectory: $(System.DefaultWorkingDirectory)/Build 37 | 38 | 39 | - pwsh: .\manifest.ps1 40 | displayName: "List built packages & assemblies" 41 | workingDirectory: '$(System.DefaultWorkingDirectory)/Build' 42 | condition: succeededOrFailed() 43 | 44 | 45 | - template: step-wrap-up.yml 46 | -------------------------------------------------------------------------------- /Build/test.ps1: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. All rights reserved. 2 | # Licensed under the MIT License. 3 | 4 | $ErrorActionPreference = 'Stop' 5 | 6 | & "$PSScriptRoot/set-env.ps1" 7 | $all_ok = $True 8 | 9 | function Test-One { 10 | Param($project) 11 | 12 | dotnet test (Join-Path $PSScriptRoot $project) ` 13 | -c $Env:BUILD_CONFIGURATION ` 14 | -v $Env:BUILD_VERBOSITY ` 15 | --logger trx ` 16 | /property:DefineConstants=$Env:ASSEMBLY_CONSTANTS ` 17 | /property:Version=$Env:ASSEMBLY_VERSION 18 | 19 | if ($LastExitCode -ne 0) { 20 | Write-Host "##vso[task.logissue type=error;]Failed to test $project." 21 | $script:all_ok = $False 22 | } 23 | } 24 | 25 | Write-Host "##[info]Testing Standard/tests/Standard.Tests.csproj" 26 | Test-One '../Standard/tests/Standard.Tests.csproj' 27 | 28 | Write-Host "##[info]Testing Chemistry/tests/ChemistryTests/QSharpTests.csproj" 29 | Test-One '../Chemistry/tests/ChemistryTests/QSharpTests.csproj' 30 | 31 | Write-Host "##[info]Testing Chemistry/tests/SystemTests/SystemTests.csproj" 32 | Test-One '../Chemistry/tests/SystemTests/SystemTests.csproj' 33 | 34 | Write-Host "##[info]Testing Chemistry/tests/DataModelTests/DataModelTests.csproj" 35 | Test-One '../Chemistry/tests/DataModelTests/DataModelTests.csproj' 36 | 37 | Write-Host "##[info]Testing Chemistry/tests/JupyterTests/JupyterTests.csproj" 38 | Test-One '../Chemistry/tests/JupyterTests/JupyterTests.csproj' 39 | 40 | Write-Host "##[info]Testing Numerics/tests/NumericsTests.csproj" 41 | Test-One '../Numerics/tests/NumericsTests.csproj' 42 | 43 | if (-not $all_ok) { 44 | throw "At least one test failed execution. Check the logs." 45 | } 46 | -------------------------------------------------------------------------------- /Chemistry/Common/DelaySign.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | 3 | // Attributes for delay-signing 4 | #if SIGNED 5 | [assembly:AssemblyKeyFile("..\\..\\..\\Build\\267DevDivSNKey2048.snk")] 6 | [assembly:AssemblyDelaySign(true)] 7 | #endif 8 | 9 | internal static class SigningConstants 10 | { 11 | #if SIGNED 12 | public const string PUBLIC_KEY = ", PublicKey=" + 13 | "002400000c800000140100000602000000240000525341310008000001000100613399aff18ef1" + 14 | "a2c2514a273a42d9042b72321f1757102df9ebada69923e2738406c21e5b801552ab8d200a65a2" + 15 | "35e001ac9adc25f2d811eb09496a4c6a59d4619589c69f5baf0c4179a47311d92555cd006acc8b" + 16 | "5959f2bd6e10e360c34537a1d266da8085856583c85d81da7f3ec01ed9564c58d93d713cd0172c" + 17 | "8e23a10f0239b80c96b07736f5d8b022542a4e74251a5f432824318b3539a5a087f8e53d2f135f" + 18 | "9ca47f3bb2e10aff0af0849504fb7cea3ff192dc8de0edad64c68efde34c56d302ad55fd6e80f3" + 19 | "02d5efcdeae953658d3452561b5f36c542efdbdd9f888538d374cef106acf7d93a4445c3c73cd9" + 20 | "11f0571aaf3d54da12b11ddec375b3"; 21 | #else 22 | public const string PUBLIC_KEY = ""; 23 | #endif 24 | } 25 | -------------------------------------------------------------------------------- /Chemistry/README.md: -------------------------------------------------------------------------------- 1 | # Microsoft Quantum Chemistry Library # 2 | 3 | This folder contains the C# and Q# sources used to implement the [Microsoft Quantum Chemistry library](https://docs.microsoft.com/azure/quantum/user-guide/libraries/chemistry). 4 | 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). 5 | 6 | ## Building and testing ## 7 | 8 | The quantum chemistry library consists of two cross-platform project built using [.NET Core](https://docs.microsoft.com/en-us/dotnet/core/): 9 | 10 | - [**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. 11 | - [**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. 12 | 13 | Once .NET Core is installed, you may build and run its tests by executing the following from a command line: 14 | 15 | ```bash 16 | dotnet test tests 17 | ``` 18 | 19 | For more details about creating and running tests in Q#, 20 | see the [Testing and debugging](https://docs.microsoft.com/azure/quantum/user-guide/testing-debugging) 21 | section of the [developer's guide](https://docs.microsoft.com/azure/quantum). 22 | -------------------------------------------------------------------------------- /Chemistry/src/DataModel/Analysis/README.txt: -------------------------------------------------------------------------------- 1 | Placeholder folder for Hamiltonian analysis routines. -------------------------------------------------------------------------------- /Chemistry/src/DataModel/Fermion/FermionHamiltonian.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using Microsoft.Quantum.Chemistry.Generic; 7 | 8 | namespace Microsoft.Quantum.Chemistry.Fermion 9 | { 10 | public partial class FermionHamiltonian : Hamiltonian 11 | { 12 | public FermionHamiltonian() : base() { } 13 | 14 | /// 15 | /// Method for collecting all distinct system (orbital) indices. 16 | /// 17 | /// Collate orbital indices from this orbital integral. 18 | public override void AddToSystemIndices(HermitianFermionTerm index) 19 | { 20 | foreach (var idx in index.Sequence) 21 | { 22 | SystemIndices.Add(idx.Index); 23 | } 24 | } 25 | } 26 | 27 | } -------------------------------------------------------------------------------- /Chemistry/src/DataModel/Fermion/Wavefunction/UnitaryCCWavefunction.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | using System; 5 | using System.Numerics; 6 | using System.Linq; 7 | using System.Collections.Generic; 8 | using Microsoft.Quantum.Chemistry.LadderOperators; 9 | using Microsoft.Quantum.Chemistry.OrbitalIntegrals; 10 | 11 | namespace Microsoft.Quantum.Chemistry.Fermion 12 | { 13 | // For now, UCC is a subclass of MCF. It should eventually be a Hamiltonian 14 | // + a WavefunctionSCF. 15 | // 16 | public class UnitaryCCWavefunction : SparseMultiCFWavefunction 17 | where TIndex : IEquatable, IComparable 18 | { 19 | public UnitaryCCWavefunction() : base() { } 20 | 21 | /// 22 | /// Changes the indexing scheme of this instance. 23 | /// 24 | /// Type of the new indexing scheme. 25 | /// Function for mapping the current scheme to the new scheme. 26 | /// Instance with a new index type. 27 | public UnitaryCCWavefunction SelectIndex(Func indexFunction) 28 | where TNewIndex : IEquatable, IComparable 29 | => new UnitaryCCWavefunction() 30 | { 31 | // Be sure to propagate any change in the ladder operators to the coefficient. 32 | Reference = this.Reference.SelectIndex(indexFunction), 33 | Excitations = this.Excitations 34 | .ToDictionary(kv => new IndexOrderedSequence( 35 | kv.Key.SelectIndex(indexFunction).Sequence, 1), kv => kv.Value * (double)kv.Key.Coefficient) 36 | }; 37 | } 38 | 39 | } 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /Chemistry/src/DataModel/Paulis/PauliHamiltonian.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Quantum.Chemistry.Generic; 5 | 6 | namespace Microsoft.Quantum.Chemistry.Paulis 7 | { 8 | 9 | /// 10 | /// 11 | /// Jordan–Wigner representation of a general fermion Hamiltonian . 12 | /// This representation may only be created from instances of , 13 | /// and stores term data in a format suitable for consumption by Q#, 14 | /// and optimized for a product formula Hamiltonian simulation algorithm. 15 | /// 16 | /// 17 | /// This supports the following : 18 | /// , 19 | /// , 20 | /// , 21 | /// , 22 | /// , 23 | /// . 24 | /// 25 | /// 26 | /// Some optimizations are performed: 27 | /// 28 | /// PQQP and PP terms are merged where needed. 29 | /// PQQR and PR terms are merged where possible. 30 | /// 31 | /// All PQRS terms with the same set of spin-orbital indices are performed simultaneously, 32 | /// and only the XXXX, XXYY, XYXY, YXXY, YYYY, YYXX, YXYX, XYYX terms are only performed as 33 | /// needed. 34 | /// 35 | /// Terms in each group of term types are applied in lexicographic ordering. 36 | /// 37 | /// 38 | /// 39 | public class PauliHamiltonian : Hamiltonian 40 | { 41 | public PauliHamiltonian() : base() { } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Chemistry/src/DataModel/Paulis/PauliTermExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | using System.Collections.Generic; 5 | 6 | 7 | namespace Microsoft.Quantum.Chemistry.Paulis 8 | { 9 | 10 | /// 11 | /// Extensions For Pauli objects. 12 | /// 13 | public static class Extensions 14 | { 15 | /// 16 | /// Construct PauliTTermValue that implements the ITermValue interface. 17 | /// 18 | /// Input double. 19 | /// PauliTTermValue representing the input double. 20 | public static PauliTermValue ToPauliTTermValue(this double x) 21 | { 22 | return new PauliTermValue(x); 23 | } 24 | 25 | /// 26 | /// Construct PauliTTermValue that implements the ITermValue interface. 27 | /// 28 | /// Input double sequence. 29 | /// PauliTTermValue representing the input double sequence. 30 | public static PauliTermValue ToPauliTTermValue(this IEnumerable x) 31 | { 32 | return new PauliTermValue(x); 33 | } 34 | } 35 | } 36 | 37 | -------------------------------------------------------------------------------- /Chemistry/src/DataModel/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.CompilerServices; 2 | 3 | [assembly: InternalsVisibleTo("Microsoft.Quantum.Chemistry.Tests.CSharp" + SigningConstants.PUBLIC_KEY)] 4 | -------------------------------------------------------------------------------- /Chemistry/src/DataModel/Serialization/Broombridge/README.md: -------------------------------------------------------------------------------- 1 | # Broombridge Serialization Design 2 | 3 | The C# files in this folder implement serialization and deserialization for Broombridge files, using the YamlDotNet package. 4 | In particular, the data model used for loading from and saving to YAML is implemented by the `BroombridgeDataStructuresv0.1.cs` and `BroombridgeDataStructuresv0.2.cs` files. 5 | These files define internal classes for use with YamlDotNet, and that then get converted into instances of the public `ElectronicStructureProblem` classes. 6 | For compatibility with earlier versions of Broombridge, these files include full data models for historical Broombridge versions; where newer versions have not modified data structures, data models for later versions may have properties whose types are associated with earlier versions. 7 | For instance, the `basis_set` property in Broombridge 0.2 is the same as it was in 0.1, such that the 0.2 `ProblemDescription` class has a `BasisSet` property whose type is `V0_1.BasisSet`. 8 | 9 | > **NOTE**: These classes are designed for internal use only, but are marked as `public` to make them available to Python interoperability. 10 | 11 | This separation prevents users from depending on the exact details of how electronic structure problems are represented in each version of Broombridge, focusing instead on the _logical_ structure of problems once deserialized. 12 | -------------------------------------------------------------------------------- /Chemistry/src/DataModel/SerializationFormats.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Chemistry 5 | { 6 | public enum SerializationFormat 7 | { 8 | Broombridge, 9 | LiQuiD, 10 | FciDump 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Chemistry/src/Jupyter/BroombridgeMagic.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Jupyter.Core; 2 | using System.Threading.Tasks; 3 | using Microsoft.Quantum.Chemistry.Broombridge; 4 | 5 | namespace Microsoft.Quantum.Chemistry.Magic 6 | { 7 | /// 8 | /// Jupyter Magic that loads and returns 9 | /// Broombridge electronic structure problem representation from a given .yaml file. 10 | /// 11 | public class BroombridgeMagic : MagicSymbol 12 | { 13 | /// 14 | /// Default constructor. 15 | /// 16 | public BroombridgeMagic() 17 | { 18 | this.Name = $"%chemistry.broombridge"; 19 | this.Documentation = new Microsoft.Jupyter.Core.Documentation() { Summary = "Loads and returns Broombridge electronic structure problem representation from a given .yaml file." }; 20 | this.Kind = SymbolKind.Magic; 21 | this.Execute = this.Run; 22 | } 23 | 24 | /// 25 | /// Loads the broombridge data from the given .yaml file and returns it. 26 | /// 27 | public Task Run(string input, IChannel channel) 28 | { 29 | if (string.IsNullOrWhiteSpace(input)) 30 | { 31 | channel.Stderr("Please provide the name of a broombridge file to load\n"); 32 | return Task.FromResult(ExecuteStatus.Error.ToExecutionResult()); 33 | } 34 | 35 | var yamlData = Deserializers.DeserializeBroombridge(input).Raw; 36 | return Task.FromResult(yamlData.ToExecutionResult()); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Chemistry/src/Jupyter/Jupyter.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | net6.0 4 | x64 5 | Microsoft.Quantum.Chemistry.Jupyter 6 | 7 | 8 | 9 | Microsoft 10 | Microsoft's Quantum Chemistry Libraries Jupyter integration. 11 | © Microsoft Corporation. All rights reserved. 12 | See: https://docs.microsoft.com/azure/quantum/qdk-relnotes/ 13 | https://github.com/microsoft/QuantumLibraries/raw/main/LICENSE.txt 14 | https://github.com/microsoft/QuantumLibraries/tree/main/Chemistry 15 | qdk-nuget-icon.png 16 | Quantum Q# Qsharp Jupyter 17 | 1591 18 | true 19 | true 20 | true 21 | true 22 | snupkg 23 | $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb;.xml 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /Chemistry/src/Metapackage/Metapackage.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | x64 6 | Microsoft.Quantum.Chemistry.Metapackage 7 | 8 | 9 | 10 | Microsoft 11 | Microsoft's Quantum Chemistry Libraries. 12 | © Microsoft Corporation. All rights reserved. 13 | Microsoft.Quantum.Chemistry 14 | See: https://docs.microsoft.com/azure/quantum/qdk-relnotes/ 15 | MIT 16 | https://github.com/microsoft/QuantumLibraries/tree/main/Chemistry 17 | qdk-nuget-icon.png 18 | Quantum Q# Qsharp 19 | 1591 20 | true 21 | true 22 | true 23 | false 24 | false 25 | snupkg 26 | $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb;.xml 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /Chemistry/src/Runtime/JordanWigner/Utils.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Chemistry.JordanWigner { 5 | open Microsoft.Quantum.Intrinsic; 6 | open Microsoft.Quantum.Canon; 7 | open Microsoft.Quantum.Chemistry; 8 | 9 | 10 | /// # Summary 11 | /// Format of data passed from C# to Q# to represent terms of the Hamiltonian. 12 | /// The meaning of the data represented is determined by the algorithm that receives it. 13 | newtype JWOptimizedHTerms = (HTerm[], HTerm[], HTerm[], HTerm[]); 14 | 15 | /// # Summary 16 | /// Format of data passed from C# to Q# to represent preparation of the initial state 17 | /// The meaning of the data represented is determined by the algorithm that receives it. 18 | newtype JordanWignerInputState = ((Double, Double), Int[]); 19 | 20 | /// # Summary 21 | /// Format of data passed from C# to Q# to represent all information for Hamiltonian simulation. 22 | /// The meaning of the data represented is determined by the algorithm that receives it. 23 | newtype JordanWignerEncodingData = (Int, JWOptimizedHTerms, (Int, JordanWignerInputState[]), Double); 24 | 25 | } 26 | 27 | 28 | -------------------------------------------------------------------------------- /Chemistry/src/Tools/Extensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using System; 5 | using System.CommandLine; 6 | using System.CommandLine.Invocation; 7 | using System.Collections.Generic; 8 | 9 | using Broombridge = Microsoft.Quantum.Chemistry.Broombridge; 10 | 11 | namespace Microsoft.Quantum.Chemistry.Tools 12 | { 13 | public static class Extensions 14 | { 15 | public static Command WithHandler(this Command command, ICommandHandler handler) 16 | { 17 | command.Handler = handler; 18 | return command; 19 | } 20 | 21 | public static Command WithHandler(this Command command, Action handler) => 22 | command.WithHandler(CommandHandler.Create(handler)); 23 | 24 | public static Command WithHandler(this Command command, Action handler) => 25 | command.WithHandler(CommandHandler.Create(handler)); 26 | 27 | public static Command WithHandler(this Command command, Action handler) => 28 | command.WithHandler(CommandHandler.Create(handler)); 29 | 30 | public static Command WithHandler(this Command command, Action handler) => 31 | command.WithHandler(CommandHandler.Create(handler)); 32 | 33 | public static Command WithHandler(this Command command, Action handler) => 34 | command.WithHandler(CommandHandler.Create(handler)); 35 | 36 | public static Command WithDescription(this Command command, string description) 37 | { 38 | command.Description = description; 39 | return command; 40 | } 41 | } 42 | } 43 | 44 | -------------------------------------------------------------------------------- /Chemistry/src/Tools/Program.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #nullable enable 5 | 6 | using Microsoft.Extensions.Configuration; 7 | using Microsoft.Extensions.Logging; 8 | using System.Collections.Generic; 9 | using System.Linq; 10 | using System.Threading.Tasks; 11 | using System.CommandLine; 12 | using System.CommandLine.Invocation; 13 | using System.IO; 14 | using System; 15 | 16 | namespace Microsoft.Quantum.Chemistry.Tools 17 | { 18 | 19 | public class Program 20 | { 21 | 22 | public static Command CreateRootCommand() => 23 | new RootCommand 24 | { 25 | Convert.CreateCommand(), 26 | Normalize.CreateCommand(), 27 | ExportJW.CreateCommand() 28 | } 29 | .WithDescription("Tools for working with quantum chemistry data."); 30 | 31 | public static async Task Main(string[] args) => 32 | await CreateRootCommand().InvokeAsync(args); 33 | 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Chemistry/src/Tools/Tools.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | x64 6 | net6.0 7 | Microsoft.Quantum.Chemistry.Tools 8 | qdk-chem 9 | enable 10 | 11 | 12 | 13 | 0162 14 | Microsoft 15 | Tools for working with quantum chemistry data. 16 | © Microsoft Corporation. All rights reserved. 17 | See: https://docs.microsoft.com/azure/quantum/qdk-relnotes/ 18 | MIT 19 | https://github.com/microsoft/quantumlibraries 20 | qdk-nuget-icon.png 21 | Quantum Q# Qsharp 22 | true 23 | qdk-chem 24 | Microsoft.Quantum.Chemistry.Tools 25 | \ 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /Chemistry/tests/ChemistryTests/QSharpTests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | net6.0 7 | false 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /Chemistry/tests/ChemistryTests/TestSuiteRunner.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Quantum.Simulation.XUnit; 5 | using Microsoft.Quantum.Simulation.Simulators; 6 | using Xunit.Abstractions; 7 | using System.Diagnostics; 8 | 9 | namespace Microsoft.Quantum.Chemistry.Tests 10 | { 11 | public class TestSuiteRunner 12 | { 13 | private readonly ITestOutputHelper output; 14 | 15 | public TestSuiteRunner(ITestOutputHelper output) 16 | { 17 | this.output = output; 18 | } 19 | 20 | /// 21 | /// This driver will run all Q# tests (operations named "...Test") 22 | /// that belong to namespace Quantum.ChemistryTests. 23 | /// 24 | [OperationDriver(TestNamespace = "Microsoft.Quantum.Chemistry.Tests")] 25 | public void TestTarget(TestOperation op) 26 | { 27 | using (var sim = new QuantumSimulator()) 28 | { 29 | // OnLog defines action(s) performed when Q# test calls function Message 30 | sim.OnLog += (msg) => { output.WriteLine(msg); }; 31 | sim.OnLog += (msg) => { Debug.WriteLine(msg); }; 32 | op.TestOperationRunner(sim); 33 | } 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Chemistry/tests/DataModelTests/DocumentationExample.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | using Xunit; 5 | using Microsoft.Quantum.Chemistry; 6 | using Microsoft.Quantum.Simulation.Core; 7 | 8 | using System.Text.RegularExpressions; 9 | using System; 10 | using System.Linq; 11 | using System.Collections.Generic; 12 | 13 | using Microsoft.Quantum.Chemistry.OrbitalIntegrals; 14 | 15 | namespace Microsoft.Quantum.Chemistry.Tests 16 | { 17 | 18 | using OrbitalIntegral = OrbitalIntegral; 19 | 20 | /// 21 | /// These are examples that we may use or are currently using as sample 22 | /// code online in the chemistry library prose documentation, or in research 23 | /// manuscripts. If these break, those examples are no longer valid and need updating. 24 | /// 25 | public class DocumentationExamplesTests 26 | { 27 | [Fact] 28 | public void HydrogenOrbitalIntegrals() 29 | { 30 | // These orbital integrals represent terms in molecular Hydrogen 31 | var orbitalIntegrals = new OrbitalIntegral[] 32 | { 33 | new OrbitalIntegral(new[] { 0,0 }, -1.252477495), 34 | new OrbitalIntegral(new[] { 1,1 }, -0.475934275), 35 | new OrbitalIntegral(new[] { 0,0,0,0 }, 0.674493166), 36 | new OrbitalIntegral(new[] { 0,1,0,1 }, 0.181287518), 37 | new OrbitalIntegral(new[] { 0,1,1,0 }, 0.663472101), 38 | new OrbitalIntegral(new[] { 1,1,1,1 }, 0.697398010) 39 | }; 40 | } 41 | 42 | } 43 | } -------------------------------------------------------------------------------- /Chemistry/tests/DataModelTests/ExtensionsTest.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | using Xunit; 5 | using Microsoft.Quantum.Chemistry; 6 | using Microsoft.Quantum.Simulation.Core; 7 | 8 | using System.Text.RegularExpressions; 9 | using System; 10 | using System.Linq; 11 | using System.Collections.Generic; 12 | 13 | using static Microsoft.Quantum.Chemistry.Extensions; 14 | 15 | namespace Microsoft.Quantum.Chemistry.Tests 16 | { 17 | public class ComparerTests 18 | { 19 | [Fact] 20 | public void IsIntArrayAscendingTest() 21 | { 22 | Assert.True((new Int64[] { }).IsInAscendingOrder()); 23 | Assert.True((new Int64[] { 1 }).IsInAscendingOrder()); 24 | Assert.True((new Int64[] { 1, 2, 3, 4 }).IsInAscendingOrder()); 25 | Assert.True((new Int64[] { 1, 1, 3, 3 }).IsInAscendingOrder()); 26 | Assert.False((new Int64[] { 1, 1, 0, 1 }).IsInAscendingOrder()); 27 | Assert.False((new Int64[] { 10, 9, 7, 4 }).IsInAscendingOrder()); 28 | Assert.False((new Int64[] { 1, 2, 3, 2 }).IsInAscendingOrder()); 29 | } 30 | 31 | [Fact] 32 | public void CompareIntArrayTest() 33 | { 34 | Assert.Equal(0, CompareArray(new Int64[] { 1, 2, 3, 4 }, new Int64[] { 1, 2, 3, 4 })); 35 | Assert.Equal(1, CompareArray(new Int64[] { 1, 2, 3, 4 }, new Int64[] { 1, 2, 3, 3 })); 36 | Assert.Equal(-1, CompareArray(new Int64[] { 1, 2, 3, 3 }, new Int64[] { 1, 2, 3, 4 })); 37 | Assert.Equal(0, CompareArray(new Int64[] { 2, 2, 2, 2 }, new Int64[] { 2, 2, 2, 2 })); 38 | Assert.Equal(1, CompareArray(new Int64[] { 2, 2, 3, 4 }, new Int64[] { 1, 2, 10, 3 })); 39 | Assert.Equal(-1, CompareArray(new Int64[] { 1, 3, 3, 3 }, new Int64[] { 10, 2, 3, 4 })); 40 | } 41 | 42 | [Fact] 43 | public void PrintIntArray() 44 | { 45 | var arr = new[] { 1, 2, 3, 4 }; 46 | var arrString = arr.ToString(); 47 | 48 | var arrHashSet = new HashSet(arr) ; 49 | var arrHashSetString = arr.ToString(); 50 | 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Chemistry/tests/DataModelTests/OrbitalIntegralTests/SpinOrbitalTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | using Xunit; 5 | using Microsoft.Quantum.Chemistry; 6 | using Microsoft.Quantum.Simulation.Core; 7 | 8 | using System.Text.RegularExpressions; 9 | using System; 10 | using System.Linq; 11 | using System.Collections.Generic; 12 | 13 | using Microsoft.Quantum.Chemistry.OrbitalIntegrals; 14 | 15 | namespace Microsoft.Quantum.Chemistry.Tests 16 | { 17 | using SpinOrbital = SpinOrbital; 18 | using Spin = Spin; 19 | 20 | public class SpinOrbitalTests 21 | { 22 | [Theory] 23 | [InlineData(10, 1, 0,1)] 24 | [InlineData(10, 1, 1, 11)] 25 | [InlineData(10, 0, 1, 10)] 26 | [InlineData(1, 0, 1, 1)] 27 | [InlineData(1, 0, 0, 0)] 28 | public void SpinOrbitalTest(int nOrbitals, int orbital, int spin, int expected){ 29 | Assert.Equal(expected, new SpinOrbital((orbital, spin)).ToInt(IndexConvention.HalfUp, nOrbitals)); 30 | } 31 | } 32 | 33 | } -------------------------------------------------------------------------------- /Chemistry/tests/DataModelTests/SerializationTests/FcidumpTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #nullable enable 5 | 6 | using System; 7 | using System.Collections.Generic; 8 | using System.IO; 9 | using System.Linq; 10 | 11 | using Microsoft.Quantum.Chemistry.Broombridge; 12 | 13 | using Newtonsoft.Json; 14 | 15 | using Xunit; 16 | 17 | using static Microsoft.Quantum.Chemistry.Tests.Extensions; 18 | 19 | namespace Microsoft.Quantum.Chemistry.Tests 20 | { 21 | public class FciDumpTests : IClassFixture 22 | { 23 | FciDumpDataFixture fixture; 24 | public FciDumpTests(FciDumpDataFixture fixture) 25 | { 26 | this.fixture = fixture; 27 | } 28 | 29 | [Fact] 30 | public void EnergyOffsetIsZero() 31 | { 32 | Assert.Equal(fixture.problem.EnergyOffset.Value, 0.0); 33 | AssertThat(fixture.problem.EnergyOffset.HasUnits("hartree")); 34 | } 35 | 36 | [Fact] 37 | public void CoulombRepulsionIsCorrect() 38 | { 39 | Assert.Equal(fixture.problem.CoulombRepulsion.Value, 0.71510433906); 40 | AssertThat(fixture.problem.CoulombRepulsion.HasUnits("hartree")); 41 | } 42 | 43 | [Fact] 44 | public void NumberOfTermsIsCorrect() 45 | { 46 | Assert.Equal(fixture.problem.OrbitalIntegralHamiltonian.Terms[TermType.OrbitalIntegral.OneBody].Count, 2); 47 | Assert.Equal(fixture.problem.OrbitalIntegralHamiltonian.Terms[TermType.OrbitalIntegral.TwoBody].Count, 4); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Chemistry/tests/DataModelTests/SerializationTests/IntegrationTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #nullable enable 5 | 6 | using System; 7 | using System.Collections.Generic; 8 | using System.IO; 9 | using System.Linq; 10 | 11 | using Microsoft.Quantum.Chemistry.Broombridge; 12 | 13 | using Newtonsoft.Json; 14 | 15 | using Xunit; 16 | 17 | using static Microsoft.Quantum.Chemistry.Tests.Extensions; 18 | 19 | namespace Microsoft.Quantum.Chemistry.Tests 20 | { 21 | 22 | public class IntegrationTests : IClassFixture 23 | { 24 | FciDumpDataFixture fixture; 25 | public IntegrationTests(FciDumpDataFixture fixture) 26 | { 27 | this.fixture = fixture; 28 | } 29 | 30 | [Fact] 31 | public void RoundtripFcidumpIsCorrect() 32 | { 33 | // Start by converting the Fcidump data deserialized 34 | // in the test fixture out to Broombridge. 35 | using var writer = new StringWriter(); 36 | BroombridgeSerializer.Serialize(writer, new [] { fixture.problem }); 37 | 38 | // Now deserialize back from Broombridge. 39 | using var reader = new StringReader(writer.ToString()); 40 | var roundtripData = BroombridgeSerializer.Deserialize(reader).Single(); 41 | 42 | // Next, check that the resulting problem is the same. 43 | AssertThat(fixture.problem.IsEqualTo(roundtripData)); 44 | } 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /Chemistry/tests/DataModelTests/SerializationTests/SerialzeWavefunctionTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | using System.Collections.Generic; 5 | using System.IO; 6 | using System.Linq; 7 | using System.Diagnostics; 8 | using Microsoft.Quantum.Chemistry.Broombridge; 9 | using Microsoft.Quantum.Chemistry.Fermion; 10 | using Newtonsoft.Json; 11 | using Microsoft.Quantum.Chemistry.LadderOperators; 12 | using Xunit; 13 | using Microsoft.Quantum.Chemistry.LadderOperators; 14 | using Microsoft.Quantum.Chemistry.JordanWigner; 15 | using Microsoft.Quantum.Chemistry.OrbitalIntegrals; 16 | 17 | namespace Microsoft.Quantum.Chemistry.Tests 18 | { 19 | public class SerializeWavefunctionTests 20 | { 21 | public FermionWavefunction MakeWavefunction(string wavefunctionLabel = "UCCSD |G>") 22 | { 23 | var data = Broombridge.Deserializers.DeserializeBroombridge( 24 | Path.Join("Broombridge", "broombridge_v0.2.yaml" 25 | )); 26 | return data.ProblemDescriptions.First().Wavefunctions[wavefunctionLabel].ToIndexing(IndexConvention.UpDown); 27 | } 28 | 29 | [Fact] 30 | public void LoadWavefunctionTest() 31 | { 32 | var wavefunction = MakeWavefunction("UCCSD |G>"); 33 | } 34 | 35 | [Fact] 36 | public void SerializeUCCWavefunctionTest() 37 | { 38 | var wavefunction = MakeWavefunction("UCCSD |G>"); 39 | 40 | string json = JsonConvert.SerializeObject(wavefunction, Formatting.Indented); 41 | 42 | Debug.WriteLine(json); 43 | 44 | var deserializedWavefunction = JsonConvert.DeserializeObject>(json); 45 | } 46 | 47 | [Fact] 48 | public void SerializeMCFWavefunctionTest() 49 | { 50 | var wavefunction = MakeWavefunction("|E>"); 51 | 52 | string json = JsonConvert.SerializeObject(wavefunction, Formatting.Indented); 53 | 54 | Debug.WriteLine(json); 55 | 56 | var deserializedWavefunction = JsonConvert.DeserializeObject>(json); 57 | } 58 | 59 | 60 | } 61 | } -------------------------------------------------------------------------------- /Chemistry/tests/DataModelTests/SerializationTests/TestFixtures.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #nullable enable 5 | 6 | using System; 7 | using System.Collections.Generic; 8 | using System.IO; 9 | using System.Linq; 10 | 11 | using Microsoft.Quantum.Chemistry.Broombridge; 12 | 13 | using Newtonsoft.Json; 14 | 15 | using Xunit; 16 | 17 | using static Microsoft.Quantum.Chemistry.Tests.Extensions; 18 | 19 | namespace Microsoft.Quantum.Chemistry.Tests 20 | { 21 | public class FciDumpDataFixture 22 | { 23 | public ElectronicStructureProblem problem; 24 | 25 | public FciDumpDataFixture() 26 | { 27 | using var reader = File.OpenText( 28 | Path.Join( 29 | "FciDump", "h2_anorccmb.fcidump" 30 | ) 31 | ); 32 | problem = FciDumpSerializer.Deserialize(reader).Single(); 33 | } 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /Chemistry/tests/DataModelTests/TermValueTests/TermValueTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | using Xunit; 5 | using Microsoft.Quantum.Chemistry; 6 | using Microsoft.Quantum.Simulation.Core; 7 | 8 | using System.Text.RegularExpressions; 9 | using System; 10 | using System.Linq; 11 | using System.Collections.Generic; 12 | 13 | namespace Microsoft.Quantum.Chemistry.Tests 14 | { 15 | 16 | public class TTermValueTests 17 | { 18 | [Fact] 19 | void NormTest() 20 | { 21 | var norm = new double[] { 1.0, 2.0, 4.0, 0.1 }.Norm(1.0); 22 | Assert.Equal(7.1, norm); 23 | 24 | norm = new double[] { 1.0, 2.0, 4.0, 0.1 }.Norm(100.0); 25 | Assert.Equal(4.0, norm,5); 26 | } 27 | 28 | [Fact] 29 | void DoubleAddTest() 30 | { 31 | var x = new DoubleCoeff(1.0); 32 | var y = new DoubleCoeff(2.0); 33 | Assert.Equal(3.0, (x + y)); 34 | } 35 | 36 | [Fact] 37 | void DoubleReferenceTest() 38 | { 39 | var x = new DoubleCoeff(1.0); 40 | var y = new DoubleCoeff(3.0); 41 | var z = x + y; 42 | Assert.Equal(1.0, x.Value); 43 | Assert.Equal(3.0, y.Value); 44 | Assert.Equal(4.0, z); 45 | } 46 | 47 | [Fact] 48 | void DoubleSubtractTest() 49 | { 50 | var x = new DoubleCoeff(1.0); 51 | var y = new DoubleCoeff(3.0); 52 | var z = x - y; 53 | Assert.Equal(1.0, x.Value); 54 | Assert.Equal(3.0, y.Value); 55 | Assert.Equal(-2.0, z); 56 | } 57 | } 58 | } -------------------------------------------------------------------------------- /Chemistry/tests/DataModelTests/xunit.runner.json: -------------------------------------------------------------------------------- 1 | { 2 | "methodDisplay": "method" 3 | } -------------------------------------------------------------------------------- /Chemistry/tests/JupyterTests/BroombridgeMagicTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | using System.Collections.Generic; 5 | using System.IO; 6 | using System.Linq; 7 | using Microsoft.Jupyter.Core; 8 | using Microsoft.Quantum.Chemistry.Broombridge; 9 | using Microsoft.Quantum.Chemistry.Magic; 10 | using Newtonsoft.Json; 11 | 12 | using Xunit; 13 | 14 | namespace Microsoft.Quantum.Chemistry.Tests 15 | { 16 | public class BroombridgeMagicTests 17 | { 18 | [Fact] 19 | public async void LoadNoFile() 20 | { 21 | var magic = new BroombridgeMagic(); 22 | var channel = new MockChannel(); 23 | 24 | Assert.Equal("%chemistry.broombridge", magic.Name); 25 | var result = await magic.Run("", channel); 26 | 27 | Assert.Equal(ExecuteStatus.Error, result.Status); 28 | } 29 | 30 | 31 | [Fact] 32 | public async void LoadInvalidFile() 33 | { 34 | var filename = "foo_bar.yaml"; 35 | var magic = new BroombridgeMagic(); 36 | var channel = new MockChannel(); 37 | 38 | await Assert.ThrowsAsync(async () => await magic.Run(filename, channel)); 39 | } 40 | 41 | 42 | // [Fact] 43 | // public async void LoadBroombridgeFile() 44 | // { 45 | // var filename = "broombridge_v0.2.yaml"; 46 | // var magic = new BroombridgeMagic(); 47 | // var channel = new MockChannel(); 48 | 49 | // var result = await magic.Run(filename, channel); 50 | // var broombridge = (V0_2.Data)result.Output; 51 | // Assert.Equal(ExecuteStatus.Ok, result.Status); 52 | // Assert.Equal("0.2", broombridge.Format.Version); 53 | // Assert.Equal(3, broombridge.Bibliography.Count); 54 | // Assert.Single(broombridge.ProblemDescriptions); 55 | // } 56 | } 57 | } -------------------------------------------------------------------------------- /Chemistry/tests/JupyterTests/JupyterTests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net6.0 5 | x64 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | PreserveNewest 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | all 25 | runtime; build; native; contentfiles; analyzers; buildtransitive 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /Chemistry/tests/JupyterTests/MockChannel.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | using Microsoft.Jupyter.Core; 5 | 6 | namespace Microsoft.Quantum.Chemistry.Tests 7 | { 8 | public class MockChannel : IChannel 9 | { 10 | public List errors = new List(); 11 | public List msgs = new List(); 12 | 13 | public void Display(object displayable) 14 | { 15 | throw new NotImplementedException(); 16 | } 17 | 18 | public void Stderr(string message) => errors.Add(message); 19 | 20 | public void Stdout(string message) => msgs.Add(message); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Chemistry/tests/README.md: -------------------------------------------------------------------------------- 1 | # Quantum Chemistry Library Tests # 2 | 3 | Unit tests for the [Microsoft Quantum Chemistry library](https://docs.microsoft.com/azure/quantum/user-guide/libraries/chemistry). 4 | 5 | ## Structure of the tests ## 6 | 7 | - **[DataModelTests](DataModelTests/)**: 8 | Contains tests for the C# component of handling the chemistry Hamiltonian and loading them from files. 9 | 10 | - **[ChemistryTests](ChemistryTests/)**: 11 | Contains tests for isolated Q# component of simulating chemistry Hamiltonians. 12 | 13 | - **[SystemTests](SystemTests/)**: 14 | Contains tests for simulating chemistry Hamiltonians that are output by the DataModel library. 15 | -------------------------------------------------------------------------------- /Chemistry/tests/SamplesTests/SamplesTests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net6.0 5 | x64 6 | false 7 | 8 | 9 | 10 | 11 | PreserveNewest 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | all 21 | runtime; build; native; contentfiles; analyzers; buildtransitive 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | PreserveNewest 42 | 43 | 44 | PreserveNewest 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /Chemistry/tests/SamplesTests/xunit.runner.json: -------------------------------------------------------------------------------- 1 | { 2 | "methodDisplay": "method" 3 | } -------------------------------------------------------------------------------- /Chemistry/tests/SystemTests/SystemTest.cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoft/QuantumLibraries/f2f5e380225367ee4eb995d922067025dc77f0a0/Chemistry/tests/SystemTests/SystemTest.cs -------------------------------------------------------------------------------- /Chemistry/tests/SystemTests/SystemTestBlockEncoding.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | namespace SystemTestsBlockEncoding { 5 | open Microsoft.Quantum.Simulation; 6 | open Microsoft.Quantum.Math; 7 | open Microsoft.Quantum.Intrinsic; 8 | open Microsoft.Quantum.Canon; 9 | open Microsoft.Quantum.Convert; 10 | open Microsoft.Quantum.Chemistry.JordanWigner; 11 | 12 | ////////////////////////////////////////////////////////////////////////// 13 | // Using BlockEncoding /////////////////////////////////////////////////// 14 | ////////////////////////////////////////////////////////////////////////// 15 | 16 | /// # Summary 17 | /// This allocates qubits and applies a block-encoding step. 18 | operation BlockEncodingStep (nSpinOrbitals : Int, data : JWOptimizedHTerms) : Unit { 19 | let generatorSystem = JordanWignerBlockEncodingGeneratorSystem(data); 20 | let (l1Norm, blockEncodingReflection) = PauliBlockEncoding(generatorSystem); 21 | let (nTerms, genIdxFunction) = generatorSystem!; 22 | let systemQubits = nSpinOrbitals; 23 | let auxillaryQubits = Ceiling(Lg(IntAsDouble(nTerms))); 24 | let nQubits = systemQubits + auxillaryQubits; 25 | 26 | use qubits = Qubit[nQubits]; 27 | blockEncodingReflection!!(qubits[systemQubits .. Length(qubits) - 1], qubits[0 .. systemQubits - 1]); 28 | ResetAll(qubits); 29 | } 30 | 31 | } 32 | 33 | 34 | -------------------------------------------------------------------------------- /Chemistry/tests/SystemTests/SystemTestOptimizedBlockEncoding.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace SystemTestsOptimizedBlockEncoding { 5 | 6 | open Microsoft.Quantum.Intrinsic; 7 | open Microsoft.Quantum.Canon; 8 | open Microsoft.Quantum.Convert; 9 | open Microsoft.Quantum.Chemistry.JordanWigner; 10 | 11 | ////////////////////////////////////////////////////////////////////////// 12 | // Using OptimizedBlockEncoding() //////////////////////////////////////// 13 | ////////////////////////////////////////////////////////////////////////// 14 | 15 | /// # Summary 16 | /// We can now use Canon's phase estimation algorithms to 17 | /// learn the ground state energy using the above simulation. 18 | operation RunOptimizedBlockEncoding (nSpinOrbitals : Int, data : JWOptimizedHTerms, targetError : Double) : Unit { 19 | let ((nCtrlRegisterQubits, nTargetRegisterQubits), (oneNorm, blockEncodingReflection)) = _JordanWignerOptimizedBlockEncoding_(targetError, data, nSpinOrbitals); 20 | let op = blockEncodingReflection!!; 21 | 22 | use ctrlQubits = Qubit[nCtrlRegisterQubits]; 23 | use targetQubits = Qubit[nTargetRegisterQubits]; 24 | op(ctrlQubits, targetQubits); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /Chemistry/tests/SystemTests/SystemTests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | net6.0 7 | false 8 | 9 | 10 | 11 | 12 | PreserveNewest 13 | 14 | 15 | 16 | 17 | 18 | PreserveNewest 19 | 20 | 21 | PreserveNewest 22 | 23 | 24 | PreserveNewest 25 | 26 | 27 | PreserveNewest 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /Chemistry/tests/SystemTests/xunit.runner.json: -------------------------------------------------------------------------------- 1 | { 2 | "methodDisplay": "method" 3 | } -------------------------------------------------------------------------------- /Chemistry/tests/TestData/Broombridge/hydrogen_0.1.yaml: -------------------------------------------------------------------------------- 1 | 2 | "$schema": https://raw.githubusercontent.com/Microsoft/Quantum/main/Chemistry/Schema/broombridge-0.1.schema.json 3 | 4 | bibliography: 5 | - {url: 'https://www.nwchem-sw.org'} 6 | format: {version: '0.1'} 7 | generator: {source: nwchem, version: '6.8'} 8 | integral_sets: 9 | - basis_set: {name: sto-3g, type: gaussian} 10 | coulomb_repulsion: {units: hartree, value: 0.713776188} 11 | energy_offset: {units: hartree, value: 0.0} 12 | fci_energy: {lower: 0.0, units: hartree, upper: 0.0, value: 0.0} 13 | geometry: 14 | atoms: 15 | - coords: [0.0, 0.0, 0.0] 16 | name: H 17 | - coords: [0.0, 0.0, 1.624] 18 | name: H 19 | coordinate_system: cartesian 20 | symmetry: c1 21 | units: angstrom 22 | hamiltonian: 23 | one_electron_integrals: 24 | format: sparse 25 | units: hartree 26 | values: 27 | - [1, 1, -1.252477495] 28 | - [2, 2, -0.475934275] 29 | two_electron_integrals: 30 | format: sparse 31 | index_convention: mulliken 32 | units: hartree 33 | values: 34 | - [1,1,1,1,0.674493166] 35 | - [1,2,2,1,0.181287518] 36 | - [1,1,2,2,0.663472101] 37 | - [2,2,2,2,0.697398010] 38 | 39 | metadata: {molecule_name: unknown} 40 | n_electrons: 2 41 | n_orbitals: 2 42 | scf_energy: {units: hartree, value: -7.86099161} 43 | scf_energy_offset: {units: hartree, value: 0.0} 44 | -------------------------------------------------------------------------------- /Chemistry/tests/TestData/FciDump/README.md: -------------------------------------------------------------------------------- 1 | # FCIDUMP Examples # 2 | 3 | Example FCIDUMP files to test the FCIDUMP-BroomBridge file converter. 4 | 5 | ## File Descriptions ## 6 | - **[ethylene_ccpvdz.fcidump](ethylene_ccpvdz.fcidump)**: 7 | Ethylene molecule in cc-pVDZ basis, 10 orbitals, and 16 electrons. 8 | - **[h2o_ccpvdz.fcidump](h2o_ccpvdz.fcidump)**: 9 | Water molecule in cc-pVDZ basis, 9 orbitals, and 10 electrons. 10 | - **[h2_anorccmb.fcidump](h2_anorccmb.fcidump)**: 11 | Hydrogen molecule in ANO-RCC minimal basis, 2 orbitals, and 2 electrons. 12 | 13 | All FCIDUMP files are generated from OpenMolcas, and are covered under MIT license. 14 | -------------------------------------------------------------------------------- /Chemistry/tests/TestData/FciDump/h2_anorccmb.fcidump: -------------------------------------------------------------------------------- 1 | &FCI NORB= 2,NELEC= 2,MS2= 0, 2 | ORBSYM= 1, 1, 3 | ISYM=0 4 | &END 5 | 0.60678308648 1 1 1 1 6 | 0.15821110448 2 1 2 1 7 | 0.60486756354 2 2 1 1 8 | 0.64496763778 2 2 2 2 9 | -1.2207498577 1 1 0 0 10 | -0.52751160572 2 2 0 0 11 | 0.0000000000 1 0 0 0 12 | 0.0000000000 2 0 0 0 13 | 0.71510433906 0 0 0 0 14 | 15 | -------------------------------------------------------------------------------- /Chemistry/tests/TestData/LiQuiD/B_sto6g.dat: -------------------------------------------------------------------------------- 1 | tst=0 info=0.0000,0.0000 nuc=0.000000000000 Ehf=-14.505522886816 0,0=-11.918025147583 0,4=-1.875783313132 4,4=6.620229994627 1,1=-2.152057112751 3,3=-2.152057112751 2,2=-2.152057112751 0,0,0,0=2.521734600094 0,4,0,0=0.895853556286 0,4,4,0=2.529089389716 0,1,1,0=1.657197916382 0,3,3,0=1.657197916382 0,2,2,0=1.657197916382 0,0,0,4=0.895853556286 0,4,0,4=0.757499936984 0,4,4,4=1.200215215751 0,1,1,4=0.253719605726 0,3,3,4=0.253719605726 0,2,2,4=0.253719605726 4,0,0,0=0.895853556286 4,4,0,0=0.757499936984 4,4,4,0=1.200215215751 4,1,1,0=0.253719605726 4,3,3,0=0.253719605726 4,2,2,0=0.253719605726 4,0,0,4=2.529089389716 4,4,0,4=1.200215215751 4,4,4,4=2.931512735286 4,1,1,4=1.511359251162 4,3,3,4=1.511359251162 4,2,2,4=1.511359251162 1,0,0,1=1.657197916382 1,4,0,1=0.253719605726 1,4,4,1=1.511359251162 1,1,1,1=1.489788814781 1,3,3,1=1.326975015437 1,2,2,1=1.326975015437 3,0,0,3=1.657197916382 3,4,0,3=0.253719605726 3,4,4,3=1.511359251162 3,1,1,3=1.326975015437 3,3,3,3=1.489788814781 3,2,2,3=1.326975015437 2,0,0,2=1.657197916382 2,4,0,2=0.253719605726 2,4,4,2=1.511359251162 2,1,1,2=1.326975015437 2,3,3,2=1.326975015437 2,2,2,2=1.489788814781 3,2,3,2=0.081406899672 2,2,3,3=0.081406899672 1,2,1,2=0.081406899672 2,2,1,1=0.081406899672 1,3,1,3=0.081406899672 3,3,1,1=0.081406899672 0,1,0,1=0.246613987771 0,1,4,1=-0.104645020087 4,1,0,1=-0.104645020087 4,1,4,1=0.096488915226 1,1,0,0=0.246613987771 1,1,4,0=-0.104645020087 1,1,0,4=-0.104645020087 1,1,4,4=0.096488915226 0,3,0,3=0.246613987771 0,3,4,3=-0.104645020087 4,3,0,3=-0.104645020087 4,3,4,3=0.096488915226 3,3,0,0=0.246613987771 3,3,4,0=-0.104645020087 3,3,0,4=-0.104645020087 3,3,4,4=0.096488915226 0,2,0,2=0.246613987771 0,2,4,2=-0.104645020087 4,2,0,2=-0.104645020087 4,2,4,2=0.096488915226 2,2,0,0=0.246613987771 2,2,4,0=-0.104645020087 2,2,0,4=-0.104645020087 2,2,4,4=0.096488915226 2 | -------------------------------------------------------------------------------- /Design/notes/environment.yml: -------------------------------------------------------------------------------- 1 | name: qdk-libraries-notes 2 | channels: 3 | - conda-forge 4 | dependencies: 5 | - qutip 6 | - notebook 7 | - numpy 8 | - scipy 9 | -------------------------------------------------------------------------------- /Docs/README.md: -------------------------------------------------------------------------------- 1 | # Quantum Development Kit: Documentation # 2 | 3 | Please see the [main documentation site](https://docs.microsoft.com/azure/quantum) for an introduction to quantum computing, the Q# language, and to the libraries provided with the Quantum Development Kit. 4 | 5 | ## Additional Documentation ## 6 | 7 | - [Q# Style Guide](./style-guide.md): Advice on how to write quantum programs in a consistent and readable manner. 8 | 9 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Microsoft Corporation 4 | 5 | All rights reserved. 6 | 7 | Permission is hereby granted, free of charge, to any person obtaining a copy 8 | of this software and associated documentation files (the "Software"), to deal 9 | in the Software without restriction, including without limitation the rights 10 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 11 | copies of the Software, and to permit persons to whom the Software is 12 | furnished to do so, subject to the following conditions: 13 | 14 | The above copyright notice and this permission notice shall be included in all 15 | copies or substantial portions of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 18 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 20 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 21 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 23 | SOFTWARE. -------------------------------------------------------------------------------- /MachineLearning/Common/DelaySign.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | 3 | // Attributes for delay-signing 4 | #if SIGNED 5 | [assembly:AssemblyKeyFile("..\\..\\Build\\267DevDivSNKey2048.snk")] 6 | [assembly:AssemblyDelaySign(true)] 7 | #endif 8 | 9 | internal static class SigningConstants 10 | { 11 | #if SIGNED 12 | public const string PUBLIC_KEY = ", PublicKey=" + 13 | "002400000c800000140100000602000000240000525341310008000001000100613399aff18ef1" + 14 | "a2c2514a273a42d9042b72321f1757102df9ebada69923e2738406c21e5b801552ab8d200a65a2" + 15 | "35e001ac9adc25f2d811eb09496a4c6a59d4619589c69f5baf0c4179a47311d92555cd006acc8b" + 16 | "5959f2bd6e10e360c34537a1d266da8085856583c85d81da7f3ec01ed9564c58d93d713cd0172c" + 17 | "8e23a10f0239b80c96b07736f5d8b022542a4e74251a5f432824318b3539a5a087f8e53d2f135f" + 18 | "9ca47f3bb2e10aff0af0849504fb7cea3ff192dc8de0edad64c68efde34c56d302ad55fd6e80f3" + 19 | "02d5efcdeae953658d3452561b5f36c542efdbdd9f888538d374cef106acf7d93a4445c3c73cd9" + 20 | "11f0571aaf3d54da12b11ddec375b3"; 21 | #else 22 | public const string PUBLIC_KEY = ""; 23 | #endif 24 | } 25 | -------------------------------------------------------------------------------- /MachineLearning/src/Datasets/Properties/NamespaceInfo.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | /// # Summary 5 | /// This namespace provides example datasets for use 6 | /// with quantum machine learning classifiers. 7 | namespace Microsoft.Quantum.MachineLearning.Datasets { } 8 | -------------------------------------------------------------------------------- /MachineLearning/src/MachineLearning.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | net6.0 4 | Microsoft.Quantum.MachineLearning 5 | true 6 | Microsoft.Quantum.MachineLearning 7 | 11 | false 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | Microsoft 29 | Microsoft's Quantum ML Libraries. 30 | © Microsoft Corporation. All rights reserved. 31 | Microsoft.Quantum.MachineLearning 32 | See: https://docs.microsoft.com/azure/quantum/qdk-relnotes/ 33 | MIT 34 | https://github.com/microsoft/QuantumLibraries/tree/main/MachineLearning 35 | qdk-nuget-icon.png 36 | Quantum Q# Qsharp 37 | 1591 38 | true 39 | true 40 | true 41 | snupkg 42 | $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb;.xml 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /MachineLearning/src/Private.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.MachineLearning { 5 | open Microsoft.Quantum.Logical; 6 | open Microsoft.Quantum.Arrays; 7 | open Microsoft.Quantum.Intrinsic; 8 | open Microsoft.Quantum.Canon; 9 | open Microsoft.Quantum.Math; 10 | 11 | internal function AllNearlyEqualD(v1 : Double[], v2 : Double[]) : Bool { 12 | return Length(v1) == Length(v2) and All(NearlyEqualD, Zipped(v1, v2)); 13 | } 14 | 15 | internal function TailMeasurement(nQubits : Int) : (Qubit[] => Result) { 16 | let paulis = [PauliI, size = nQubits] w/ (nQubits - 1) <- PauliZ; 17 | return Measure(paulis, _); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /MachineLearning/src/Properties/NamespaceInfo.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | /// # Summary 5 | /// This namespace provides functions and operations used in 6 | /// quantum machine learning applications. 7 | /// 8 | /// # Description 9 | /// To learn more about this quantum machine learning library, see 10 | /// [Introduction to the Quantum Machine Learning Library](xref:microsoft.quantum.libraries.overview.machine-learning.intro) 11 | /// in Q# documentation. 12 | /// 13 | /// # References 14 | /// - Maria Schuld, Alex Bocharov, Krysta Svore, Nathan Wiebe, 15 | /// "Circuit-centric quantum classifiers", 16 | /// https://arxiv.org/abs/1804.00633. 17 | namespace Microsoft.Quantum.MachineLearning { } 18 | -------------------------------------------------------------------------------- /MachineLearning/tests/ClassificationTests.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.MachineLearning.Tests { 5 | open Microsoft.Quantum.Logical; 6 | open Microsoft.Quantum.Arrays; 7 | open Microsoft.Quantum.Intrinsic; 8 | open Microsoft.Quantum.Diagnostics; 9 | open Microsoft.Quantum.MachineLearning as ML; 10 | 11 | @Test("QuantumSimulator") 12 | function InferredLabelFact() : Unit { 13 | EqualityFactI(ML.InferredLabel(0.25, 0.26), 1, "InferredLabel returned wrong class."); 14 | } 15 | 16 | @Test("QuantumSimulator") 17 | function InferredLabelsFact() : Unit { 18 | AllEqualityFactI( 19 | ML.InferredLabels(0.25, [0.23, 0.26, 0.1]), 20 | [0, 1, 0], 21 | "InferredLabels returned at least one wrong class." 22 | ); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /MachineLearning/tests/InputEncodingTests.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.MachineLearning.Tests { 5 | open Microsoft.Quantum.Arrays; 6 | open Microsoft.Quantum.Math; 7 | open Microsoft.Quantum.Arithmetic; 8 | open Microsoft.Quantum.Preparation; 9 | open Microsoft.Quantum.Intrinsic; 10 | open Microsoft.Quantum.Canon; 11 | open Microsoft.Quantum.Diagnostics; 12 | open Microsoft.Quantum.MachineLearning; 13 | 14 | operation _ApplyToBareRegister(op : (LittleEndian => Unit is Adj), register : Qubit[]) : Unit is Adj { 15 | op(LittleEndian(register)); 16 | } 17 | 18 | @Test("QuantumSimulator") 19 | operation CheckInputEncoderWithPositiveInputs() : Unit { 20 | let coefficients = [0.1, 0.2, 0.3, 0.4]; 21 | let encoder = InputEncoder(coefficients); 22 | AssertOperationsEqualReferenced(2, 23 | _ApplyToBareRegister(PrepareArbitraryStateCP(Mapped(ComplexPolar(_, 0.0), coefficients), _), _), 24 | _ApplyToBareRegister(encoder::Prepare, _) 25 | ); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /MachineLearning/tests/MachineLearningTests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | net6.0 7 | Microsoft.Quantum.Standard.Tests 8 | false 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /MachineLearning/tests/TypesTests.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.MachineLearning.Tests { 5 | open Microsoft.Quantum.Diagnostics; 6 | open Microsoft.Quantum.MachineLearning as ML; 7 | 8 | @Test("QuantumSimulator") 9 | function ScheduleLengthFact() : Unit { 10 | let actualLength = ML.ScheduleLength(ML.SamplingSchedule([0..4, 1..2..5])); 11 | EqualityFactI(actualLength, 5 + 3, "Wrong output from ScheduleLength."); 12 | } 13 | 14 | @Test("QuantumSimulator") 15 | function SampledFact() : Unit { 16 | let actuallySampled = ML.Sampled(ML.SamplingSchedule([0..4, 1..2..5]), [0, 10, 20, 30, 40, 50, 60, 70]); 17 | AllEqualityFactI(actuallySampled, [0, 10, 20, 30, 40, 10, 30, 50], "Wrong output from Sampled."); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /MachineLearning/tests/ValidationTests.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.MachineLearning.Tests { 5 | open Microsoft.Quantum.Diagnostics; 6 | open Microsoft.Quantum.MachineLearning as ML; 7 | 8 | @Test("QuantumSimulator") 9 | function MisclassificationsFact() : Unit { 10 | let misclassifications = ML.Misclassifications([0, 1, 0, 0], [0, 1, 1, 0]); 11 | AllEqualityFactI(misclassifications, [2], "Wrong output from Misclassifications."); 12 | } 13 | 14 | @Test("QuantumSimulator") 15 | function NMisclassificationsFact() : Unit { 16 | let nMisclassifications = ML.NMisclassifications([0, 1, 0, 0, 1], [0, 1, 1, 0, 0]); 17 | EqualityFactI(nMisclassifications, 2, "Wrong output from NMisclassifications."); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /NuGet.Config: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /Numerics.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.28307.539 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Numerics", "Numerics\src\Numerics.csproj", "{C7E6F1F9-5DB7-41D6-ADA4-3E8F5BAEF731}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NumericsTests", "Numerics\tests\NumericsTests.csproj", "{B8E99F28-CF37-4AA1-BDEC-16D3573CAEFD}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Standard", "Standard\src\Standard.csproj", "{4EE69CC7-1158-49A2-A28F-9443B06D4A32}" 11 | EndProject 12 | Global 13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 14 | Debug|Any CPU = Debug|Any CPU 15 | Release|Any CPU = Release|Any CPU 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {C7E6F1F9-5DB7-41D6-ADA4-3E8F5BAEF731}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 19 | {C7E6F1F9-5DB7-41D6-ADA4-3E8F5BAEF731}.Debug|Any CPU.Build.0 = Debug|Any CPU 20 | {C7E6F1F9-5DB7-41D6-ADA4-3E8F5BAEF731}.Release|Any CPU.ActiveCfg = Release|Any CPU 21 | {C7E6F1F9-5DB7-41D6-ADA4-3E8F5BAEF731}.Release|Any CPU.Build.0 = Release|Any CPU 22 | {B8E99F28-CF37-4AA1-BDEC-16D3573CAEFD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {B8E99F28-CF37-4AA1-BDEC-16D3573CAEFD}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {B8E99F28-CF37-4AA1-BDEC-16D3573CAEFD}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {B8E99F28-CF37-4AA1-BDEC-16D3573CAEFD}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {4EE69CC7-1158-49A2-A28F-9443B06D4A32}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {4EE69CC7-1158-49A2-A28F-9443B06D4A32}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {4EE69CC7-1158-49A2-A28F-9443B06D4A32}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {4EE69CC7-1158-49A2-A28F-9443B06D4A32}.Release|Any CPU.Build.0 = Release|Any CPU 30 | EndGlobalSection 31 | GlobalSection(SolutionProperties) = preSolution 32 | HideSolutionNode = FALSE 33 | EndGlobalSection 34 | GlobalSection(ExtensibilityGlobals) = postSolution 35 | SolutionGuid = {62FF308E-50FB-430C-B3EE-BE8E142835C9} 36 | EndGlobalSection 37 | EndGlobal 38 | -------------------------------------------------------------------------------- /Numerics/Common/DelaySign.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | 3 | // Attributes for delay-signing 4 | #if SIGNED 5 | [assembly:AssemblyKeyFile("..\\..\\Build\\267DevDivSNKey2048.snk")] 6 | [assembly:AssemblyDelaySign(true)] 7 | #endif 8 | 9 | internal static class SigningConstants 10 | { 11 | #if SIGNED 12 | public const string PUBLIC_KEY = ", PublicKey=" + 13 | "002400000c800000140100000602000000240000525341310008000001000100613399aff18ef1" + 14 | "a2c2514a273a42d9042b72321f1757102df9ebada69923e2738406c21e5b801552ab8d200a65a2" + 15 | "35e001ac9adc25f2d811eb09496a4c6a59d4619589c69f5baf0c4179a47311d92555cd006acc8b" + 16 | "5959f2bd6e10e360c34537a1d266da8085856583c85d81da7f3ec01ed9564c58d93d713cd0172c" + 17 | "8e23a10f0239b80c96b07736f5d8b022542a4e74251a5f432824318b3539a5a087f8e53d2f135f" + 18 | "9ca47f3bb2e10aff0af0849504fb7cea3ff192dc8de0edad64c68efde34c56d302ad55fd6e80f3" + 19 | "02d5efcdeae953658d3452561b5f36c542efdbdd9f888538d374cef106acf7d93a4445c3c73cd9" + 20 | "11f0571aaf3d54da12b11ddec375b3"; 21 | #else 22 | public const string PUBLIC_KEY = ""; 23 | #endif 24 | } 25 | -------------------------------------------------------------------------------- /Numerics/src/FixedPoint/Comparison.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Arithmetic { 5 | 6 | /// # Summary 7 | /// Compares two fixed-point numbers stored in quantum registers, and 8 | /// controls a flip on the result. 9 | /// 10 | /// # Input 11 | /// ## fp1 12 | /// First fixed-point number to be compared. 13 | /// ## fp2 14 | /// Second fixed-point number to be compared. 15 | /// ## result 16 | /// Result of the comparison. Will be flipped if `fp1 > fp2`. 17 | /// 18 | /// # Remarks 19 | /// The current implementation requires the two fixed-point numbers 20 | /// to have the same point position and the same number of qubits. 21 | operation CompareGreaterThanFxP(fp1 : FixedPoint, fp2 : FixedPoint, 22 | result : Qubit) : Unit is Adj + Ctl { 23 | IdenticalFormatFactFxP([fp1, fp2]); 24 | CompareGTSI(SignedLittleEndian(LittleEndian(fp1::Register)), 25 | SignedLittleEndian(LittleEndian(fp2::Register)), 26 | result); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Numerics/src/FixedPoint/Init.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Arithmetic { 5 | open Microsoft.Quantum.Canon; 6 | open Microsoft.Quantum.Convert; 7 | open Microsoft.Quantum.Intrinsic; 8 | open Microsoft.Quantum.Math; 9 | 10 | /// # Summary 11 | /// Initialize a quantum fixed-point number to a classical constant. 12 | /// 13 | /// # Input 14 | /// ## constant 15 | /// Constant to which to initialize the quantum fixed-point number. 16 | /// ## fp 17 | /// Fixed-point number (of type FixedPoint) to initialize. 18 | operation PrepareFxP(constant : Double, fp : FixedPoint) 19 | : Unit is Adj + Ctl { 20 | let bits = FixedPointAsBoolArray(fp::IntegerBits, Length(fp::Register) - fp::IntegerBits, constant); 21 | ApplyPauliFromBitString(PauliX, true, bits, fp::Register); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Numerics/src/FixedPoint/Math.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Math { 5 | open Microsoft.Quantum.Convert; 6 | 7 | /// # Summary 8 | /// Returns the smallest representable number for specific fixed point dimensions. 9 | /// 10 | /// # Input 11 | /// ## integerBits 12 | /// Number of integer bits (including the sign bit). 13 | /// ## fractionalBits 14 | /// Number of fractional bits. 15 | /// 16 | /// # Remark 17 | /// The value can be computed as $-2^{p-1}$, where $p$ is the number of integer bits. 18 | function SmallestFixedPoint(integerBits : Int, fractionalBits : Int) : Double { 19 | return -PowD(2.0, IntAsDouble(integerBits - 1)); 20 | } 21 | 22 | /// # Summary 23 | /// Returns the largest representable number for specific fixed point dimensions. 24 | /// 25 | /// # Input 26 | /// ## integerBits 27 | /// Number of integer bits (including the sign bit). 28 | /// ## fractionalBits 29 | /// Number of fractional bits. 30 | /// 31 | /// # Remark 32 | /// The value can be computed as $2^{p-1} - 2^{-q}$, where $p$ 33 | /// is the number of integer bits and $q$ is the number of fractional bits. 34 | function LargestFixedPoint(integerBits : Int, fractionalBits : Int) : Double { 35 | return PowD(2.0, IntAsDouble(integerBits - 1)) - PowD(2.0, -IntAsDouble(fractionalBits)); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /Numerics/src/FixedPoint/Measurement.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Arithmetic { 5 | open Microsoft.Quantum.Arrays; 6 | open Microsoft.Quantum.Canon; 7 | open Microsoft.Quantum.Convert; 8 | open Microsoft.Quantum.Measurement; 9 | 10 | /// # Summary 11 | /// Measure a fixed-point number, returns its value as Double, and resets 12 | /// all the register to zero. 13 | /// 14 | /// # Input 15 | /// ## fp 16 | /// Fixed-point number to measure. 17 | operation MeasureFxP(fp : FixedPoint) : Double { 18 | let bits = ForEach(q => MResetZ(q) == One, fp::Register); 19 | return BoolArrayAsFixedPoint(fp::IntegerBits, bits); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Numerics/src/FixedPoint/Reciprocal.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Arithmetic { 5 | open Microsoft.Quantum.Math; 6 | open Microsoft.Quantum.Canon; 7 | open Microsoft.Quantum.Arrays; 8 | open Microsoft.Quantum.Intrinsic; 9 | open Microsoft.Quantum.Diagnostics; 10 | 11 | /// # Summary 12 | /// Computes the reciprocal of a number stored in a quantum register with 13 | /// the fixed-point representation. 14 | /// 15 | /// # Description 16 | /// Given a register in the state $\ket{x}$ for a fixed-point number $x$, 17 | /// computes the reciprocal $1 / x$ into the state of the `result` 18 | /// register. 19 | /// 20 | /// # Input 21 | /// ## x 22 | /// Fixed-point number to be inverted. 23 | /// ## result 24 | /// Fixed-point number that will hold the result. Must be initialized to $\ket{0.0}$. 25 | operation ComputeReciprocalFxP(x : FixedPoint, result : FixedPoint) : Unit is Adj { 26 | body (...) { 27 | Controlled ComputeReciprocalFxP([], (x, result)); 28 | } 29 | controlled (controls, ...) { 30 | let (p, xs) = x!; 31 | let (pRes, rs) = result!; 32 | let n = Length(xs); 33 | AssertAllZero(rs); 34 | Fact(p + pRes - 1 + n >= Length(rs), "Output register is too wide."); 35 | use sign = Qubit(); 36 | use tmpRes = Qubit[2 * n]; 37 | CNOT(Tail(xs), sign); 38 | (Controlled Invert2sSI) 39 | ([sign], SignedLittleEndian(LittleEndian(xs))); 40 | ComputeReciprocalI(LittleEndian(xs), LittleEndian(tmpRes)); 41 | (Controlled ApplyToEachCA)(controls, 42 | (CNOT, Zipped(tmpRes[p+pRes-1+n-Length(rs)..Min([n+p+pRes, 2*n-1])], rs))); 43 | (Controlled Invert2sSI)([sign], SignedLittleEndian(LittleEndian(rs))); 44 | (Adjoint ComputeReciprocalI)(LittleEndian(xs), LittleEndian(tmpRes)); 45 | (Controlled Adjoint Invert2sSI) 46 | ([sign], SignedLittleEndian(LittleEndian(xs))); 47 | CNOT(Tail(xs), sign); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Numerics/src/FixedPoint/Types.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Arithmetic { 5 | /// # Summary 6 | /// Represents a register of qubits encoding a fixed-point number. Consists of an integer that is equal to the number of 7 | /// qubits to the left of the binary point, i.e., qubits of weight greater 8 | /// than or equal to 1, and a quantum register. 9 | newtype FixedPoint = (IntegerBits: Int, Register: Qubit[]); 10 | } 11 | -------------------------------------------------------------------------------- /Numerics/src/Integer/Division.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Arithmetic { 5 | open Microsoft.Quantum.Intrinsic; 6 | open Microsoft.Quantum.Diagnostics; 7 | 8 | /// # Summary 9 | /// Divides two quantum integers. 10 | /// 11 | /// # Description 12 | /// `xs` will hold the 13 | /// remainder `xs - floor(xs/ys) * ys` and `result` will hold 14 | /// `floor(xs/ys)`. 15 | /// 16 | /// # Input 17 | /// ## xs 18 | /// $n$-bit dividend, will be replaced by the remainder. 19 | /// ## ys 20 | /// $n$-bit divisor 21 | /// ## result 22 | /// $n$-bit result, must be in state $\ket{0}$ initially 23 | /// and will be replaced by the result of the integer division. 24 | /// 25 | /// # Remarks 26 | /// Uses a standard shift-and-subtract approach to implement the division. 27 | /// The controlled version is specialized such the subtraction does not 28 | /// require additional controls. 29 | operation DivideI (xs: LittleEndian, ys: LittleEndian, 30 | result: LittleEndian) : Unit { 31 | body (...) { 32 | Controlled DivideI([], (xs, ys, result)); 33 | } 34 | controlled (controls, ...) { 35 | let n = Length(result!); 36 | 37 | EqualityFactI(n, Length(ys!), "Integer division requires 38 | equally-sized registers ys and result."); 39 | EqualityFactI(n, Length(xs!), "Integer division 40 | requires an n-bit dividend registers."); 41 | AssertAllZero(result!); 42 | 43 | let xpadded = LittleEndian(xs! + result!); 44 | 45 | for i in (n - 1)..(-1)..0 { 46 | let xtrunc = LittleEndian(xpadded![i..i+n-1]); 47 | Controlled CompareGTI(controls, (ys, xtrunc, result![i])); 48 | // if ys > xtrunc, we don't subtract: 49 | (Controlled X) (controls, result![i]); 50 | (Controlled Adjoint AddI) ([result![i]], (ys, xtrunc)); 51 | } 52 | } 53 | adjoint auto; 54 | adjoint controlled auto; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /Numerics/src/Integer/Types.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Arithmetic { 5 | /// # Summary 6 | /// Type of a signed integer stored in little endian (see LittleEndian). 7 | /// Negative numbers are stored using two's complement. 8 | newtype SignedLittleEndian = LittleEndian; 9 | } 10 | -------------------------------------------------------------------------------- /Numerics/src/Numerics.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | Microsoft.Quantum.Numerics 6 | true 7 | Microsoft.Quantum.Numerics 8 | false 9 | 10 | 11 | 12 | 0162 13 | True 14 | Microsoft 15 | Microsoft's Quantum numerics libraries. 16 | © Microsoft Corporation. All rights reserved. 17 | See: https://docs.microsoft.com/azure/quantum/qdk-relnotes/ 18 | MIT 19 | https://github.com/Microsoft/QuantumLibraries 20 | qdk-nuget-icon.png 21 | Quantum Q# Qsharp 22 | 1591 23 | true 24 | true 25 | true 26 | true 27 | snupkg 28 | $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb;.xml 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /Numerics/tests/NumericsTests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | net6.0 7 | false 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /Python/.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore autogenerated Python modules. 2 | version.py 3 | 4 | # Python packaging artifacts 5 | *.egg-info/ 6 | build/ 7 | dist/ 8 | -------------------------------------------------------------------------------- /Python/qsharp-chemistry/qsharp/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoft/QuantumLibraries/f2f5e380225367ee4eb995d922067025dc77f0a0/Python/qsharp-chemistry/qsharp/tests/__init__.py -------------------------------------------------------------------------------- /Python/qsharp/README.md: -------------------------------------------------------------------------------- 1 | # Q# Interoperability for Python # 2 | 3 | The `qsharp` package for Python provides interoperability with the Quantum Development Kit and with the Q# language, making it easy to simulate Q# operations and functions from within Python. 4 | 5 | For details on how to get started with Python and Q#, please see the [Getting Started with Python guide](https://docs.microsoft.com/azure/quantum/install-python-qdk). 6 | 7 | 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. 8 | 9 | ## Installing with Anaconda ## 10 | 11 | If you use Anaconda or Miniconda, installing the `qsharp` package will automatically include all dependencies: 12 | 13 | ```bash 14 | conda install -c quantum-engineering qsharp 15 | ``` 16 | 17 | ## Installing from Source ## 18 | 19 | If you'd like to contribute to or experiment with the Python interoperability feature, it may be useful to install from source rather than from the `qsharp` package on the Python Package Index (PyPI). 20 | To do so, make sure that you are in the `Python/qsharp` directory, and run `setup.py` with the `install` argument: 21 | 22 | ```bash 23 | cd Python/qsharp 24 | python setup.py install 25 | ``` 26 | 27 | ## Building the `qsharp` Package ## 28 | 29 | The Python interoperability feature uses a standard `setuptools`-based packaging strategy. 30 | To build a platform-independent wheel, run the setup script with `bdist_wheel` instead: 31 | 32 | ```bash 33 | cd Python/qsharp 34 | python setup.py bdist_wheel 35 | ``` 36 | 37 | By default, this will create a `qsharp` wheel in `dist/` with the version number set to 0.0.0.1. 38 | To provide a more useful version number, set the `PYTHON_VERSION` environment variable before running `setup.py`. 39 | 40 | ## Support and Q&A 41 | 42 | 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#**. 43 | -------------------------------------------------------------------------------- /Python/qsharp/setup.py: -------------------------------------------------------------------------------- 1 | #!/bin/env python 2 | # -*- coding: utf-8 -*- 3 | ## 4 | # setup.py: Installs Python host functionality for Q#. 5 | ## 6 | # Copyright (c) Microsoft Corporation. All rights reserved. 7 | # Licensed under the MIT License. 8 | ## 9 | 10 | ## IMPORTS ## 11 | 12 | import setuptools 13 | import os 14 | 15 | ## VERSION INFORMATION ## 16 | # Our build process sets the PYTHON_VERSION environment variable to a version 17 | # string that is compatible with PEP 440, and so we inherit that version number 18 | # here and propagate that to qsharp/version.py. 19 | # 20 | # To make sure that local builds still work without the same environment 21 | # variables, we'll default to 0.0.0.1 as a development version. 22 | 23 | version = os.environ.get('PYTHON_VERSION', '0.0.0.1') 24 | 25 | ## DESCRIPTION ## 26 | # The long description metadata passed to setuptools is used to populate the 27 | # PyPI page for this package. Thus, we'll generate the description by using the 28 | # same README.md file that we use in the GitHub repo. 29 | 30 | with open("./README.md", "r") as fh: 31 | long_description = fh.read() 32 | 33 | ## SETUPTOOLS INVOCATION ## 34 | 35 | setuptools.setup( 36 | name="qsharp", 37 | version=version, 38 | author="Microsoft", 39 | author_email="que-contacts@microsoft.com", 40 | description="Q# Libraries for interop with Python.", 41 | long_description=long_description, 42 | long_description_content_type="text/markdown", 43 | url="https://github.com/microsoft/QuantumLibraries", 44 | packages=setuptools.find_packages(), 45 | classifiers=[ 46 | "Programming Language :: Python :: 3", 47 | "License :: OSI Approved :: MIT License", 48 | "Operating System :: OS Independent", 49 | ], 50 | install_requires=[ 51 | f'qsharp-core=={version}', 52 | f'qsharp-chemistry=={version}' 53 | ] 54 | ) 55 | -------------------------------------------------------------------------------- /Standard/Common/DelaySign.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | 3 | // Attributes for delay-signing 4 | #if SIGNED 5 | [assembly:AssemblyKeyFile("..\\..\\Build\\267DevDivSNKey2048.snk")] 6 | [assembly:AssemblyDelaySign(true)] 7 | #endif 8 | 9 | internal static class SigningConstants 10 | { 11 | #if SIGNED 12 | public const string PUBLIC_KEY = ", PublicKey=" + 13 | "002400000c800000140100000602000000240000525341310008000001000100613399aff18ef1" + 14 | "a2c2514a273a42d9042b72321f1757102df9ebada69923e2738406c21e5b801552ab8d200a65a2" + 15 | "35e001ac9adc25f2d811eb09496a4c6a59d4619589c69f5baf0c4179a47311d92555cd006acc8b" + 16 | "5959f2bd6e10e360c34537a1d266da8085856583c85d81da7f3ec01ed9564c58d93d713cd0172c" + 17 | "8e23a10f0239b80c96b07736f5d8b022542a4e74251a5f432824318b3539a5a087f8e53d2f135f" + 18 | "9ca47f3bb2e10aff0af0849504fb7cea3ff192dc8de0edad64c68efde34c56d302ad55fd6e80f3" + 19 | "02d5efcdeae953658d3452561b5f36c542efdbdd9f888538d374cef106acf7d93a4445c3c73cd9" + 20 | "11f0571aaf3d54da12b11ddec375b3"; 21 | #else 22 | public const string PUBLIC_KEY = ""; 23 | #endif 24 | } 25 | -------------------------------------------------------------------------------- /Standard/README.md: -------------------------------------------------------------------------------- 1 | # Microsoft.Quantum.Canon # 2 | 3 | Q# sources used to implement [the canon](https://docs.microsoft.com/en-us/azure/quantum/user-guide/libraries) portion of the Q# standard library. 4 | 5 | ## Building and testing ## 6 | 7 | The canon is a cross-platform project built using [.NET Core](https://docs.microsoft.com/en-us/dotnet/core/). 8 | Once .NET Core is installed, you may build and run its tests by executing the following from a command line: 9 | 10 | ```bash 11 | dotnet test tests 12 | ``` 13 | 14 | For more details about creating and running tests in Q#, 15 | see the [Testing and debugging](https://docs.microsoft.com/azure/quantum/user-guide/testing-debugging) 16 | section of the [developer's guide](https://docs.microsoft.com/azure/quantum). -------------------------------------------------------------------------------- /Standard/src/AmplitudeAmplification/CommonOracles.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.AmplitudeAmplification { 5 | open Microsoft.Quantum.Canon; 6 | open Microsoft.Quantum.Intrinsic; 7 | open Microsoft.Quantum.Oracles; 8 | 9 | /// # Summary 10 | /// Constructs a reflection about the all-zero string |0...0〉, which is the typical input state to amplitude amplification. 11 | /// 12 | /// # Output 13 | /// A `ReflectionOracle` that reflects about the state $\ket{0\cdots 0}$. 14 | /// 15 | /// # See Also 16 | /// - Microsoft.Quantum.AmplitudeAmplification.ReflectionOracle 17 | function ReflectionStart() : ReflectionOracle { 18 | return ReflectionOracle(RAll0); 19 | } 20 | 21 | /// # Summary 22 | /// Implementation of . 23 | internal operation ApplyTargetStateReflectionOracle(phase : Double, idxFlagQubit : Int, qubits : Qubit[]) 24 | : Unit is Adj + Ctl { 25 | R1(phase, qubits[idxFlagQubit]); 26 | } 27 | 28 | /// # Summary 29 | /// Constructs a `ReflectionOracle` about the target state uniquely marked by the flag qubit. 30 | /// 31 | /// # Description 32 | /// The oracle returned by this function reflects about the $\ket{1}$ state 33 | /// of a flag qubit (given by the index `idxFlagQubit`). 34 | /// 35 | /// # Input 36 | /// ## idxFlagQubit 37 | /// Index to flag qubit $f$ of oracle. 38 | /// 39 | /// # Output 40 | /// A `ReflectionOracle` that reflects about the state marked by $\ket{1}_f$. 41 | /// 42 | /// # See Also 43 | /// - Microsoft.Quantum.Canon.ReflectionOracle 44 | function TargetStateReflectionOracle(idxFlagQubit : Int) : ReflectionOracle { 45 | return ReflectionOracle(ApplyTargetStateReflectionOracle(_, idxFlagQubit, _)); 46 | } 47 | 48 | } 49 | 50 | -------------------------------------------------------------------------------- /Standard/src/AmplitudeAmplification/Convert.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.AmplitudeAmplification { 5 | open Microsoft.Quantum.Math; 6 | 7 | /// # Summary 8 | /// Converts phases specified as single-qubit rotations to phases 9 | /// specified as partial reflections. 10 | /// 11 | /// # Input 12 | /// ## rotPhases 13 | /// Array of single-qubit rotations to be converted to partial 14 | /// reflections. 15 | /// 16 | /// # Output 17 | /// An operation that implements phases specified as partial reflections. 18 | /// 19 | /// # References 20 | /// We use the convention in 21 | /// - [ *G.H. Low, I. L. Chuang* ](https://arxiv.org/abs/1707.05391) 22 | /// for relating single-qubit rotation phases to reflection operator phases. 23 | function RotationPhasesAsReflectionPhases(rotPhases : RotationPhases) 24 | : ReflectionPhases { 25 | let nPhasesRot = Length(rotPhases!); 26 | let nPhasesRef = (nPhasesRot + 1) / 2; 27 | 28 | if (nPhasesRot % 2 == 0) { 29 | fail $"Number of rotations must be odd."; 30 | } 31 | 32 | mutable phasesTarget = [0.0, size = nPhasesRef]; 33 | mutable phasesStart = [0.0, size = nPhasesRef]; 34 | 35 | if nPhasesRot == 1 { 36 | return ReflectionPhases(phasesStart, phasesTarget); 37 | } 38 | 39 | set phasesTarget w/= 0 <- ((rotPhases!)[0] - (rotPhases!)[1]) - PI(); 40 | set phasesStart w/= 0 <- -(rotPhases!)[0] + 0.5 * PI(); 41 | 42 | for idxPhases in 1 .. nPhasesRef - 2 { 43 | set phasesTarget w/= idxPhases <- ((rotPhases!)[2 * idxPhases] - (rotPhases!)[2 * idxPhases + 1]) - PI(); 44 | set phasesStart w/= idxPhases <- ((rotPhases!)[2 * idxPhases - 1] - (rotPhases!)[2 * idxPhases]) + PI(); 45 | } 46 | 47 | set phasesTarget w/= nPhasesRef - 1 <- (rotPhases!)[2 * nPhasesRef - 2] - 0.5 * PI(); 48 | set phasesStart w/= nPhasesRef - 1 <- ((rotPhases!)[2 * nPhasesRef - 3] - (rotPhases!)[2 * nPhasesRef - 2]) + PI(); 49 | return ReflectionPhases(phasesStart, phasesTarget); 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /Standard/src/AmplitudeAmplification/Types.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.AmplitudeAmplification { 5 | 6 | /// # Summary 7 | /// Phases for a sequence of partial reflections in amplitude amplification. 8 | /// 9 | /// # Named Items 10 | /// ## AboutStart 11 | /// An array of phases for reflection about the 12 | /// start state. 13 | /// ## AboutTarget 14 | /// An array of phases for reflection 15 | /// about the target state. 16 | /// 17 | /// # Remarks 18 | /// Both arrays must be of equal length. Note that in many cases, the first phase about the start state and last phase about the target state introduces a global phase shift and may be set to $0$. 19 | newtype ReflectionPhases = ( 20 | AboutStart: Double[], 21 | AboutTarget: Double[] 22 | ); 23 | 24 | /// # Summary 25 | /// Phases for a sequence of single-qubit rotations in amplitude amplification. 26 | /// 27 | /// # Remarks 28 | /// The first parameter is an array of phases for reflections, expressed as a product of single-qubit rotations. 29 | /// [ G.H. Low, I. L. Chuang, https://arxiv.org/abs/1707.05391]. 30 | newtype RotationPhases = Double[]; 31 | 32 | } 33 | 34 | 35 | -------------------------------------------------------------------------------- /Standard/src/Arithmetic/Comparators.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Arithmetic { 5 | open Microsoft.Quantum.Intrinsic; 6 | open Microsoft.Quantum.Canon; 7 | open Microsoft.Quantum.Arrays; 8 | 9 | /// # Summary 10 | /// This operation tests if an integer represented by a register of qubits 11 | /// is greater than another integer, applying an XOR of the result onto an 12 | /// output qubit. 13 | /// 14 | /// # Description 15 | /// Given two integers `x` and `y` stored in equal-size qubit registers, 16 | /// this operation checks if they satisfy `x > y`. If true, 1 is 17 | /// XORed into an output qubit. Otherwise, 0 is XORed into an output qubit. 18 | /// In other words, this operation can be represented by the unitary 19 | /// $$ 20 | /// \begin{align} 21 | /// U\ket{x}\ket{y}\ket{z} = \ket{x}\ket{y}\ket{z\oplus (x>y)}. 22 | /// \end{align} 23 | /// $$ 24 | /// 25 | /// # Input 26 | /// ## x 27 | /// First number to be compared stored in `LittleEndian` format in a qubit register. 28 | /// ## y 29 | /// Second number to be compared stored in `LittleEndian` format in a qubit register. 30 | /// ## output 31 | /// Qubit that stores the result of the comparison $x>y$. 32 | /// 33 | /// # References 34 | /// - A new quantum ripple-carry addition circuit 35 | /// Steven A. Cuccaro, Thomas G. Draper, Samuel A. Kutin, David Petrie Moulton 36 | /// https://arxiv.org/abs/quant-ph/0410184 37 | operation CompareUsingRippleCarry(x : LittleEndian, y : LittleEndian, output : Qubit) 38 | : Unit is Adj + Ctl { 39 | if (Length(x!) != Length(y!)) { 40 | fail "Size of integer registers must be equal."; 41 | } 42 | 43 | use auxiliary = Qubit(); 44 | within { 45 | let nQubitsX = Length(x!); 46 | 47 | // Take 2's complement 48 | ApplyToEachCA(X, x! + [auxiliary]); 49 | 50 | ApplyMajorityInPlace(x![0], [y![0], auxiliary]); 51 | ApplyToEachCA(MAJ, Zipped3(Most(x!), Rest(y!), Rest(x!))); 52 | } apply { 53 | X(output); 54 | CNOT(Tail(x!), output); 55 | } 56 | } 57 | 58 | } 59 | -------------------------------------------------------------------------------- /Standard/src/Arithmetic/Convert.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Arithmetic { 5 | open Microsoft.Quantum.Intrinsic; 6 | open Microsoft.Quantum.Canon; 7 | open Microsoft.Quantum.Arrays; 8 | 9 | /// # Summary 10 | /// Converts a `LittleEndian` qubit register to a `BigEndian` qubit 11 | /// register by reversing the qubit ordering. 12 | /// 13 | /// # Input 14 | /// ## input 15 | /// Qubit register in `LittleEndian` format. 16 | /// 17 | /// # Output 18 | /// Qubit register in `BigEndian` format. 19 | function LittleEndianAsBigEndian(input: LittleEndian) : BigEndian { 20 | return BigEndian(Reversed(input!)); 21 | } 22 | 23 | /// # Summary 24 | /// Converts a `BigEndian` qubit register to a `LittleEndian` qubit 25 | /// register by reversing the qubit ordering. 26 | /// 27 | /// # Input 28 | /// ## input 29 | /// Qubit register in `BigEndian` format. 30 | /// 31 | /// # Output 32 | /// Qubit register in `LittleEndian` format. 33 | function BigEndianAsLittleEndian(input: BigEndian) : LittleEndian { 34 | return LittleEndian(Reversed(input!)); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /Standard/src/Arithmetic/Measurement.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Arithmetic { 5 | open Microsoft.Quantum.Measurement; 6 | open Microsoft.Quantum.Convert; 7 | 8 | /// # Summary 9 | /// Measures the content of a quantum register and converts 10 | /// it to an integer. The measurement is performed with respect 11 | /// to the standard computational basis, i.e., the eigenbasis of `PauliZ`. 12 | /// 13 | /// # Input 14 | /// ## target 15 | /// A quantum register in the little-endian encoding. 16 | /// 17 | /// # Output 18 | /// An unsigned integer that contains the measured value of `target`. 19 | /// 20 | /// # Remarks 21 | /// This operation resets its input register to the $\ket{00\cdots 0}$ state, 22 | /// suitable for releasing back to a target machine. 23 | operation MeasureInteger(target : LittleEndian) : Int { 24 | mutable results = [Zero, size = Length(target!)]; 25 | 26 | for idx in 0 .. Length(target!) - 1 { 27 | set results w/= idx <- MResetZ((target!)[idx]); 28 | } 29 | 30 | return ResultArrayAsInt(results); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /Standard/src/Arithmetic/Properties/BuildConfiguration.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Arithmetic { 5 | 6 | /// # Summary 7 | /// If true, enables extra asserts that are expensive, but useful to debug the use of 8 | /// the arithmetic functions. 9 | /// 10 | /// # Remarks 11 | /// This function allows to configure the behavior of the library. 12 | internal function ExtraArithmeticAssertionsEnabled() : Bool { 13 | return false; 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /Standard/src/Arithmetic/Properties/NamespaceInfo.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | /// # Summary 5 | /// This namespace contains functions and operations used for coherently 6 | /// computing arithmetic. 7 | namespace Microsoft.Quantum.Arithmetic {} 8 | -------------------------------------------------------------------------------- /Standard/src/Arithmetic/Reflections.qs: -------------------------------------------------------------------------------- 1 | namespace Microsoft.Quantum.Arithmetic { 2 | open Microsoft.Quantum.Arrays; 3 | open Microsoft.Quantum.Convert; 4 | open Microsoft.Quantum.Intrinsic; 5 | open Microsoft.Quantum.Canon; 6 | open Microsoft.Quantum.Logical; 7 | 8 | /// # Summary 9 | /// Reflects a quantum register about a given classical integer. 10 | /// 11 | /// # Description 12 | /// Given a quantum register initially in the state $\sum_i \alpha_i \ket{i}$, 13 | /// where each $\ket{i}$ is a basis state representing an integer $i$, 14 | /// reflects the state of the register about the basis state for a given 15 | /// integer $\ket{j}$, 16 | /// $$ 17 | /// \sum_i (-1)^{ \delta_{ij} } \alpha_i \ket{i} 18 | /// $$ 19 | /// 20 | /// # Input 21 | /// ## index 22 | /// The classical integer indexing the basis state about which to reflect. 23 | /// 24 | /// # Remarks 25 | /// This operation is implemented in-place, without explicit allocation of 26 | /// additional auxiliary qubits. 27 | operation ReflectAboutInteger(index : Int, reg : LittleEndian) : Unit is Adj + Ctl { 28 | within { 29 | // We want to reduce to the problem of reflecting about the all-ones 30 | // state. To do that, we apply our reflection within an application 31 | // of X instructions that flip all the zeros in our index. 32 | ApplyToEachCA( 33 | CControlledCA(X), 34 | Zipped(Mapped(Not, IntAsBoolArray(index, Length(reg!))), reg!) 35 | ); 36 | } apply { 37 | Controlled Z(Most(reg!), Tail(reg!)); 38 | } 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /Standard/src/Arithmetic/Shorthand.qs: -------------------------------------------------------------------------------- 1 | namespace Microsoft.Quantum.Arithmetic { 2 | open Microsoft.Quantum.Intrinsic; 3 | open Microsoft.Quantum.Canon; 4 | 5 | /// # Summary 6 | /// This applies the in-place majority operation to 3 qubits. 7 | /// 8 | /// # Description 9 | /// If we denote the state of the target qubit as $\ket{z}$, and input states of 10 | /// the input qubits as $\ket{x}$ and $\ket{y}$, then 11 | /// this operation performs the following transformation: 12 | /// $\ket{xyz} \rightarrow \ket{x \oplus z} \ket{y \oplus z} \ket{\operatorname{MAJ} (x, y, z)}$. 13 | /// 14 | /// # Input 15 | /// ## input0 16 | /// The first input qubit. 17 | /// ## input1 18 | /// The second input qubit. 19 | /// ## target 20 | /// A qubit onto which the majority function will be applied. 21 | operation MAJ(input0 : Qubit, input1 : Qubit, target : Qubit) : Unit { 22 | body (...) { 23 | CNOT(target, input1); 24 | CNOT(target, input0); 25 | CCNOT(input1, input0, target); 26 | } 27 | adjoint auto; 28 | controlled auto; 29 | adjoint controlled auto; 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /Standard/src/Arithmetic/Types.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Arithmetic { 5 | 6 | /// # Summary 7 | /// Register that encodes an unsigned integer in little-endian order. The 8 | /// qubit with index `0` encodes the lowest bit of an unsigned integer. 9 | /// 10 | /// # Remarks 11 | /// We abbreviate `LittleEndian` as `LE` in the documentation. 12 | newtype LittleEndian = Qubit[]; 13 | 14 | /// # Summary 15 | /// Register that encodes an unsigned integer in big-endian order. The 16 | /// qubit with index `0` encodes the highest bit of an unsigned integer. 17 | /// 18 | /// # Remarks 19 | /// We abbreviate `BigEndian` as `BE` in the documentation. 20 | newtype BigEndian = Qubit[]; 21 | 22 | /// # Summary 23 | /// Little-endian unsigned integers in QFT basis. 24 | /// 25 | /// # Description 26 | /// If $\ket{x}$ is the little-endian encoding of the integer 27 | /// $x$ in the computational basis, 28 | /// then $\operatorname{QFTLE} \ket{x}$ is the encoding of $x$ in the QFT 29 | /// basis. 30 | /// 31 | /// # Remarks 32 | /// We abbreviate `PhaseLittleEndian` as `PhaseLE` in the documentation. 33 | /// 34 | /// # See Also 35 | /// - Microsoft.Quantum.Canon.QFT 36 | /// - Microsoft.Quantum.Canon.QFTLE 37 | newtype PhaseLittleEndian = Qubit[]; 38 | 39 | } 40 | -------------------------------------------------------------------------------- /Standard/src/Arrays/All.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Arrays { 5 | open Microsoft.Quantum.Logical; 6 | 7 | /// # Summary 8 | /// Given an array and a predicate that is defined 9 | /// for the elements of the array, and checks if all elements of the 10 | /// array satisfy the predicate. 11 | /// 12 | /// # Remarks 13 | /// The function is defined for generic types, i.e., whenever we have 14 | /// an array `'T[]` and a function `predicate: 'T -> Bool` we can produce 15 | /// a `Bool` value that indicates if all elements satisfy `predicate`. 16 | /// 17 | /// # Type Parameters 18 | /// ## 'T 19 | /// The type of `array` elements. 20 | /// 21 | /// # Input 22 | /// ## predicate 23 | /// A function from `'T` to `Bool` that is used to check elements. 24 | /// ## array 25 | /// An array of elements over `'T`. 26 | /// 27 | /// # Output 28 | /// A `Bool` value of the AND function of the predicate applied to all elements. 29 | /// 30 | /// # Example 31 | /// The following code checks whether all elements of the array are non-zero: 32 | /// ```qsharp 33 | /// open Microsoft.Quantum.Arrays; 34 | /// open Microsoft.Quantum.Logical; 35 | /// 36 | /// function AllDemo() : Unit { 37 | /// let predicate = NotEqualI(_, 0); 38 | /// let isNonZero = All(predicate, [2, 3, 4, 5, 6, 0]); 39 | /// Message($"{isNonZero}"); 40 | /// } 41 | /// ``` 42 | /// 43 | function All<'T> (predicate : ('T -> Bool), array : 'T[]) : Bool { 44 | return Fold(And, true, Mapped(predicate, array)); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /Standard/src/Arrays/Any.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Arrays { 5 | open Microsoft.Quantum.Logical; 6 | 7 | /// # Summary 8 | /// Given an array and a predicate that is defined 9 | /// for the elements of the array, checks if at least one element of 10 | /// the array satisfies the predicate. 11 | /// 12 | /// # Remarks 13 | /// The function is defined for generic types, i.e., whenever we have 14 | /// an array `'T[]` and a function `predicate: 'T -> Bool` we can produce 15 | /// a `Bool` value that indicates if some element satisfies `predicate`. 16 | /// 17 | /// # Type Parameters 18 | /// ## 'T 19 | /// The type of `array` elements. 20 | /// 21 | /// # Input 22 | /// ## predicate 23 | /// A function from `'T` to `Bool` that is used to check elements. 24 | /// ## array 25 | /// An array of elements over `'T`. 26 | /// 27 | /// # Output 28 | /// A `Bool` value of the OR function of the predicate applied to all elements. 29 | /// 30 | /// # Example 31 | /// ```qsharp 32 | /// open Microsoft.Quantum.Arrays; 33 | /// open Microsoft.Quantum.Logical; 34 | /// 35 | /// function IsThreePresent() : Bool { 36 | /// let arrayOfInts = [1, 2, 3, 4, 5]; 37 | /// let is3Present = IsNumberPresentInArray(3, arrayOfInts); 38 | /// return is3Present; 39 | /// } 40 | /// 41 | /// function IsNumberPresentInArray(n : Int, array : Int[]) : Bool { 42 | /// return Any(EqualI(_, n), array); 43 | /// } 44 | /// ``` 45 | function Any<'T> (predicate : ('T -> Bool), array : 'T[]) : Bool { 46 | return Fold(Or, false, Mapped(predicate, array)); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /Standard/src/Arrays/DrawMany.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Arrays { 5 | 6 | /// # Summary 7 | /// Repeats an operation for a given number of samples, collecting its outputs 8 | /// in an array. 9 | /// 10 | /// # Input 11 | /// ## op 12 | /// The operation to be called repeatedly. 13 | /// ## nSamples 14 | /// The number of samples of calling `op` to collect. 15 | /// ## input 16 | /// The input to be passed to `op`. 17 | /// 18 | /// # Type Parameters 19 | /// ## TInput 20 | /// The type of input expected by `op`. 21 | /// ## TOutput 22 | /// The type of output returned by `op`. 23 | /// 24 | /// # Example 25 | /// The following samples an integer, given an operation 26 | /// that samples a single bit at a time. 27 | /// ```qsharp 28 | /// let randomInteger = BoolArrayAsInt(DrawMany(SampleRandomBit, 16, ())); 29 | /// ``` 30 | /// 31 | /// # See Also 32 | /// - Microsoft.Quantum.Canon.Repeat 33 | operation DrawMany<'TInput, 'TOutput>(op : ('TInput => 'TOutput), nSamples : Int, input : 'TInput) 34 | : 'TOutput[] { 35 | if nSamples == 0 { 36 | return []; 37 | } 38 | 39 | let first = op(input); 40 | mutable outputs = [first, size = nSamples]; 41 | for idx in 1..nSamples - 1 { 42 | set outputs w/= idx <- op(input); 43 | } 44 | return outputs; 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /Standard/src/Arrays/Enumeration.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Arrays { 5 | 6 | internal function Identity<'T>(input : 'T) : 'T { return input; } 7 | 8 | /// # Summary 9 | /// Given an array, returns a new array containing elements of the original 10 | /// array along with the indices of each element. 11 | /// 12 | /// # Type Parameters 13 | /// ## 'TElement 14 | /// The type of elements of the array. 15 | /// 16 | /// # Input 17 | /// ## array 18 | /// An array whose elements are to be enumerated. 19 | /// 20 | /// # Output 21 | /// A new array containing elements of the original array along with their 22 | /// indices. 23 | /// 24 | /// # Example 25 | /// The following `for` loops are equivalent: 26 | /// ```qsharp 27 | /// for (idx in IndexRange(array)) { 28 | /// let element = array[idx]; 29 | /// ... 30 | /// } 31 | /// for ((idx, element) in Enumerated(array)) { ... } 32 | /// ``` 33 | function Enumerated<'TElement>(array : 'TElement[]) : (Int, 'TElement)[] { 34 | return MappedByIndex(Identity<(Int, 'TElement)>, array); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /Standard/src/Arrays/Fold.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Arrays { 5 | 6 | /// # Summary 7 | /// Iterates a function `f` through an array `array`, returning 8 | /// `f(...f(f(initialState, array[0]), array[1]), ...)`. 9 | /// 10 | /// # Type Parameters 11 | /// ## 'State 12 | /// The type of states the `folder` function operates on, i.e., accepts as its first 13 | /// argument and returns. 14 | /// ## 'T 15 | /// The type of `array` elements. 16 | /// 17 | /// # Input 18 | /// ## folder 19 | /// A function to be folded over the array. 20 | /// ## state 21 | /// The initial state of the folder. 22 | /// ## array 23 | /// An array of values to be folded over. 24 | /// 25 | /// # Output 26 | /// The final state returned by the folder after iterating over 27 | /// all elements of `array`. 28 | /// 29 | /// # Example 30 | /// ```qsharp 31 | /// function Plus(a : Double, b : Double) { 32 | /// return a + b; 33 | /// } 34 | /// function Sum(xs : Double[]) { 35 | /// return Fold(Plus, 0.0, xs); 36 | /// } 37 | /// ``` 38 | function Fold<'State, 'T> (folder : (('State, 'T) -> 'State), state : 'State, array : 'T[]) : 'State { 39 | mutable current = state; 40 | 41 | for idxElement in IndexRange(array) { 42 | set current = folder(current, array[idxElement]); 43 | } 44 | 45 | return current; 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /Standard/src/Arrays/ForEach.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Quantum.Simulation.Core; 5 | using System; 6 | 7 | namespace Microsoft.Quantum.Arrays 8 | { 9 | public partial class ForEach<__T__, __U__> 10 | { 11 | public override RuntimeMetadata GetRuntimeMetadata(IApplyData args) 12 | { 13 | var metadata = base.GetRuntimeMetadata(args); 14 | if (metadata == null) throw new NullReferenceException($"Null RuntimeMetadata found for {this.ToString()}."); 15 | metadata.IsComposite = true; 16 | return metadata; 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Standard/src/Arrays/Interleaved.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Arrays { 5 | open Microsoft.Quantum.Diagnostics; 6 | 7 | /// # Summary 8 | /// Interleaves two arrays of (almost) same size. 9 | /// 10 | /// # Description 11 | /// This function returns the interleaving of two arrays, starting 12 | /// with the first element from the first array, then the first 13 | /// element from the second array, and so on. 14 | /// 15 | /// The first array must either be 16 | /// of the same length as the second one, or can have one more element. 17 | /// 18 | /// # Type Parameters 19 | /// ## 'T 20 | /// The type of each element of `first` and `second`. 21 | /// 22 | /// # Input 23 | /// ## first 24 | /// The first array to be interleaved. 25 | /// 26 | /// ## second 27 | /// The second array to be interleaved. 28 | /// 29 | /// # Output 30 | /// Interleaved array 31 | /// 32 | /// # Example 33 | /// ```qsharp 34 | /// // same as int1 = [1, -1, 2, -2, 3, -3] 35 | /// let int1 = Interleaved([1, 2, 3], [-1, -2, -3]) 36 | /// 37 | /// // same as int2 = [false, true, false, true, false] 38 | /// let int2 = Interleaved(ConstantArray(3, false), ConstantArray(2, true)); 39 | /// ``` 40 | function Interleaved<'T>(first : 'T[], second : 'T[]) : 'T[] { 41 | let lFirst = Length(first); 42 | let lSecond = Length(second); 43 | 44 | Fact(lFirst >= lSecond and lFirst - lSecond <= 1, "Array `first` is either of same size as `second`, or has one more element"); 45 | 46 | if lFirst == 0 { 47 | return []; 48 | } else { 49 | return [first[0], size = lFirst + lSecond] 50 | w/ 0..2..(lFirst + lSecond - 1) <- first 51 | w/ 1..2..(lFirst + lSecond - 1) <- second; 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /Standard/src/Arrays/Properties/NamespaceInfo.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | /// # Summary 5 | /// This namespace contains functions for creating and manipulating arrays of 6 | /// data. 7 | namespace Microsoft.Quantum.Arrays {} 8 | -------------------------------------------------------------------------------- /Standard/src/Arrays/Reductions.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Arrays { 5 | 6 | /// # Summary 7 | /// Combines Mapped and Fold into a single function 8 | /// 9 | /// # Description 10 | /// This function iterates the `fn` function through the array, starting from 11 | /// an initial state `state` and returns all intermediate values, not including 12 | /// the initial state. 13 | /// 14 | /// # Type Parameters 15 | /// ## 'State 16 | /// The type of states that the `fn` function operates on, i.e., accepts as its first 17 | /// input and returns. 18 | /// ## 'T 19 | /// The type of `array` elements. 20 | /// 21 | /// # Input 22 | /// ## fn 23 | /// A function to be folded over the array 24 | /// 25 | /// ## state 26 | /// The initial state to be folded 27 | /// 28 | /// ## array 29 | /// An array of values to be folded over 30 | /// 31 | /// # Output 32 | /// All intermediate states, including the final state, but not the initial state. 33 | /// The length of the output array is of the same length as `array`. 34 | /// 35 | /// # Remark 36 | /// This function generalizes `Fold` since 37 | /// `Tail(CumulativeFolded(fn, state, array))` is the same as `Fold(fn, state, array)`. 38 | /// 39 | /// # Example 40 | /// ```qsharp 41 | /// // same as sums = [1, 3, 6, 10, 15] 42 | /// let sums = CumulativeFolded(PlusI, 0, SequenceI(1, 5)); 43 | /// ``` 44 | function CumulativeFolded<'State, 'T>(fn : (('State, 'T) -> 'State), state : 'State, array : 'T[]) : 'State[] { 45 | mutable current = state; 46 | // initialize with current, and then overwrite in loop 47 | mutable result = [current, size = Length(array)]; 48 | 49 | for (i, elem) in Enumerated(array) { 50 | set current = fn(current, elem); 51 | set result w/= i <- current; 52 | } 53 | 54 | return result; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /Standard/src/Arrays/Search.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Arrays { 5 | open Microsoft.Quantum.Intrinsic; 6 | open Microsoft.Quantum.Canon; 7 | 8 | /// # Summary 9 | /// Returns the first index of the first element in an array that satisfies 10 | /// a given predicate. If no such element exists, returns -1. 11 | /// 12 | /// # Input 13 | /// ## predicate 14 | /// A predicate function acting on elements of the array. 15 | /// ## arr 16 | /// An array to be searched using the given predicate. 17 | /// 18 | /// # Output 19 | /// Either the smallest index `idx` such that `predicate(arr[idx])` is true, 20 | /// or -1 if no such element exists. 21 | /// 22 | /// # Example 23 | /// Suppose that `IsEven : Int -> Bool` is a function that returns `true` 24 | /// if and only if its input is even. Then, this can be used with `IndexOf` 25 | /// to find the first even element in an array: 26 | /// ```qsharp 27 | /// let items = [1, 3, 17, 2, 21]; 28 | /// let idx = IndexOf(IsEven, items); // returns 3 29 | /// ``` 30 | function IndexOf<'T>(predicate : ('T -> Bool), arr : 'T[]) : Int { 31 | for idx in IndexRange(arr) { 32 | if predicate(arr[idx]) { 33 | return idx; 34 | } 35 | } 36 | return -1; 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /Standard/src/Arrays/Unique.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Arrays { 5 | /// # Summary 6 | /// Returns a new array that has no equal adjacent elements. 7 | /// 8 | /// # Description 9 | /// Given some array of elements and a function to test equality, this 10 | /// function returns a new array in which the relative order of elements 11 | /// is kept, but all adjacent elements which are equal are filtered to 12 | /// just a single element. 13 | /// 14 | /// # Type Parameters 15 | /// ## 'T 16 | /// The type of each element of `array`. 17 | /// 18 | /// # Input 19 | /// ## equal 20 | /// A function that compares two elements such that `a` is considered to 21 | /// be equal to `b` if `equal(a, b)` is `true`. 22 | /// ## array 23 | /// The array to be filtered for unique elements. 24 | /// 25 | /// # Output 26 | /// Array with no equal adjacent elements. 27 | /// 28 | /// # Remarks 29 | /// If there are multiple elements that are equal but not next to each other, 30 | /// there will be multiple occurrences in the output array. Use this function 31 | /// together with `Sorted` to get an array with overall unique elements. 32 | /// 33 | /// # Example 34 | /// ```qsharp 35 | /// let unique1 = Unique(EqualI, [1, 1, 3, 3, 2, 5, 5, 5, 7]); 36 | /// // same as [1, 3, 2, 5, 7] 37 | /// let unique2 = Unique(EqualI, [2, 2, 1, 1, 2, 2, 1, 1]); 38 | /// // same as [2, 1, 2, 1]; 39 | /// let unique3 = Unique(EqualI, Sorted(LessThanOrEqualI, [2, 2, 1, 1, 2, 2, 1, 1])); 40 | /// // same as [1, 2]; 41 | /// ``` 42 | function Unique<'T>(equal : (('T, 'T) -> Bool), array : 'T[]) : 'T[] { 43 | if Length(array) == 0 { 44 | return []; 45 | } 46 | 47 | mutable unique = ConstantArray(Length(array), Head(array)); 48 | mutable count = 1; 49 | 50 | for elem in Rest(array) { 51 | if (not equal(elem, unique[count - 1])) { 52 | set unique w/= count <- elem; 53 | set count += 1; 54 | } 55 | } 56 | 57 | return unique[0..count - 1]; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /Standard/src/Bitwise/Properties/NamespaceInfo.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | /// # Summary 5 | /// This namespace contains functions for acting on the bitwise representation of 6 | /// classical data types. 7 | /// 8 | /// # Description 9 | /// A lot of functions in this namespace offer the same functionality as the 10 | /// [bitwise expressions](xref:microsoft.quantum.qsharp.bitwiseexpressions). 11 | namespace Microsoft.Quantum.Bitwise { } 12 | -------------------------------------------------------------------------------- /Standard/src/Canon/Combinators/ApplyToEach.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Quantum.Simulation.Core; 5 | using System; 6 | 7 | namespace Microsoft.Quantum.Canon 8 | { 9 | public partial class ApplyToEach<__T__> 10 | { 11 | public override RuntimeMetadata GetRuntimeMetadata(IApplyData args) 12 | { 13 | var metadata = base.GetRuntimeMetadata(args); 14 | if (metadata == null) throw new NullReferenceException($"Null RuntimeMetadata found for {this.ToString()}."); 15 | metadata.IsComposite = true; 16 | return metadata; 17 | } 18 | } 19 | 20 | public partial class ApplyToEachC<__T__> 21 | { 22 | public override RuntimeMetadata GetRuntimeMetadata(IApplyData args) 23 | { 24 | var metadata = base.GetRuntimeMetadata(args); 25 | if (metadata == null) throw new NullReferenceException($"Null RuntimeMetadata found for {this.ToString()}."); 26 | metadata.IsComposite = true; 27 | return metadata; 28 | } 29 | } 30 | 31 | public partial class ApplyToEachA<__T__> 32 | { 33 | public override RuntimeMetadata GetRuntimeMetadata(IApplyData args) 34 | { 35 | var metadata = base.GetRuntimeMetadata(args); 36 | if (metadata == null) throw new NullReferenceException($"Null RuntimeMetadata found for {this.ToString()}."); 37 | metadata.IsComposite = true; 38 | return metadata; 39 | } 40 | } 41 | 42 | public partial class ApplyToEachCA<__T__> 43 | { 44 | public override RuntimeMetadata GetRuntimeMetadata(IApplyData args) 45 | { 46 | var metadata = base.GetRuntimeMetadata(args); 47 | if (metadata == null) throw new NullReferenceException($"Null RuntimeMetadata found for {this.ToString()}."); 48 | metadata.IsComposite = true; 49 | return metadata; 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /Standard/src/Canon/Combinators/Compose.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Canon { 5 | 6 | /// # Summary 7 | /// Returns the output of the composition of `inner` and `outer` 8 | /// for a given input. 9 | internal function ComposedOutput<'T, 'U, 'V> (outer : ('U -> 'V), inner : ('T -> 'U), target : 'T) : 'V { 10 | return outer(inner(target)); 11 | } 12 | 13 | /// # Summary 14 | /// Returns the composition of two functions. 15 | /// 16 | /// # Description 17 | /// Given two functions $f$ and $g$, returns a new function representing 18 | /// $f \circ g$. 19 | /// 20 | /// # Input 21 | /// ## outer 22 | /// The second function to be applied. 23 | /// ## inner 24 | /// The first function to be applied. 25 | /// 26 | /// # Output 27 | /// A new function $h$ such that for all inputs $x$, $f(g(x)) = h(x)$. 28 | /// 29 | /// # Type Parameters 30 | /// ## 'T 31 | /// The input type of the first function to be applied. 32 | /// ## 'U 33 | /// The output type of the first function to be applied and the input type 34 | /// of the second function to be applied. 35 | /// ## 'V 36 | /// The output type of the second function to be applied. 37 | function Compose<'T, 'U, 'V> (outer : ('U -> 'V), inner : ('T -> 'U)) : ('T -> 'V) { 38 | return ComposedOutput(outer, inner, _); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /Standard/src/Canon/Combinators/SinglyControlled.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Canon { 5 | 6 | /// # Summary 7 | /// Given a controllable operation, returns a controlled version of that operation 8 | /// accepting exactly one control qubit. 9 | /// 10 | /// # Input 11 | /// ## op 12 | /// The operation to be controlled. 13 | /// 14 | /// # Output 15 | /// A controlled variant of `op` accepting exactly one control qubit. 16 | /// 17 | /// # Example 18 | /// To add the weight (number of "1" bits) of a control register to 19 | /// a target register: 20 | /// ```qsharp 21 | /// ApplyToEachCA( 22 | /// SinglyControlled(IncrementByInteger)(_, (1, target)), 23 | /// controls) 24 | /// ); 25 | /// ``` 26 | /// 27 | /// # See Also 28 | /// - Microsoft.Quantum.Canon.SinglyControlledA 29 | function SinglyControlled<'T>(op : 'T => Unit is Ctl) : (Qubit, 'T) => Unit is Ctl { 30 | return (ctrl, originalInput) => Controlled op([ctrl], originalInput); 31 | } 32 | 33 | /// # Summary 34 | /// Given a controllable operation, returns a controlled version of that operation 35 | /// accepting exactly one control qubit. 36 | /// 37 | /// # Input 38 | /// ## op 39 | /// The operation to be controlled. 40 | /// 41 | /// # Output 42 | /// A controlled variant of `op` accepting exactly one control qubit. 43 | /// 44 | /// # Example 45 | /// To add the weight (number of "1" bits) of a control register to 46 | /// a target register: 47 | /// ```qsharp 48 | /// ApplyToEachCA( 49 | /// SinglyControlledA(IncrementByInteger)(_, (1, target)), 50 | /// controls) 51 | /// ); 52 | /// ``` 53 | /// 54 | /// # See Also 55 | /// - Microsoft.Quantum.Canon.SinglyControlled 56 | function SinglyControlledA<'T>(op : 'T => Unit is Adj + Ctl) : (Qubit, 'T) => Unit is Adj + Ctl { 57 | return (ctrl, originalInput) => Controlled op([ctrl], originalInput); 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /Standard/src/Canon/CommonGates.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #nullable enable 5 | 6 | using System; 7 | using System.Collections.Generic; 8 | using Microsoft.Quantum.Simulation.Core; 9 | 10 | namespace Microsoft.Quantum.Canon 11 | { 12 | public partial class CX 13 | { 14 | public override RuntimeMetadata? GetRuntimeMetadata(IApplyData args) => 15 | args.Value switch 16 | { 17 | (Qubit ctrl, Qubit target) => new RuntimeMetadata() 18 | { 19 | Label = "X", 20 | IsControlled = true, 21 | Controls = new List() { ctrl }, 22 | Targets = new List() { target }, 23 | }, 24 | _ => throw new Exception($"Failed to retrieve runtime metadata for {this.ToString()}."), 25 | }; 26 | } 27 | 28 | public partial class CY 29 | { 30 | public override RuntimeMetadata? GetRuntimeMetadata(IApplyData args) => 31 | args.Value switch 32 | { 33 | (Qubit ctrl, Qubit target) => new RuntimeMetadata() 34 | { 35 | Label = "Y", 36 | IsControlled = true, 37 | Controls = new List() { ctrl }, 38 | Targets = new List() { target }, 39 | }, 40 | _ => throw new Exception($"Failed to retrieve runtime metadata for {this.ToString()}."), 41 | }; 42 | } 43 | 44 | public partial class CZ 45 | { 46 | public override RuntimeMetadata? GetRuntimeMetadata(IApplyData args) => 47 | args.Value switch 48 | { 49 | (Qubit ctrl, Qubit target) => new RuntimeMetadata() 50 | { 51 | Label = "Z", 52 | IsControlled = true, 53 | Controls = new List() { ctrl }, 54 | Targets = new List() { target }, 55 | }, 56 | _ => throw new Exception($"Failed to retrieve runtime metadata for {this.ToString()}."), 57 | }; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /Standard/src/Canon/DataStructures/Pairs.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Canon 5 | { 6 | 7 | /// # Summary 8 | /// Given a pair, returns its first element. 9 | /// 10 | /// # Type Parameters 11 | /// ## 'T 12 | /// The type of the pair's first member. 13 | /// ## 'U 14 | /// The type of the pair's second member. 15 | /// 16 | /// # Input 17 | /// ## pair 18 | /// A tuple with two elements. 19 | /// 20 | /// # Output 21 | /// The first element of `pair`. 22 | function Fst<'T, 'U> (pair : ('T, 'U)) : 'T { 23 | let (fst, snd) = pair; 24 | return fst; 25 | } 26 | 27 | 28 | /// # Summary 29 | /// Given a pair, returns its second element. 30 | /// 31 | /// # Type Parameters 32 | /// ## 'T 33 | /// The type of the pair's first member. 34 | /// ## 'U 35 | /// The type of the pair's second member. 36 | /// 37 | /// # Input 38 | /// ## pair 39 | /// A tuple with two elements. 40 | /// 41 | /// # Output 42 | /// The second element of `pair`. 43 | function Snd<'T, 'U> (pair : ('T, 'U)) : 'U { 44 | let (fst, snd) = pair; 45 | return snd; 46 | } 47 | 48 | } 49 | 50 | 51 | -------------------------------------------------------------------------------- /Standard/src/Canon/Deprecated.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Canon { 5 | open Microsoft.Quantum.Arithmetic; 6 | open Microsoft.Quantum.Logical; 7 | 8 | /// # Deprecated 9 | /// Please use @"Microsoft.Quantum.Logical.Xor". 10 | @Deprecated("Microsoft.Quantum.Logical.Xor") 11 | function XOR(bit1 : Bool, bit2 : Bool) : Bool { 12 | return Xor(bit1, bit2); 13 | } 14 | 15 | @Deprecated("Microsoft.Quantum.Canon.ApplyCNOTChain") 16 | operation CNOTChain(qubits : Qubit[]) : Unit is Adj + Ctl { 17 | ApplyCNOTChain(qubits); 18 | } 19 | 20 | @Deprecated("Microsoft.Quantum.Canon.ApplyCNOTChainWithTarget") 21 | operation CNOTChainTarget(qubits : Qubit[], targetQubit : Qubit) 22 | : Unit is Adj + Ctl { 23 | ApplyCNOTChainWithTarget(qubits, targetQubit); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /Standard/src/Canon/Enumeration/Deprecated.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Canon { 5 | 6 | @Deprecated("Microsoft.Quantum.Canon.DecomposedIntoTimeStepsCA") 7 | function DecomposeIntoTimeStepsCA<'T>( 8 | (nSteps : Int, op : ((Int, Double, 'T) => Unit is Adj + Ctl)), 9 | trotterOrder : Int 10 | ) 11 | : ((Double, 'T) => Unit is Adj + Ctl) { 12 | return DecomposedIntoTimeStepsCA((nSteps, op), trotterOrder); 13 | } 14 | 15 | } 16 | 17 | 18 | -------------------------------------------------------------------------------- /Standard/src/Canon/Properties/NamespaceInfo.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | /// # Summary 5 | /// This namespace contains a variety of useful operations and functions. 6 | /// 7 | /// # Description 8 | /// To learn more about the operations in this namespace, see 9 | /// [Higher-Order Control Flow](xref:microsoft.quantum.libraries.overview-standard.control-flow) and 10 | /// [Quantum Fourier Transform](xref:microsoft.quantum.libraries.overview.standard.algorithms#quantum-fourier-transform). 11 | namespace Microsoft.Quantum.Canon {} 12 | -------------------------------------------------------------------------------- /Standard/src/Canon/Range.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Canon { 5 | 6 | /// # Summary 7 | /// Returns true if and only if input range is empty. 8 | /// 9 | /// # Input 10 | /// ## rng 11 | /// Any range 12 | /// 13 | /// # Output 14 | /// True, if and only if `rng` is empty 15 | /// 16 | /// # Remark 17 | /// This function needs to check at most one range index 18 | /// to determine whether the range is empty. 19 | function IsRangeEmpty(rng : Range) : Bool { 20 | for idx in rng { 21 | return false; 22 | } 23 | return true; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Standard/src/Canon/Registers.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Canon { 5 | open Microsoft.Quantum.Intrinsic; 6 | 7 | /// # Summary 8 | /// Uses SWAP gates to Reversed the order of the qubits in 9 | /// a register. 10 | /// 11 | /// # Input 12 | /// ## register 13 | /// The qubits order of which should be reversed using SWAP gates 14 | operation SwapReverseRegister (register : Qubit[]) : Unit { 15 | body (...) { 16 | let totalQubits = Length(register); 17 | let halfTotal = totalQubits / 2; 18 | 19 | for i in 0 .. halfTotal - 1 { 20 | SWAP(register[i], register[(totalQubits - i) - 1]); 21 | } 22 | } 23 | 24 | adjoint self; 25 | controlled distribute; 26 | controlled adjoint self; 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /Standard/src/Canon/Utils/Predicates.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Canon 5 | { 6 | 7 | /// # Summary 8 | /// Tests if a given Result value is equal to `Zero`. 9 | /// 10 | /// # Input 11 | /// ## input 12 | /// `Result` value to be tested. 13 | /// # Output 14 | /// Returns `true` if `input` is equal to `Zero`. 15 | function IsResultZero (input : Result) : Bool 16 | { 17 | return input == Zero; 18 | } 19 | 20 | 21 | /// # Summary 22 | /// Tests if a given Result value is equal to `One`. 23 | /// 24 | /// # Input 25 | /// ## input 26 | /// `Result` value to be tested. 27 | /// # Output 28 | /// Returns `true` if `input` is equal to `One`. 29 | function IsResultOne (input : Result) : Bool 30 | { 31 | return input == One; 32 | } 33 | 34 | } 35 | 36 | 37 | -------------------------------------------------------------------------------- /Standard/src/Characterization/Deprecated.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Characterization { 5 | open Microsoft.Quantum.Measurement as Meas; 6 | open Microsoft.Quantum.Intrinsic; 7 | open Microsoft.Quantum.Arrays; 8 | 9 | /// # Deprecated 10 | /// Please use @"Microsoft.Quantum.Measurement.MeasureAllZ". 11 | @Deprecated("Microsoft.Quantum.Measurement.MeasureAllZ") 12 | operation MeasureAllZ(register : Qubit[]) : Result { 13 | return Measure(ConstantArray(Length(register), PauliZ), register); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /Standard/src/Characterization/PhaseEstimation/Quantum.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Characterization { 5 | open Microsoft.Quantum.Arithmetic; 6 | open Microsoft.Quantum.Intrinsic; 7 | open Microsoft.Quantum.Diagnostics; 8 | open Microsoft.Quantum.Oracles; 9 | open Microsoft.Quantum.Canon; 10 | 11 | /// # Summary 12 | /// Performs the quantum phase estimation algorithm for a given oracle `U` and `targetState`, 13 | /// reading the phase into a big-endian quantum register. 14 | /// 15 | /// # Input 16 | /// ## oracle 17 | /// An operation implementing $U^m$ for given integer powers m. 18 | /// ## targetState 19 | /// A quantum register representing the state $\ket{\phi}$ acted on by $U$. If $\ket{\phi}$ is an 20 | /// eigenstate of $U$, $U\ket{\phi} = e^{i\phi} \ket{\phi}$ for $\phi \in [0, 2\pi)$ an unknown phase. 21 | /// ## controlRegister 22 | /// A big-endian representation integer register that can be used 23 | /// to control the provided oracle, and that will contain the a representation of $\phi$ following 24 | /// the application of this operation. The controlRegister is assumed to start in the initial 25 | /// state $\ket{00\cdots 0}$, where the length of the register indicates the desired precision. 26 | operation QuantumPhaseEstimation (oracle : DiscreteOracle, targetState : Qubit[], controlRegister : BigEndian) : Unit is Adj + Ctl { 27 | let nQubits = Length(controlRegister!); 28 | AssertAllZeroWithinTolerance(controlRegister!, 1E-10); 29 | ApplyToEachCA(H, controlRegister!); 30 | 31 | for idxControlQubit in 0 .. nQubits - 1 { 32 | let control = (controlRegister!)[idxControlQubit]; 33 | let power = 2 ^ ((nQubits - idxControlQubit) - 1); 34 | Controlled oracle!([control], (power, targetState)); 35 | } 36 | 37 | Adjoint QFT(controlRegister); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /Standard/src/Characterization/Properties/NamespaceInfo.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | /// # Summary 5 | /// This namespace contains functions and operations for learning properties of 6 | /// quantum states and processes, including tomography and phase estimation. 7 | /// 8 | /// # Description 9 | /// To learn more about this namespace, see 10 | /// [Quantum characterization and statistics](xref:microsoft.quantum.libraries.overview.characterization). 11 | namespace Microsoft.Quantum.Characterization {} 12 | -------------------------------------------------------------------------------- /Standard/src/Convert/Properties/NamespaceInfo.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | /// # Summary 5 | /// This namespace contains functions for converting between various Q# data 6 | /// types. 7 | /// 8 | /// # Description 9 | /// To learn more about this namespace, see 10 | /// [Type Conversions](xref:microsoft.quantum.libraries.overview.convert). 11 | namespace Microsoft.Quantum.Convert {} 12 | -------------------------------------------------------------------------------- /Standard/src/Diagnostics/Asserts.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Diagnostics { 5 | open Microsoft.Quantum.Intrinsic; 6 | open Microsoft.Quantum.Convert; 7 | open Microsoft.Quantum.Math; 8 | 9 | /// # Summary 10 | /// Asserts that the phase of an equal superposition state has the expected value. 11 | /// 12 | /// # Description 13 | /// This operation asserts that the phase $\phi$ of a quantum state 14 | /// that may be expressed as 15 | /// $\frac{e^{i t}}{\sqrt{2}}(e^{i\phi}\ket{0} + e^{-i\phi}\ket{1})$ 16 | /// for some arbitrary real $t$ has the expected value. 17 | /// 18 | /// # Input 19 | /// ## expected 20 | /// The expected value of $\phi \in (-\pi,\pi]$. 21 | /// 22 | /// ## qubit 23 | /// The qubit that stores the expected state. 24 | /// 25 | /// ## tolerance 26 | /// Absolute tolerance on the difference between actual and expected. 27 | /// 28 | /// # Example 29 | /// The following assert succeeds: 30 | /// `qubit` is in state $\ket{\psi}=e^{i 0.5}\sqrt{1/2}\ket{0}+e^{i 0.5}\sqrt{1/2}\ket{1}$; 31 | /// - `AssertPhase(0.0, qubit, 10e-10);` 32 | /// 33 | /// `qubit` is in state $\ket{\psi}=e^{i 0.5}\sqrt{1/2}\ket{0}+e^{-i 0.5}\sqrt{1/2}\ket{1}$; 34 | /// - `AssertPhase(0.5, qubit, 10e-10);` 35 | /// 36 | /// `qubit` is in state $\ket{\psi}=e^{-i 2.2}\sqrt{1/2}\ket{0}+e^{i 0.2}\sqrt{1/2}\ket{1}$; 37 | /// - `AssertPhase(-1.2, qubit, 10e-10);` 38 | operation AssertPhase(expected : Double, qubit : Qubit, tolerance : Double) : Unit { 39 | let exptectedProbX = Cos(expected) * Cos(expected); 40 | let exptectedProbY = Sin(-1.0 * expected + PI() / 4.0) * Sin(-1.0 * expected + PI() / 4.0); 41 | AssertMeasurementProbability([PauliZ], [qubit], Zero, 0.5, $"AssertPhase failed. Was not given a uniform superposition.", tolerance); 42 | AssertMeasurementProbability([PauliY], [qubit], Zero, exptectedProbY, $"AssertPhase failed. PauliY Zero basis did not give probability {exptectedProbY}.", tolerance); 43 | AssertMeasurementProbability([PauliX], [qubit], Zero, exptectedProbX, $"AssertPhase failed. PauliX Zero basis did not give probability {exptectedProbX}.", tolerance); 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /Standard/src/Diagnostics/Deprecated.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Canon { 5 | 6 | @Deprecated("Microsoft.Quantum.Diagnostics.AssertPhase") 7 | operation AssertPhase(expected : Double, qubit : Qubit, tolerance : Double) : Unit { 8 | Microsoft.Quantum.Diagnostics.AssertPhase(expected, qubit, tolerance); 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /Standard/src/Diagnostics/Internal.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Diagnostics { 5 | open Microsoft.Quantum.Intrinsic; 6 | 7 | /// # Summary 8 | /// Internal function used to fail with meaningful error messages. 9 | /// 10 | /// # Remarks 11 | /// This function is intended to be emulated by simulation runtimes, so as 12 | /// to allow forwarding formatted contradictions. 13 | internal function FormattedFailure<'T>(actual : 'T, expected : 'T, message : String) : Unit { 14 | fail $"{message}\n\tExpected:\t{expected}\n\tActual:\t{actual}"; 15 | } 16 | 17 | /// # Summary 18 | /// Uses DumpRegister to provide diagnostics on the state of a reference and 19 | /// target register. Written as separate operation to allow overriding and 20 | /// interpreting as separate registers, rather than as a single combined 21 | /// register. 22 | internal operation DumpReferenceAndTarget(reference : Qubit[], target : Qubit[]) : Unit is Adj + Ctl { 23 | DumpRegister((), reference + target); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /Standard/src/Diagnostics/Properties/NamespaceInfo.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | /// # Summary 5 | /// This namespace contains function and operations that help 6 | /// ensure correctness of Q# programs and inspect their behavior. 7 | /// 8 | /// # Description 9 | /// To learn more about the testing and diagnostics tools available in Q#, see 10 | /// [Diagnostics](xref:microsoft.quantum.libraries.overview.diagnostics) and 11 | /// [Testing and Debugging](xref:microsoft.quantum.user-guide-qdk.overview.testingdebugging) 12 | /// articles. 13 | namespace Microsoft.Quantum.Diagnostics {} 14 | -------------------------------------------------------------------------------- /Standard/src/Emulation/cgmanifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/component-detection-manifest.json", 3 | "Registrations": [ 4 | { 5 | "Component": { 6 | "Type": "other", 7 | "Other": { 8 | "Name": "NumPy", 9 | "Version": "4a2b6a7d8e389abe06d5d7f2fbfa6ebd03b9092a", 10 | "DownloadUrl": "https://raw.githubusercontent.com/numpy/numpy/4a2b6a7d8e389abe06d5d7f2fbfa6ebd03b9092a/numpy/random/mtrand/distributions.c" 11 | } 12 | } 13 | } 14 | ], 15 | "Version": 1 16 | } 17 | -------------------------------------------------------------------------------- /Standard/src/ErrorCorrection/Properties/NamespaceInfo.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | /// # Summary 5 | /// This namespace contains functions, operations, and user-defined types for 6 | /// quantum error correction. 7 | /// 8 | /// # Description 9 | /// To learn more about this namespace, see 10 | /// [Error Correction](xref:microsoft.quantum.libraries.overview.error-correction). 11 | namespace Microsoft.Quantum.ErrorCorrection {} 12 | -------------------------------------------------------------------------------- /Standard/src/Logical/Properties/NamespaceInfo.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | /// # Summary 5 | /// Contains functions for working with logical expressions and Boolean logic. 6 | /// 7 | /// # Description 8 | /// A lot of functions in this namespace offer the same functionality as the 9 | /// [logical expressions](xref:microsoft.quantum.qsharp.logicalexpressions) and 10 | /// [comparative expressions](xref:microsoft.quantum.qsharp.comparativeexpressions). 11 | namespace Microsoft.Quantum.Logical { } 12 | -------------------------------------------------------------------------------- /Standard/src/Math/Constants.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Math { 5 | 6 | /// # Summary 7 | /// Returns the natural logarithm of 2. 8 | /// 9 | /// # Output 10 | /// Returns a `Double` equal to $0.6931471805599453$. 11 | function LogOf2 () : Double 12 | { 13 | return 0.6931471805599453; 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /Standard/src/Math/Convert.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Math { 5 | 6 | /// # Summary 7 | /// Converts a complex number of type `ComplexPolar` to a complex 8 | /// number of type `Complex`. 9 | /// 10 | /// # Input 11 | /// ## input 12 | /// Complex number $c = r e^{i t}$. 13 | /// 14 | /// # Output 15 | /// Complex number $c = x + i y$. 16 | function ComplexPolarAsComplex (input : ComplexPolar) : Complex { 17 | return Complex( 18 | input::Magnitude * Cos(input::Argument), 19 | input::Magnitude * Sin(input::Argument) 20 | ); 21 | } 22 | 23 | /// # Summary 24 | /// Converts a complex number of type `Complex` to a complex 25 | /// number of type `ComplexPolar`. 26 | /// 27 | /// # Input 28 | /// ## input 29 | /// Complex number $c = x + i y$. 30 | /// 31 | /// # Output 32 | /// Complex number $c = r e^{i t}$. 33 | function ComplexAsComplexPolar (input : Complex) : ComplexPolar { 34 | return ComplexPolar(AbsComplex(input), ArgComplex(input)); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /Standard/src/Math/DeprecatedRandom.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Math { 5 | open Microsoft.Quantum.Intrinsic; 6 | open Microsoft.Quantum.Canon; 7 | open Microsoft.Quantum.Convert; 8 | open Microsoft.Quantum.Random; 9 | 10 | @Deprecated("Microsoft.Quantum.Random.DrawRandomInt") 11 | operation RandomIntPow2 (maxBits : Int) : Int { 12 | return DrawRandomInt(0, 2^maxBits - 1); 13 | } 14 | 15 | @Deprecated("Microsoft.Quantum.Random.DrawRandomInt") 16 | operation RandomInt (maxInt : Int) : Int { 17 | return DrawRandomInt(0, maxInt - 1); 18 | } 19 | 20 | 21 | @Deprecated("Microsoft.Quantum.Random.DrawRandomDouble") 22 | operation RandomReal (bitsRandom : Int) : Double { 23 | if (bitsRandom < 1) { 24 | fail $"Number of random bits must be greater than 0."; 25 | } 26 | 27 | return IntAsDouble(RandomIntPow2(bitsRandom)) / PowD(2.0, IntAsDouble(bitsRandom)); 28 | } 29 | 30 | @Deprecated("Microsoft.Quantum.Random.DrawRandomPauli") 31 | operation RandomSingleQubitPauli() : Pauli { 32 | return Snd(MaybeChooseElement([PauliI, PauliX, PauliY, PauliZ], DiscreteUniformDistribution(0, 3))); 33 | } 34 | 35 | } 36 | 37 | 38 | -------------------------------------------------------------------------------- /Standard/src/Math/Properties/NamespaceInfo.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | /// # Summary 5 | /// This namespace contains classical mathematical functions and data types. 6 | /// 7 | /// # Description 8 | /// A lot of functions in this namespace offer the same functionality as the 9 | /// [arithmetic expressions](xref:microsoft.quantum.qsharp.arithmeticexpressions). 10 | namespace Microsoft.Quantum.Math {} 11 | -------------------------------------------------------------------------------- /Standard/src/Math/Random.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Random { 5 | open Microsoft.Quantum.Arrays; 6 | open Microsoft.Quantum.Synthesis; 7 | open Microsoft.Quantum.Intrinsic; 8 | open Microsoft.Quantum.Canon; 9 | 10 | /// # Summary 11 | /// Returns a single-qubit Clifford operator chosen uniformly at random 12 | /// from the single-qubit Clifford group. 13 | /// 14 | /// # Output 15 | /// A single-qubit Clifford operator, drawn at random from the 192 elements 16 | /// of the single-qubit Clifford group. 17 | operation DrawRandomSingleQubitClifford() : SingleQubitClifford { 18 | return Identity1C() 19 | w/ E <- DrawRandomInt(0, 2) 20 | w/ S <- DrawRandomInt(0, 3) 21 | w/ X <- DrawRandomInt(0, 1) 22 | w/ Omega <- DrawRandomInt(0, 7); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Standard/src/Math/Types.qs: -------------------------------------------------------------------------------- 1 | namespace Microsoft.Quantum.Math { 2 | 3 | /// # Summary 4 | /// Represents a rational number of the form `p/q`. Integer `p` is 5 | /// the first element of the tuple and `q` is the second element 6 | /// of the tuple. 7 | /// 8 | /// # Named Items 9 | /// ## Numerator 10 | /// Numerator of the fraction. 11 | /// ## Denominator 12 | /// Denominator of the fraction/ 13 | newtype Fraction = ( 14 | Numerator: Int, 15 | Denominator: Int 16 | ); 17 | 18 | /// # Summary 19 | /// Represents a rational number of the form `p/q`. Integer `p` is 20 | /// the first element of the tuple and `q` is the second element 21 | /// of the tuple. 22 | /// 23 | /// # Named Items 24 | /// ## Numerator 25 | /// Numerator of the fraction. 26 | /// ## Denominator 27 | /// Denominator of the fraction/ 28 | newtype BigFraction = ( 29 | Numerator: BigInt, 30 | Denominator: BigInt 31 | ); 32 | 33 | } 34 | -------------------------------------------------------------------------------- /Standard/src/Measurement/Properties/NamespaceInfo.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | /// # Summary 5 | /// This namespace contains operations for performing measurements beyond 6 | /// the basic measurement operations available in the 7 | /// [`Microsoft.Quantum.Intrinsic` namespace](xref:Microsoft.Quantum.Intrinsic). 8 | /// 9 | /// # Description 10 | /// To learn more about the different types of measurements, see the 11 | /// [Single- and multi-qubit Pauli measurement operations](xref:microsoft.quantum.concepts.pauli) 12 | /// article. 13 | namespace Microsoft.Quantum.Measurement {} 14 | -------------------------------------------------------------------------------- /Standard/src/Optimization/Properties/NamespaceInfo.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | /// # Summary 5 | /// Contains functions and optimizations for finding minima. 6 | namespace Microsoft.Quantum.Optimization { } 7 | -------------------------------------------------------------------------------- /Standard/src/Oracles/Properties/NamespaceInfo.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | /// # Summary 5 | /// This namespace provides user-defined types to decorate various kinds of 6 | /// oracles by their intended use in quantum algorithms such as phase estimation 7 | /// and amplitude amplification. 8 | namespace Microsoft.Quantum.Oracles {} 9 | -------------------------------------------------------------------------------- /Standard/src/Preparation/Properties/NamespaceInfo.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | /// # Summary 5 | /// This namespace contains functions and operations for preparing qubits into 6 | /// arbitrary initial states. 7 | namespace Microsoft.Quantum.Preparation {} 8 | -------------------------------------------------------------------------------- /Standard/src/Preparation/Types.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Preparation { 5 | open Microsoft.Quantum.Arithmetic; 6 | 7 | /// # Summary 8 | /// Represents a particular mixed state that can be prepared on an index 9 | /// and a garbage register. 10 | /// 11 | /// # Input 12 | /// ## Requirements 13 | /// Specifies the size of the qubit registers required to prepare the 14 | /// mixed state represented by this UDT value. 15 | /// ## Norm 16 | /// Specifies the 1-norm of the coefficients used to define this mixed 17 | /// state. 18 | /// ## Prepare 19 | /// An operation that, given an index register, a data register, and a 20 | /// garbage register initially in the $\ket{0}$, $\let{00\dots 0}$, and 21 | /// $\ket{00\dots 0}$ states (respectively), 22 | /// prepares the state represented by this UDT value on those registers. 23 | /// 24 | /// # See Also 25 | /// - Microsoft.Quantum.PurifiedMixedState 26 | newtype MixedStatePreparation = ( 27 | Requirements: MixedStatePreparationRequirements, 28 | Norm: Double, 29 | Prepare: ((LittleEndian, Qubit[], Qubit[]) => Unit is Adj + Ctl) 30 | ); 31 | 32 | /// # Summary 33 | /// Represents the number of qubits required in order to prepare a given 34 | /// mixed state. 35 | /// 36 | /// # Input 37 | /// ## NTotalQubits 38 | /// The total number of qubits required by the represented state preparation 39 | /// operation. 40 | /// ## NIndexQubits 41 | /// The number of qubits required for the index register used by the 42 | /// represented state preparation operation. 43 | /// ## NGarbageQubits 44 | /// The number of qubits required for the garbage register used by the 45 | /// represented state preparation operation. 46 | /// 47 | /// # See Also 48 | /// - Microsoft.Quantum.PurifiedMixedState 49 | newtype MixedStatePreparationRequirements = ( 50 | NTotalQubits: Int, 51 | ( 52 | NIndexQubits: Int, 53 | NGarbageQubits: Int 54 | ) 55 | ); 56 | 57 | } 58 | -------------------------------------------------------------------------------- /Standard/src/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.CompilerServices; 2 | 3 | [assembly: InternalsVisibleTo("Microsoft.Quantum.Standard.Tests" + SigningConstants.PUBLIC_KEY)] 4 | -------------------------------------------------------------------------------- /Standard/src/Simulation/Properties/NamespaceInfo.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | /// # Summary 5 | /// This namespace contains functions and operations for coherently simulating 6 | /// the dynamics of quantum systems. 7 | namespace Microsoft.Quantum.Simulation {} 8 | -------------------------------------------------------------------------------- /Standard/src/Synthesis/Properties/NamespaceInfo.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | /// # Summary 5 | /// This namespace contains functions and operations for 6 | /// synthesizing quantum operations based on permutations 7 | /// and Boolean functions. 8 | namespace Microsoft.Quantum.Synthesis {} 9 | -------------------------------------------------------------------------------- /Standard/src/Synthesis/SingleQubitCliffordGroup/Diagnostics.qs: -------------------------------------------------------------------------------- 1 | namespace Microsoft.Quantum.Synthesis { 2 | open Microsoft.Quantum.Diagnostics; 3 | open Microsoft.Quantum.Intrinsic; 4 | open Microsoft.Quantum.Canon; 5 | 6 | /// # Summary 7 | /// Requires that a single-qubit Clifford operator is equal to the identity. 8 | /// 9 | /// # Input 10 | /// ## actual 11 | /// The value to be checked. 12 | /// ## message 13 | /// Failure message string to be used when `actual` is not equal to the identity. 14 | function IdentityFact1C(actual : SingleQubitClifford, message : String) : Unit { 15 | EqualityFact1C(actual, Identity1C(), message); 16 | } 17 | 18 | /// # Summary 19 | /// Requires that a single-qubit Clifford operator has the expected value. 20 | /// 21 | /// # Input 22 | /// ## actual 23 | /// The value to be checked. 24 | /// ## expected 25 | /// The expected value. 26 | /// ## message 27 | /// Failure message string to be used when `actual` is not equal to `expected`. 28 | function EqualityFact1C(actual : SingleQubitClifford, expected : SingleQubitClifford, message : String) 29 | : Unit { 30 | if actual::E != expected::E or actual::S != expected::S or actual::X != expected::X or actual::Omega != expected::Omega { 31 | FormattedFailure(actual, expected, message); 32 | } 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /Standard/src/app.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /Standard/tests/ApplyMultiControlledTests.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Tests { 5 | open Microsoft.Quantum.Canon; 6 | open Microsoft.Quantum.Intrinsic; 7 | open Microsoft.Quantum.Diagnostics; 8 | 9 | 10 | /// # Summary 11 | /// Tests multiply controlled not implementation that uses 12 | /// ApplyMultiControlledCA against multiply controlled version of 13 | /// the Microsoft.Quantum.Intrinsic.X 14 | @Test("QuantumSimulator") 15 | operation CheckApplyMultiControlled() : Unit { 16 | 17 | let twoQubitOp = CNOT; 18 | 19 | // this gives us operation ( controls : Qubit[], targets : Qubit[] ) => () 20 | // where we expect targets to have length 2 21 | let multiControlledCNOT = Controlled (ApplyToFirstTwoQubitsCA(twoQubitOp, _)); 22 | 23 | // this gives up operation ( qubits : Qubit[] ) => () 24 | // where first qubit in qubits is control and the rest are target for 25 | // twoQubitOp 26 | let singlyControlledCNOT = ApplyToPartitionCA(multiControlledCNOT, 1, _); 27 | 28 | // Construct multiply controlled op using its singly controlled version 29 | // with the help of ApplyMultiControlledCA 30 | let canonMultiNot = ApplyMultiControlledCA(singlyControlledCNOT, CCNOTop(CCNOT), _, _); 31 | 32 | for numberOfcontrols in 1 .. 5 { 33 | Message($"Checking the equality with {numberOfcontrols} controls"); 34 | 35 | // construct actual and expected with desired number of controls 36 | let actual = ApplyToPartitionCA(canonMultiNot, numberOfcontrols, _); 37 | let expected = ApplyToPartitionCA(multiControlledCNOT, numberOfcontrols, _); 38 | 39 | // check equality 40 | AssertOperationsEqualReferenced(numberOfcontrols + 2, actual, expected); 41 | } 42 | } 43 | 44 | } 45 | 46 | 47 | -------------------------------------------------------------------------------- /Standard/tests/Arithmetic/ReflectionTests.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Tests { 5 | open Microsoft.Quantum.Intrinsic; 6 | open Microsoft.Quantum.Arithmetic; 7 | open Microsoft.Quantum.Diagnostics; 8 | 9 | operation ManuallyReflectAboutFive(register : Qubit[]) : Unit is Adj + Ctl { 10 | within { 11 | X(register[1]); 12 | } apply { 13 | Controlled Z(register[0..1], register[2]); 14 | } 15 | } 16 | 17 | operation ReflectAboutFiveUsingLibrary(register : Qubit[]) : Unit is Adj + Ctl { 18 | let littleEndian = LittleEndian(register); 19 | ReflectAboutInteger(5, littleEndian); 20 | } 21 | 22 | @Test("QuantumSimulator") 23 | operation CheckReflectAboutInteger() : Unit { 24 | AssertOperationsEqualReferenced(3, 25 | ReflectAboutFiveUsingLibrary, 26 | ManuallyReflectAboutFive 27 | ); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /Standard/tests/Arrays/DrawManyTests.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Arrays { 5 | open Microsoft.Quantum.Diagnostics; 6 | open Microsoft.Quantum.Math; 7 | open Microsoft.Quantum.Random; 8 | 9 | @Test("QuantumSimulator") 10 | operation CheckDrawMany() : Unit { 11 | let samples = DrawMany(DrawRandomInt, 20, (0, 29)); 12 | EqualityFactI(20, Length(samples), "Wrong number of samples returned."); 13 | 14 | for sample in samples { 15 | Fact(0 <= sample and sample < 30, "Sample returned by DrawMany was out of range."); 16 | } 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /Standard/tests/Arrays/MapTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | 5 | using Microsoft.Quantum.Simulation.Core; 6 | using Microsoft.Quantum.Simulation.Simulators; 7 | using Microsoft.Quantum.Simulation.XUnit; 8 | using System; 9 | using System.Collections.Generic; 10 | using System.Diagnostics; 11 | using System.Security.Cryptography; 12 | using System.Text; 13 | using Xunit; 14 | 15 | namespace Microsoft.Quantum.Tests 16 | { 17 | public class ForEachRuntimeMetadataTests 18 | { 19 | [Fact] 20 | public void ForEach() 21 | { 22 | var op = new Microsoft.Quantum.Arrays.ForEach(new QuantumSimulator()); 23 | var baseOp = new Microsoft.Quantum.Intrinsic.M(new QuantumSimulator()); 24 | IQArray targets = new QArray(new Qubit[] { }); 25 | var args = op.__DataIn__((baseOp, targets)); 26 | var expected = new RuntimeMetadata() 27 | { 28 | Label = "ForEach", 29 | FormattedNonQubitArgs = "(M)", 30 | IsComposite = true, 31 | Targets = new List() { }, 32 | }; 33 | Assert.Equal(expected, op.GetRuntimeMetadata(args)); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Standard/tests/Arrays/UniqueTests.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Arrays { 5 | open Microsoft.Quantum.Diagnostics; 6 | open Microsoft.Quantum.Logical; 7 | 8 | @Test("QuantumSimulator") 9 | operation UniqueInts() : Unit { 10 | 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"); 11 | AllEqualityFactI(Unique(EqualI, [0, 1, 1, 0, 0, 1, 1, 0]), [0, 1, 0, 1, 0], "Data is not unique"); 12 | AllEqualityFactI(Unique(EqualI, Sorted(LessThanOrEqualI, [2, 2, 1, 1, 2, 2, 1, 1])), [1, 2], "Sorted data is not unique"); 13 | } 14 | 15 | @Test("QuantumSimulator") 16 | operation UniqueDoubles() : Unit { 17 | let unique = Unique(EqualD, [1.1, 1.1, 2.2, 2.2, 2.2, 3.3, 0.5, 42.0]); 18 | EqualityFactI(Length(unique), 5, "Unexpected length of unique data"); 19 | Fact(unique[0] == 1.1, "Unexpected element in unique data"); 20 | Fact(unique[1] == 2.2, "Unexpected element in unique data"); 21 | Fact(unique[2] == 3.3, "Unexpected element in unique data"); 22 | Fact(unique[3] == 0.5, "Unexpected element in unique data"); 23 | Fact(unique[4] == 42.0, "Unexpected element in unique data"); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Standard/tests/BitwiseTests.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Tests { 5 | open Microsoft.Quantum.Bitwise; 6 | open Microsoft.Quantum.Diagnostics; 7 | 8 | @Test("QuantumSimulator") 9 | function ShiftIsCorrect() : Unit { 10 | let smallValue = 5; // 0b101 11 | EqualityFactI(20, LeftShiftedI(smallValue, 2), "Shifted values incorrect."); 12 | EqualityFactI(2, RightShiftedI(smallValue, 1), "Shifted values incorrect."); 13 | 14 | // 0b‭1111111011011100101110101001100001110110010101000011001000010000‬ 15 | let bigValue = 0xfedcba9876543210L; 16 | EqualityFactL( 17 | 0x1fdb97530eca864200L, 18 | LeftShiftedL(bigValue, 5), 19 | "LeftShfitedL returned wrong output." 20 | ); 21 | EqualityFactL( 22 | 0x1fdb97530eca8642L, 23 | RightShiftedL(bigValue, 3), 24 | "RightShiftedL returned wrong output." 25 | ); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /Standard/tests/Canon/Combinators/SinglyControlled.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Tests { 5 | open Microsoft.Quantum.Arithmetic; 6 | open Microsoft.Quantum.Canon; 7 | open Microsoft.Quantum.Diagnostics; 8 | open Microsoft.Quantum.Intrinsic; 9 | 10 | @Test("ToffoliSimulator") 11 | operation TestSinglyControlledWithSimulation() : Unit { 12 | use ctl = Qubit(); 13 | use target = Qubit[3]; 14 | let targetLE = LittleEndian(target); 15 | let value = 5; 16 | 17 | for singlyControlled in [SinglyControlled, SinglyControlledA] { 18 | for enableControl in [false, true] { 19 | within { 20 | ApplyIfA(enableControl, X, ctl); 21 | } apply { 22 | singlyControlled(ApplyXorInPlace(value, _))(ctl, targetLE); 23 | EqualityFactI(MeasureInteger(targetLE), enableControl ? value | 0, "Unexpected measurement result for SinglyControlled"); 24 | } 25 | } 26 | } 27 | } 28 | 29 | @Test("QuantumSimulator") 30 | operation TestSinglyControlledWithEquivalenceCheck() : Unit { 31 | AssertOperationsEqualReferenced(2, 32 | qs => SinglyControlled(H)(qs[0], qs[1]), 33 | qs => Controlled H([qs[0]], qs[1]) 34 | ); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Standard/tests/Canon/RepeatTests.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Canon { 5 | open Microsoft.Quantum.Diagnostics; 6 | open Microsoft.Quantum.Intrinsic; 7 | 8 | @Test("QuantumSimulator") 9 | operation CheckRepeatHIsNoOp() : Unit { 10 | AssertOperationsEqualReferenced(1, 11 | ApplyToEach(Repeat(H, 2, _), _), 12 | NoOp 13 | ); 14 | 15 | AssertOperationsEqualReferenced(1, 16 | ApplyToEachC(RepeatC(H, 2, _), _), 17 | NoOp 18 | ); 19 | 20 | AssertOperationsEqualReferenced(1, 21 | ApplyToEachA(RepeatA(H, 2, _), _), 22 | NoOp 23 | ); 24 | 25 | AssertOperationsEqualReferenced(1, 26 | ApplyToEachCA(RepeatCA(H, 2, _), _), 27 | NoOp 28 | ); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /Standard/tests/Canon/Utils/ControlledOnBitStringTests.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Tests { 5 | open Microsoft.Quantum.Canon; 6 | open Microsoft.Quantum.Intrinsic; 7 | open Microsoft.Quantum.Diagnostics; 8 | open Microsoft.Quantum.Arrays; 9 | 10 | /// # Summary 11 | /// Applies an Ry rotation controlled on 12 | /// the state $\ket{001}$, leaving additional 13 | /// control qubits uncontrolled. 14 | /// 15 | /// # Input 16 | /// ## register 17 | /// A register of at least four qubits, the last of which is considered to 18 | /// be the target. 19 | internal operation ApplyRyControlledOn001(register : Qubit[]) 20 | : Unit is Adj + Ctl { 21 | let controls = Most(register); 22 | let target = Tail(register); 23 | 24 | within { 25 | X(controls[0]); 26 | X(controls[1]); 27 | } apply { 28 | Controlled Ry(controls[...2], (-1.234, target)); 29 | } 30 | } 31 | 32 | internal operation ApplyControlledOnBitStringToFlatRegister( 33 | op : ((Qubit[], Qubit) => Unit is Adj + Ctl), 34 | register : Qubit[] 35 | ) : Unit is Adj + Ctl { 36 | op(Most(register), Tail(register)); 37 | } 38 | 39 | @Test("QuantumSimulator") 40 | operation CheckControlledOnBitString() : Unit { 41 | let controlledOp = ControlledOnBitString( 42 | [false, false, true], 43 | Ry(-1.234, _) 44 | ); 45 | AssertOperationsEqualReferenced(4, 46 | ApplyRyControlledOn001, 47 | ApplyControlledOnBitStringToFlatRegister(controlledOp, _) 48 | ); 49 | 50 | // Check that extra qubits are uncontrolled. 51 | AssertOperationsEqualReferenced(5, 52 | ApplyRyControlledOn001, 53 | ApplyControlledOnBitStringToFlatRegister(controlledOp, _) 54 | ); 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /Standard/tests/Characterization/DistinguishabilityTests.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Tests { 5 | open Microsoft.Quantum.Math; 6 | open Microsoft.Quantum.Canon; 7 | open Microsoft.Quantum.Intrinsic; 8 | open Microsoft.Quantum.Characterization; 9 | open Microsoft.Quantum.Diagnostics; 10 | 11 | @Test("QuantumSimulator") 12 | operation CheckOverlapBetweenPlusAndOne() : Unit { 13 | let prep1 = ApplyToEachCA(H, _); 14 | let prep2 = ApplyToEachCA(X, _); 15 | 16 | EqualityWithinToleranceFact( 17 | EstimateRealOverlapBetweenStates( 18 | NoOp, prep1, prep2, 1, 1000000 19 | ), 20 | 1.0 / Sqrt(2.0), 21 | 0.02 22 | ); 23 | EqualityWithinToleranceFact( 24 | EstimateImagOverlapBetweenStates( 25 | NoOp, prep1, prep2, 1, 1000000 26 | ), 27 | 0.0, 28 | 0.02 29 | ); 30 | EqualityWithinToleranceFact( 31 | 0.5, 32 | EstimateOverlapBetweenStates( 33 | prep1, prep2, 1, 1000000 34 | ), 35 | 0.02 36 | ); 37 | } 38 | 39 | @Test("QuantumSimulator") 40 | operation CheckOverlapWithCommonPreparation() : Unit { 41 | let common = ApplyToEachCA(H, _); 42 | let prep1 = ApplyToEachCA(S, _); 43 | let prep2 = ApplyToEachCA(Z, _); 44 | 45 | EqualityWithinToleranceFact( 46 | EstimateRealOverlapBetweenStates( 47 | common, prep1, prep2, 1, 1000000 48 | ), 49 | 0.5, 50 | 0.02 51 | ); 52 | EqualityWithinToleranceFact( 53 | EstimateImagOverlapBetweenStates( 54 | common, prep1, prep2, 1, 1000000 55 | ), 56 | 0.5, 57 | 0.02 58 | ); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Standard/tests/ConversionTests.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Tests { 5 | open Microsoft.Quantum.Diagnostics; 6 | open Microsoft.Quantum.Canon; 7 | open Microsoft.Quantum.Convert; 8 | 9 | @Test("QuantumSimulator") 10 | function ResultArrayAsIntIsCorrect() : Unit { 11 | EqualityFactI(ResultArrayAsInt([Zero, Zero]), 0, $"Expected [Zero, Zero] to be represented by 0."); 12 | EqualityFactI(ResultArrayAsInt([One, Zero]), 1, $"Expected [One, Zero] to be represented by 1."); 13 | EqualityFactI(ResultArrayAsInt([Zero, One]), 2, $"Expected [Zero, One] to be represented by 2."); 14 | EqualityFactI(ResultArrayAsInt([One, One]), 3, $"Expected [One, One] to be represented by 3."); 15 | } 16 | 17 | @Test("QuantumSimulator") 18 | function BoolArrFromPositiveIntIsCorrect() : Unit { 19 | for number in 0 .. 100 { 20 | let bits = IntAsBoolArray(number, 9); 21 | let inte = BoolArrayAsInt(bits); 22 | EqualityFactI(inte, number, $"Integer converted to bit string and back should be identical"); 23 | } 24 | 25 | let bits70 = [false, true, true, false, false, false, true, false]; 26 | let number70 = BoolArrayAsInt(bits70); 27 | EqualityFactI(70, number70, $"Integer from 01000110 in little Endian should be 70"); 28 | } 29 | 30 | @Test("QuantumSimulator") 31 | function IntAsBoolArrayIsCorrectForLargeInputs() : Unit { 32 | // Checks for regression of https://github.com/microsoft/QuantumLibraries/issues/503. 33 | let bits = IntAsBoolArray(1, 63); 34 | EqualityFactI(Length(bits), 63, $"IntAsBoolArray(1, 63) returned an array of the wrong length."); 35 | EqualityFactI(BoolArrayAsInt(bits), 1, $"IntAsBoolArray(1, 63) returned an array that did not represent 1: {bits}."); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /Standard/tests/Diagnostics/DumpTests.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Tests { 5 | open Microsoft.Quantum.Intrinsic; 6 | open Microsoft.Quantum.Canon; 7 | open Microsoft.Quantum.Diagnostics as Diag; 8 | 9 | operation DumpS() : Unit { 10 | Diag.DumpOperation(1, ApplyToEachCA(S, _)); 11 | } 12 | 13 | operation DumpCnot() : Unit is Adj + Ctl { 14 | Diag.DumpOperation(2, ApplyToFirstTwoQubitsCA(CNOT, _)); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /Standard/tests/Logical/BooleanTests.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Tests { 5 | open Microsoft.Quantum.Logical; 6 | open Microsoft.Quantum.Diagnostics; 7 | 8 | @Test("QuantumSimulator") 9 | function NotIsCorrect() : Unit { 10 | Fact(Not(false), "Not returned wrong output."); 11 | } 12 | 13 | @Test("QuantumSimulator") 14 | function AndIsCorrect() : Unit { 15 | Fact(not And(false, false), "And returned wrong output."); 16 | Fact(not And(false, true), "And returned wrong output."); 17 | Fact(not And(true, false), "And returned wrong output."); 18 | Fact(And(true, true), "And returned wrong output."); 19 | } 20 | 21 | @Test("QuantumSimulator") 22 | function OrIsCorrect() : Unit { 23 | Fact(not Or(false, false), "Or returned wrong output."); 24 | Fact(Or(false, true), "Or returned wrong output."); 25 | Fact(Or(true, false), "Or returned wrong output."); 26 | Fact(Or(true, true), "Or returned wrong output."); 27 | } 28 | 29 | @Test("QuantumSimulator") 30 | function XorIsCorrect() : Unit { 31 | Fact(not Xor(false, false), "Xor returned wrong output."); 32 | Fact(Xor(false, true), "Xor returned wrong output."); 33 | Fact(Xor(true, false), "Xor returned wrong output."); 34 | Fact(not Xor(true, true), "Xor returned wrong output."); 35 | } 36 | 37 | @Test("QuantumSimulator") 38 | function ConditionedIsCorrect() : Unit { 39 | EqualityFactI(Conditioned(true, 42, -1), 42, "Conditioned returned wrong output."); 40 | EqualityFactL(Conditioned(false, 42L, -1L), -1L, "Conditioned returned wrong output."); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /Standard/tests/Logical/ComparisonTests.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Tests { 5 | open Microsoft.Quantum.Logical; 6 | open Microsoft.Quantum.Diagnostics; 7 | open Microsoft.Quantum.Math; 8 | open Microsoft.Quantum.Arrays; 9 | 10 | @Test("QuantumSimulator") 11 | function LexographicComparisonIsCorrect() : Unit { 12 | let lexographicComparison = LexographicComparison(LessThanOrEqualD); 13 | Fact( 14 | lexographicComparison( 15 | [1.1, 2.2], [1.1, 2.2, 3.3] 16 | ), 17 | "Shorter array should have occurred first." 18 | ); 19 | Fact( 20 | lexographicComparison( 21 | [0.7, 2.2], [1.1, 2.2] 22 | ), 23 | "Array with smaller first element should have occurred first." 24 | ); 25 | Fact( 26 | lexographicComparison( 27 | [1.1, 2.2], [1.1, 2.2] 28 | ), 29 | "Identical arrays should be marked as less than or equal." 30 | ); 31 | Contradiction( 32 | lexographicComparison( 33 | [1.1, 2.7], [1.1, 2.2, 3.3] 34 | ), 35 | "Array with larger second element should have occurred second." 36 | ); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /Standard/tests/Math/BinomialTests.cs: -------------------------------------------------------------------------------- 1 | using Xunit; 2 | 3 | namespace Microsoft.Quantum.Standard.Emulation 4 | { 5 | public class BinomialTests 6 | { 7 | [Fact] 8 | public void TestExtrema() 9 | { 10 | var dist = new BinomialDistribution(100, 0.0); 11 | Assert.Equal(0, dist.NextSample()); 12 | dist = new BinomialDistribution(100, 1.0); 13 | Assert.Equal(100, dist.NextSample()); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Standard/tests/Measurement/ResetTests.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Tests { 5 | open Microsoft.Quantum.Measurement; 6 | open Microsoft.Quantum.Intrinsic; 7 | open Microsoft.Quantum.Diagnostics; 8 | 9 | operation CheckSetToBasisStateHelper(desired : Result) : Unit { 10 | use q = Qubit(); 11 | Ry(0.1234, q); 12 | SetToBasisState(desired, q); 13 | AssertQubit(desired, q); 14 | Reset(q); 15 | } 16 | 17 | @Test("QuantumSimulator") 18 | operation CheckSetToBasisState() : Unit { 19 | for desired in [Zero, One] { 20 | CheckSetToBasisStateHelper(desired); 21 | } 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /Standard/tests/Optimization/UnivariateTests.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Tests { 5 | open Microsoft.Quantum.Optimization; 6 | open Microsoft.Quantum.Math; 7 | open Microsoft.Quantum.Diagnostics; 8 | 9 | function ParabolaCase(minima : Double, x : Double) : Double { 10 | return PowD((x - minima), 2.0); 11 | } 12 | 13 | function AbsDistance(x : Double, y : Double) : Double { 14 | return AbsD(x - y); 15 | } 16 | 17 | @Test("QuantumSimulator") 18 | function MinimizedParabolaIsCorrect() : Unit { 19 | let optimum = LocalUnivariateMinimum(ParabolaCase(3.14, _), (-7.0, +12.0), 1e-10); 20 | NearEqualityFactD(optimum::Coordinate, 3.14); 21 | NearEqualityFactD(optimum::Value, 0.0); 22 | EqualityFactI(optimum::NQueries, 56, "LocalUnivariateMinimum made an unexpected amount of queries."); 23 | } 24 | 25 | @Test("QuantumSimulator") 26 | function MinimumConvergesToEdge() : Unit { 27 | let optimum = LocalUnivariateMinimum(AbsDistance(-1.0, _), (-1.0, 1.0), 1e-2); 28 | EqualityWithinToleranceFact(optimum::Coordinate, -1.0, 1e-2); 29 | EqualityFactI(optimum::NQueries, 14, "LocalUnivariateMinimum made an unexpected amount of queries."); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Standard/tests/PairTests.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | namespace Microsoft.Quantum.Tests { 4 | 5 | open Microsoft.Quantum.Canon; 6 | open Microsoft.Quantum.Diagnostics; 7 | 8 | @Test("QuantumSimulator") 9 | function PairIsCorrect() : Unit { 10 | 11 | let pair = (12, PauliZ); 12 | 13 | if (Fst(pair) != 12) { 14 | let actual = Fst(pair); 15 | fail $"Expected 12, actual {actual}."; 16 | } 17 | 18 | if (Snd(pair) != PauliZ) { 19 | let actual = Snd(pair); 20 | fail $"Expected PauliZ, actual {actual}."; 21 | } 22 | } 23 | 24 | } 25 | 26 | 27 | -------------------------------------------------------------------------------- /Standard/tests/PauliTests.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | namespace Microsoft.Quantum.Tests { 4 | open Microsoft.Quantum.Preparation; 5 | open Microsoft.Quantum.Intrinsic; 6 | open Microsoft.Quantum.Canon; 7 | open Microsoft.Quantum.Measurement; 8 | open Microsoft.Quantum.Diagnostics; 9 | 10 | @Test("QuantumSimulator") 11 | operation TestMeasureWithScratch() : Unit { 12 | use register = Qubit[2]; 13 | PrepareEntangledState([register[0]], [register[1]]); 14 | X(register[1]); 15 | let xxScratch = MeasureWithScratch([PauliX, PauliX], register); 16 | let xx = Measure([PauliX, PauliX], register); 17 | 18 | if xx != xxScratch { 19 | fail $"〈XX〉: MeasureWithScratch and Measure disagree"; 20 | } 21 | 22 | let yyScratch = MeasureWithScratch([PauliY, PauliY], register); 23 | let yy = Measure([PauliY, PauliY], register); 24 | 25 | if yy != yyScratch { 26 | fail $"〈yy〉: MeasureWithScratch and Measure disagree"; 27 | } 28 | 29 | let zzScratch = MeasureWithScratch([PauliZ, PauliZ], register); 30 | let zz = Measure([PauliZ, PauliZ], register); 31 | 32 | if zz != zzScratch { 33 | fail $"〈ZZ〉: MeasureWithScratch and Measure disagree"; 34 | } 35 | 36 | ResetAll(register); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /Standard/tests/QcvvTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using System; 5 | 6 | using Microsoft.Quantum.Simulation.Common; 7 | using Microsoft.Quantum.Simulation.Simulators; 8 | using Xunit; 9 | using Assert = Xunit.Assert; 10 | 11 | namespace Microsoft.Quantum.Tests 12 | { 13 | public class EstimateFrequency 14 | { 15 | [Fact] 16 | public void EstimateFrequencyWithAndWithoutEmulation() 17 | { 18 | void TestOne(SimulatorBase sim, int expected) 19 | { 20 | var count = 0; 21 | sim.OnLog += (_) => count++; 22 | sim.DisableLogToConsole(); 23 | 24 | EstimateFrequencyEmulationTest.Run(sim).Wait(); 25 | Assert.Equal(expected, count); 26 | 27 | if (sim is IDisposable dis) dis.Dispose(); 28 | } 29 | 30 | TestOne(new QuantumSimulator(), 1); 31 | TestOne(new ToffoliSimulator(), 2000); 32 | } 33 | 34 | [Fact] 35 | public void TestEstimateFrequencyBinomial() 36 | { 37 | using var sim = new QuantumSimulator(randomNumberGeneratorSeed: 655321); 38 | TestEstimateFrequencyBinomialInner.Run(sim).Wait(); 39 | } 40 | 41 | [Fact] 42 | public void TestRobustPhaseEstimation() 43 | { 44 | using var sim = new QuantumSimulator(randomNumberGeneratorSeed: 655321); 45 | TestRobustPhaseEstimationInner.Run(sim).Wait(); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Standard/tests/QuantumPhaseEstimationTests.qs: -------------------------------------------------------------------------------- 1 | namespace Microsoft.Quantum.Tests { 2 | open Microsoft.Quantum.Intrinsic; 3 | open Microsoft.Quantum.Canon; 4 | open Microsoft.Quantum.Arithmetic; 5 | open Microsoft.Quantum.Convert; 6 | open Microsoft.Quantum.Oracles; 7 | open Microsoft.Quantum.Characterization; 8 | open Microsoft.Quantum.Arrays; 9 | open Microsoft.Quantum.Math; 10 | open Microsoft.Quantum.Diagnostics; 11 | 12 | 13 | /// # Summary 14 | /// Assert that the QuantumPhaseEstimation operation for the T gate 15 | /// return 0000 in the controlRegister when targetState is 0 and 16 | /// return 0010 when the targetState is 1 17 | @Test("QuantumSimulator") 18 | operation TestQuantumPhaseEstimation() : Unit { 19 | 20 | let oracle = DiscreteOracle(ApplyTOracle); 21 | 22 | use qPhase = Qubit[5]; 23 | let phase = BigEndian(qPhase[0 .. 3]); 24 | let state = qPhase[4]; 25 | QuantumPhaseEstimation(oracle, [state], phase); 26 | let complexOne = Complex(1.0, 0.0); 27 | let complexZero = Complex(0.0, 0.0); 28 | 29 | for idxPhase in 0 .. 4 { 30 | AssertQubitIsInStateWithinTolerance((complexOne, complexZero), qPhase[idxPhase], 1E-06); 31 | } 32 | 33 | X(state); 34 | QuantumPhaseEstimation(oracle, [state], phase); 35 | AssertQubitIsInStateWithinTolerance((complexOne, complexZero), qPhase[0], 1E-06); 36 | AssertQubitIsInStateWithinTolerance((complexOne, complexZero), qPhase[1], 1E-06); 37 | AssertQubitIsInStateWithinTolerance((complexZero, complexOne), qPhase[2], 1E-06); 38 | AssertQubitIsInStateWithinTolerance((complexOne, complexZero), qPhase[3], 1E-06); 39 | AssertQubitIsInStateWithinTolerance((complexZero, complexOne), qPhase[4], 1E-06); 40 | ResetAll(qPhase); 41 | } 42 | 43 | 44 | /// # Summary 45 | /// Implementation of T-gate for Quantum Phase Estimation Oracle 46 | internal operation ApplyTOracle (power : Int, target : Qubit[]) : Unit is Adj + Ctl { 47 | for idxPower in 0 .. power - 1 { 48 | T(Head(target)); 49 | } 50 | } 51 | 52 | } 53 | 54 | -------------------------------------------------------------------------------- /Standard/tests/Standard.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | net6.0 7 | Microsoft.Quantum.Standard.Tests 8 | false 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /Standard/tests/TypeConversionTests.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT License. 3 | namespace Microsoft.Quantum.Tests { 4 | open Microsoft.Quantum.Intrinsic; 5 | open Microsoft.Quantum.Canon; 6 | open Microsoft.Quantum.Convert; 7 | open Microsoft.Quantum.Diagnostics; 8 | 9 | function Square(x : Int) : Int { 10 | return x * x; 11 | } 12 | 13 | operation ApplyOp<'T, 'U>(op : ('T => 'U), input : 'T) : 'U { 14 | return op(input); 15 | } 16 | 17 | @Test("ToffoliSimulator") 18 | operation TestCall() : Unit { 19 | EqualityFactI(Call(Square, 4), 16, "Call failed with Square."); 20 | } 21 | 22 | @Test("ToffoliSimulator") 23 | operation TestToOperation() : Unit { 24 | let op = FunctionAsOperation(Square); 25 | EqualityFactI(ApplyOp(op, 3), 9, "ToOperation failed with Square."); 26 | } 27 | 28 | } 29 | 30 | 31 | -------------------------------------------------------------------------------- /Standard/tests/UniformSuperpositionPreparationTests.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | namespace Microsoft.Quantum.Tests { 5 | open Microsoft.Quantum.Arithmetic; 6 | open Microsoft.Quantum.Convert; 7 | open Microsoft.Quantum.Diagnostics; 8 | open Microsoft.Quantum.Intrinsic; 9 | open Microsoft.Quantum.Preparation; 10 | 11 | 12 | @Test("QuantumSimulator") 13 | operation TestPrepareUniformSuperposition() : Unit { 14 | let nQubits = 5; 15 | use qubits = Qubit[nQubits]; 16 | for nIndices in 1..2^nQubits { 17 | Message($"Testing nIndices {nIndices} on {nQubits} qubits"); 18 | PrepareUniformSuperposition(nIndices, LittleEndian(qubits)); 19 | 20 | let prob = 1.0 / IntAsDouble(nIndices); 21 | for stateIndex in 0..2^nQubits - 1 { 22 | AssertProbInt(stateIndex, stateIndex < nIndices ? prob | 0.0, LittleEndian(qubits), 1e-10); 23 | } 24 | 25 | ResetAll(qubits); 26 | } 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /Visualization/Common/DelaySign.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | 3 | // Attributes for delay-signing 4 | #if SIGNED 5 | [assembly:AssemblyKeyFile("..\\..\\Build\\267DevDivSNKey2048.snk")] 6 | [assembly:AssemblyDelaySign(true)] 7 | #endif 8 | 9 | internal static class SigningConstants 10 | { 11 | #if SIGNED 12 | public const string PUBLIC_KEY = ", PublicKey=" + 13 | "002400000c800000140100000602000000240000525341310008000001000100613399aff18ef1" + 14 | "a2c2514a273a42d9042b72321f1757102df9ebada69923e2738406c21e5b801552ab8d200a65a2" + 15 | "35e001ac9adc25f2d811eb09496a4c6a59d4619589c69f5baf0c4179a47311d92555cd006acc8b" + 16 | "5959f2bd6e10e360c34537a1d266da8085856583c85d81da7f3ec01ed9564c58d93d713cd0172c" + 17 | "8e23a10f0239b80c96b07736f5d8b022542a4e74251a5f432824318b3539a5a087f8e53d2f135f" + 18 | "9ca47f3bb2e10aff0af0849504fb7cea3ff192dc8de0edad64c68efde34c56d302ad55fd6e80f3" + 19 | "02d5efcdeae953658d3452561b5f36c542efdbdd9f888538d374cef106acf7d93a4445c3c73cd9" + 20 | "11f0571aaf3d54da12b11ddec375b3"; 21 | #else 22 | public const string PUBLIC_KEY = ""; 23 | #endif 24 | } 25 | -------------------------------------------------------------------------------- /Visualization/src/Extensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #nullable enable 5 | 6 | using System.Text; 7 | using Microsoft.Jupyter.Core; 8 | using Microsoft.Extensions.Logging; 9 | using Newtonsoft.Json; 10 | using NumSharp; 11 | using static NumSharp.Slice; 12 | using Microsoft.Quantum.IQSharp.Jupyter; 13 | using System.Linq; 14 | using System; 15 | using System.Collections.Generic; 16 | 17 | namespace Microsoft.Quantum.Diagnostics.Emulation 18 | { 19 | 20 | internal static class Extensions 21 | { 22 | internal static IEnumerable EnumerateOverAxis(this NumSharp.NDArray array, int axis = 0) 23 | { 24 | var prefix = Enumerable.Repeat(All, axis).ToArray(); 25 | foreach (var idx in Enumerable.Range(0, array.Shape[axis])) 26 | { 27 | Slice[] slice = prefix.Concat(new Slice[] { idx, Ellipsis }).ToArray(); 28 | yield return array[slice]; 29 | } 30 | } 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /Visualization/src/Visualization.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | Microsoft.Quantum.Standard.Visualization 6 | 1591 7 | 8 | 9 | 10 | Microsoft 11 | Provides IQ# visualization support for Microsoft's Q# standard libraries. 12 | © Microsoft Corporation. All rights reserved. 13 | See: https://docs.microsoft.com/azure/quantum/qdk-relnotes/ 14 | MIT 15 | https://github.com/Microsoft/Quantum 16 | qdk-nuget-icon.png 17 | Quantum Q# Qsharp 18 | false 19 | true 20 | true 21 | true 22 | snupkg 23 | $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb;.xml 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /build.yml: -------------------------------------------------------------------------------- 1 | # 2 | # Build configuration file to run build on azure-pipelines 3 | # 4 | name: $(Build.Major).$(Build.Minor).$(DayOfMonth)$(rev:rr) 5 | 6 | trigger: none 7 | 8 | pr: 9 | - main 10 | - feature/* 11 | - features/* 12 | - release/* 13 | 14 | schedules: 15 | - cron: "0 9 * * Sat" 16 | displayName: 'Build for Component Governance' 17 | branches: 18 | include: 19 | - main 20 | always: true 21 | 22 | variables: 23 | Build.Major: 0 24 | Build.Minor: 16 25 | Drops.Dir: $(Build.ArtifactStagingDirectory)/drops 26 | 27 | jobs: 28 | - job: Windows 29 | pool: 30 | vmImage: 'windows-2019' 31 | steps: 32 | - template: Build/steps.yml 33 | - job: macOS 34 | pool: 35 | vmImage: 'macOS-latest' 36 | steps: 37 | - template: Build/steps.yml 38 | - job: Linux 39 | pool: 40 | vmImage: 'ubuntu-latest' 41 | steps: 42 | - template: Build/steps.yml 43 | 44 | 45 | -------------------------------------------------------------------------------- /global.json: -------------------------------------------------------------------------------- 1 | { 2 | "sdk": { 3 | "version": "6.0.100", 4 | "rollForward": "latestMinor" 5 | }, 6 | "msbuild-sdks": { 7 | "Microsoft.Quantum.Sdk": "0.28.302812" 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /sync.cmd: -------------------------------------------------------------------------------- 1 | :: 2 | :: This script pushes the changes on the given branch to 3 | :: the public repository (https://github.com/Microsoft/Quantum.git) 4 | :: 5 | set branch=%1 6 | IF "%branch%" == "" SET branch=main 7 | 8 | git fetch origin 9 | git fetch public || call :addPublic 10 | git push public origin/%branch%:%branch% 11 | GOTO :EOF 12 | 13 | :addPublic 14 | git remote add public https://github.com/Microsoft/Quantum.git 15 | git fetch public 16 | EXIT /B 17 | 18 | :EOF --------------------------------------------------------------------------------