Git Product home page Git Product logo

quantumlibraries's Introduction

DEPRECATION NOTICE

This repository is deprecated.

For the Modern QDK repository, please visit Microsoft/qsharp.

You can also try out the Modern QDK in VS Code for Web at vscode.dev/quantum.

For more information about the Modern QDK and Azure Quantum, visit https://aka.ms/AQ/Documentation.

Classic QDK

This repository contains open-source libraries for the Quantum Development Kit:

New to Quantum?

See the introduction to quantum computing provided with the Quantum Development Kit.

Getting Started

The libraries provided in this repository are built using .NET Core and the Quantum Development Kit. Please see the installation guide for how to get up and running.

You may also visit our Quantum repository, which offers a wide variety of samples on how to use these libraries to write quantum based programs.

Build Status

branch status
main Build Status

Feedback

If you have feedback about the content in this repository, please let us know by filing a new issue! If you have feedback about some other part of the Microsoft Quantum Development Kit, please see the contribution guide for more information.

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com.

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

[Optional] Using Prerelease Versions

If you're interested in helping test the Quantum Development Kit libraries, or if you want to try out new features before they are released, you can add the Quantum Development Kit prerelease feed to your .NET Core SDK configuration. Packages on the prerelease feed are marked with -alpha in their version number, so that projects built using released versions of Quantum Development Kit libraries will not be affected. Note that the prerelease feed is used automatically when building libraries in this repository.

To use the prerelease feed, edit your NuGet.Config file to include the prerelease feed URL (https://pkgs.dev.azure.com/ms-quantum-public/Microsoft Quantum (public)/_packaging/alpha/nuget/v3/index.json) as a package source. The location of this file varies depending on your operating system:

OS NuGet config file location
Windows $Env:APPDATA/Roaming/NuGet/NuGet.Config
macOS / Linux ~/.config/NuGet/NuGet.Config or ~/.nuget/NuGet/NuGet.Config

Note that this file may not already exist, depending on your configuration.

For example, the following NuGet.Config file includes both the main NuGet package feed, and the Quantum Development Kit prerelease feed:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
    <add key="qdk-alpha" value="https://pkgs.dev.azure.com/ms-quantum-public/Microsoft Quantum (public)/_packaging/alpha/nuget/v3/index.json" protocolVersion="3" />
  </packageSources>
</configuration>

quantumlibraries's People

Contributors

akshob avatar anjbur avatar anpaz avatar bamarsha avatar bettinaheim avatar bradben avatar cgranade avatar christopherkang avatar cryptosidh avatar dmitryvasilevsky avatar filipw avatar guanghaolow avatar ihristova11 avatar israelmiles avatar kittyyeungq avatar kuzminrobin avatar langdon-holly avatar martinquantum avatar minestarks avatar msoeken avatar natke avatar nschonni avatar numpde avatar ricardo-espinoza avatar rolfhuisman avatar rufusjwb avatar swernli avatar tcnickolas avatar thomashaener avatar vadym-kl avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

quantumlibraries's Issues

Specific Broombridge serialization/deserialization tasks

Current Broombridge tasks ( see Broombridge directory in gulow/genericladderoperators )

Some specific tasks

  • Reference public static void SerializeBroombridgev0_2(DataStructures.V0_2.Data data, string filename)
    [ ] "It might be good to serialize to a TextWriter instead so that users can more easily write to MemoryStream instances. Similarly, the deserialization routines might should take TextReaders. In both cases, an overload that takes filenames as in the current behavior would be a very reasonable convienence to provide."

[ ] Reference Add more property initializers in deserialization.

[ ] #58 Implemented a method for updating deserialized Broombridge filed from v0.1 to newer versions. It would be great to extend this so that the updated Broombridge can be reserializaed back into a file.

Provide more array initialization functions, range conversions

As raised by @bettinaheim on microsoft/Quantum#182, we should build on the enhancements in #39 by providing more functions to prepare arrays.
For instance, the ReversibleLogicSynthesis sample contributed by @msoeken implements two functions that are good candidates for Microsoft.Quantum.Arrays:

  • Sequence : (Int, Int) -> Int[]: returns an array of integers in the given (inclusive) interval.
  • Numbers : Int -> Int[]: returns an array of integers in the given half-open interval starting at 0.

Implementing these and other similar array initialization functions would allow us to better isolate mutability and provide more reusable conveniences to users.

Single Type for artithmetics in Q#

Hello everybody!
I am not an expert, and I have been (unsuccessfully) trying to multiply two real numbers using the QuantumSimulator.
Simulation works fine using Toffolis, but I want to use the full qubit, here is the code:

operation Multab(fstNbr: Double, scdNbr: Double) : Double {
    let numBits = 3;
    mutable result = 0.0;
	using ((register1, register2, carry) = (Qubit[numBits], Qubit[numBits], Qubit[numBits])) {
		let qa = FixedPoint(1,register1);
		let qb = FixedPoint(1,register2);
		let qab = FixedPoint(1,carry);
    
		// initialize the quantum numbers:
		PrepareFxP(fstNbr, qa);
		PrepareFxP(scdNbr, qb);
		PrepareFxP(0.0, qab);
    
		// perform product
		MultiplyFxP(qa, qb, qab);

                   set result = MeasureFxP(qab);
                   ResetAll(register1 + register2 + carry);
	}

Using 3 bits, the result is 0 for any numbers, reasonable for 3 bits, but if I try 4 bits, simulation fails,
My point is: having available the Single precision type, avoiding use of Double type, could help to solve this issue?
Thanks a lot!

Reorganize and refactor libraries

As the Quantum Development Kit grows, it might be good to take a step back and try to make the API surface for the standard libraries a little bit more uniform (e.g.: consolidate the names of type conversion functions, use naming conventions to communicate what callables are operations, etc.). Similarly, we can make better use of new language features that have been introduced since Q# 0.1.

QuantumPhaseEstimation takes BigEndian argument

Describe the bug
I think this is just an inconsistency, most everything uses LittleEndian and the controlRegister argument takes a BigEndian.

Expected behavior
I would expect the signature for QuantumPhaseEstimation to be

    operation QuantumPhaseEstimation (
        oracle : DiscreteOracle, 
        targetState : Qubit[], 
        controlRegister : LittleEndian
    ) 
    : Unit is Adj + Ctl{
...
}

PrepareUniformSuperposition is not generally adjointable

Describe the bug
In the signature for PrepareUniformSuperposition, it says it should be adjointable, but it seems like it only is adjointable if you start with the uniform superposition state (ie. do PrepareUniformSuperposition then Adjoint PrepareUniformSuperposition)

To Reproduce

  • This snippet crashes at runtime:
open Microsoft.Quantum.Diagnostics;
open Microsoft.Quantum.Preparation;
open Microsoft.Quantum.Arithmetic;

operation Foo() : Unit {
    using (qs = Qubit[4]) {
        Adjoint PrepareUniformSuperposition(10, LittleEndian(qs));
        DumpMachine();
        PrepareUniformSuperposition(10, LittleEndian(qs));
        ResetAll(qs);
    }
}
  • If you reverse the order of the adjoint in the snippet:
open Microsoft.Quantum.Diagnostics;
open Microsoft.Quantum.Preparation;
open Microsoft.Quantum.Arithmetic;

operation Bar() : Unit {
    using (qs = Qubit[4]) {
        PrepareUniformSuperposition(10, LittleEndian(qs));
        DumpMachine();
        Adjoint PrepareUniformSuperposition(10, LittleEndian(qs));
        ResetAll(qs);
    }
}

Expected behavior
I would expect that it would not crash when I try to run Adjoint of the operation and then the operation which should do the same as if you do the operation and then its Adjoint.

Screenshots
Here is running of the sample on the binder instance at aka.ms/try-qsharp
image

System information
iqsharp 0.10.1912.501
Jupyter Core 1.2.20112.0
.NET Runtime .NETCoreApp,Version=v3.0

IncrementByInteger should not scale O(N^2)

Problem
Semantically, IncrementByInteger is a special case of AddI, where the first argument is a classical integer. For the user, it is hence rather surprising that the specialized version is much slower (O(N^2) general rotations compared to O(N) T-gates, with N the width of the target register).

Desired solution
Replacing the current implementation of IncrementByInteger with one using the general adder would be a good short-term solution. In the longer term, a more optimized implementation taking advantage of the classical nature of one argument would be preferable.

Alternative
In case the use of N additional qubits in the proposed short-term solution is a concern, the docs for IncrementByInteger should be improved to point out the unfavorable scaling and point users to the general adders for much better scaling.

Chemistry classes inaccessible outside samples namespace

Describe the bug
The Broombridge class is inaccessible outside of the Microsoft.Quantum.Chemistry.Samples namespace.

To Reproduce

  1. Create a new project, e.g. named EstimateReferenceEnergy. Reference Microsoft.Quantum.Chemistry;, Microsoft.Quantum.Chemistry.OrbitalIntegrals;, and/or
    Microsoft.Quantum.Chemistry.Broombridge;
  2. Reference the Broombridge class in the driver, for example: var broombridge = Broombridge.Deserializers.DeserializeBroombridge($filename$); where $filename$ is the filename of a YAML file.
  3. Run the project. The error Driver.cs(29,31): error CS0103: The name 'Broombridge' does not exist in the current context should appear.
  4. Rename the namespace to Microsoft.Quantum.Chemistry.Samples. The error should disappear and allow the code to run.

Expected behavior
Regardless of namespace name, the code should be able to reference the Broombridge class.

System information

  • OS: macOS Mojave
  • Microsoft.Quantum.Standard, Microsoft.Quantum.Chemistry, Microsoft.Quantum.Development.Kit all on version 0.7.1905.3109]

Additional context
Note - I've also seen this with other classes, like Paulis and QSharpFormat.

Improved quantum arithmetic support

The existing Microsoft.Quantum.Canon package has some support for quantum arithmetic, including ripple-carry comparators and the Draper adder specialized to classical integers (coherent addition by a classical constant), but there are a few additional arithmetic features that would be good to add:

  • Takahashi et al adders and comparators
  • Cuccaro et al adders

Likely we'll want to house this new functionality in a new package as well, such that we'll need a new project at the top level of the repo for this feature.

Documentation interlinking not working

The deprecation warning comes up on this page, but the text below that I think should link to the suggested replacement function is not actually linked.

> Please use @"Microsoft.Quantum.Arrays.Partitioned" instead.


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

RobustPhaseEstimation vs QuantumPhaseEstimation

Is your feature request related to a problem? Please describe.
RobustPhaseEstimation and QuantumPhaseEstimation return quite different values as "phases", which makes switching between the two non-trivial.

  • QPE returns (after measurement) an integer which, when divided by 2^(bits of precision), produces a floating-point number between 0 and 1, which needs to be multiplied by 2π to get a phase e^{iϕ}. The API documentation does not describe the return, and the only range in the docs is ϕ∈[0,2π) which seems to suggest that no multiplication by 2π is necessary.
  • Robust PE returns a floating point phase between -π and π which corresponds to e^{iϕ} directly.

Describe the solution you'd like
It would be great to unify the outputs of these operations or at least to document them better, with specific output descriptions and examples.

Expand support for BigInt

Now that BigInt is an accessible type, there should be more and more methods that work in terms of it. For example, if you measure a LittleEndian, that should ideally produce a BigInt instead of an Int. That way the method won't stop working at 64 qubits.

Actually, I am unsure why Q# even has a concept of a 64 bit integer. Is there any efficiency benefit to this design decision? Why not copy python and simply make the default integer type an arbitrary precision integer that just works? Is a 64 bit integer needed anywhere in the language?

ApplyIfOneCA and ApplyIfZeroCA have wrong signatures

Describe the bug
AplyIfOneCA and ApplyIfZeroCA have wrong signatures

To Reproduce
Current signatures are:

operation ApplyIfZeroCA<'T> (result : Result, (op : ('T => Unit is Adj), target : 'T)) : Unit is Adj 
operation ApplyIfOneCA<'T> (result : Result, (op : ('T => Unit is Adj), target : 'T)) : Unit is Adj 

Expected behavior
The signatures must be

operation ApplyIfZeroCA<'T> (result : Result, (op : ('T => Unit is Adj + Ctl), target : 'T)) : Unit is Adj + Ctl 
operation ApplyIfOneCA<'T> (result : Result, (op : ('T => Unit is Adj + Ctl), target : 'T)) : Unit is Adj + Ctl

EstimateFrequencyA raises wrong error message when prep `fail`s.

Describe the bug
If the preparation operation passed to EstimateFrequencyA encounters a fail statement during its execution, then EstimateFrequencyA fails with the error "Released qubits are not in zero state" rather than the error passed to the fail statement in the preparation operation.

To Reproduce

In [1]: operation Fail(target : Qubit[]) : Unit is Adj {
            X(target[0]);
            fail "oops";
        }
Out[1]:
- Fail

In [2]: operation EstimateFrequencyWithFailure() : Unit {
            let prep = Fail;
            let meas = Measure([PauliZ], _);
            let count = Microsoft.Quantum.Characterization.EstimateFrequencyA(prep, meas, 1, 100);
            Message($"{count}");
        }
Out[2]:
- EstimateFrequencyWithFailure

In [3]: %simulate EstimateFrequencyWithFailure
Unhandled exception. Microsoft.Quantum.Simulation.Simulators.Exceptions.ReleasedQubitsAreNotInZeroState: Released qubits are not in zero state.
Value cannot be null. (Parameter 'key')

Full reproduction at
https://gist.github.com/cgranade/b9c8c1cf4a9c3c6501e849b45b38b220.

Expected behavior
The message oops should have been printed with the simulator exception.

System information

PS> dotnet iqsharp --version
iqsharp: 0.10.1912.501
Jupyter Core: 1.2.20112.0
.NET Runtime: .NETCoreApp,Version=v3.0

Update Broombridge and chemistry library for UCC state preparation.

Broombridge:

  • Add UCC state preparation description
  • Reduce number of mandatory fields that are not used.
  • Clarify how various fields are used

Chemistry library:

  • Add UCC state preparation method
  • Minor restructuring to improve code reusability.

Specific tasks:

  • In UnitaryCCWavefunction.cs of gulow/GenericLadderOperatos , we have the comment

// This class is for Fermion terms that are not grouped into Hermitian bunches.
// Maybe need a stype for quantum state?

// For now, UCC is a subclass of MCF. It should eventually be a Hamiltonian
// + a WavefunctionSCF.

Other tasks:
Modify Broombridge MCF to have a reference state that is not always the vacuum state #66 (comment)

qsharp.compile doesn't return the list of operations if more than one is provided

When more than one operation is included in the snippet to compile, compile is not returning any operation, for example:

import qsharp;

ops = qsharp.compile("""
    operation PrepareBell(AliceQ : Qubit, BobQ : Qubit) : Unit {
        H(AliceQ);
        CNOT(AliceQ, BobQ);
    }
    operation ExtractMessage(AliceQ : Qubit, BobQ : Qubit) : Unit {
        let resultAlice = M(AliceQ);
        let resultBob = M(BobQ);
        Message($"Result: {resultBob}, {resultAlice}");
    }
""")

print(ops)

Should print

[<Q# callable ExtractMessage>, <Q# callable PrepareBell>]

but it's currently empty.

`ControlledOnInt` return should use LittleEndian argument

Describe the bug
The return of ControlledOnInt is an operation that takes a tuple (Qubit[], 'T). I think it should return an operation that takes a tuple of (LittleEndian, 'T) so that there is a clear interpretation of the integer that the register is supposed to represent.

To Reproduce
Not really any steps, just an inconsistent design.

Expected behavior
As noted above, to be able to control on an integer there has to be way to interpret a register as an integer. This can be encoded in the type signature by having the operation take a type LittleEndian.

Refactor Microsoft.Quantum.Preparation for consistency and to use style guide.

Describe the bug
The current Microsoft.Quantum.Preparation namespace, which provides functions and operations for preparing quantum registers in a variety of different states, currently suffers from a number of different usability and consistency issues:

  • The name of the PrepareQubit operation does not accurately reflect what it does (namely, that it prepares the positive eigenstate of a single-qubit Pauli operator). (originally reported by @tcNickolas)
  • API documentation comments are inaccurate and lack examples (the latter as noted in #113)
  • API documentation comments use mathematical notation in summaries, breaking hover information in LSP clients (e.g.: VS Code and VS 2019).
  • API documentation comments refer to "returning unitaries" rather than returning operations.
  • Private callables indicated by trailing rather than leading underscores; this should go away with adapting to use microsoft/qsharp-compiler#259, but it would be good to be consistent in the meantime.
  • The StatePreparationComplexCoefficients and StatePreparationPositiveCoefficients functions are identical up to the type of their expected inputs, rather than using type suffixes.
  • StatePreparationPositiveCoefficients can be readily generalized to allow negative coefficients as well.
  • The output type of QuantumROM is confusing, and can be clarified by defining a new UDT; this does present additional API documentation concerns, however, given microsoft/qsharp-compiler#113.
  • The name QuantumROM preferences the implementation above the thing being implemented, and should be renamed accordingly.

Update Broombridge for v0.7 release of chemistry library

  • Currently Broombridge has fields defined for orbital integral Hamiltonians, and sparse multi-configurational wavefunctions. We need to extend its functionality for describing other interesting formulations of electronic structure problems. See for instance #51 and #58 which introduce unitary coulped-cluster state preparation. What else would be desirable?

  • Currently contains a number of fields that are overlapping, not used, and also vague in which fields are used and how. We need reference Broombridge examples that are clearly commented, Unnecessary and inessential information should go into a miscellaneous section.

  • While updating Broombridge, we also need to update the json schema for validating the new Broombridge versions.

  • See #58, #51 and related. for possible extensions to the next version of Broombridge that is work in progress.

Provide more descriptive documentation on operations

There's basically no descriptions on what each operation does. Sure, based on the operation name some experienced developer can infer/guess what it does, but it's pretty hard for a beginner to make sense of it. As an example, look at the documentation on "S" operation.

Add function to compare arrays

Is your feature request related to a problem? Please describe.
I'm trying to compare two arrays to see whether they are equal.

Describe the solution you'd like
A library function that would compare them for me (for example, EqualA in Microsoft.Quantum.Logical namespace, to match the pattern of EqualXXX in that library).

Describe alternatives you've considered
The best solution I could come up with is

function EqualA<'T>(array1 : 'T[], array2 : 'T[], equal : (('T, 'T) -> Bool)) : Bool {
    if (Length(array1) != Length(array2)) {
        return false;
    }
    return All(equal, Zip(array1, array2));
}

Let me know if it would be helpful to send this as a pull request!

Inadequate information on the documentation page

Please provide a proper background and brief explanation on the functions .
Example code snippet would be much helpful.
Thank you.


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

Error while downloading qsharp Python package

Hi All,
trying to setup an env via conda as described, fails. i get an error:

Downloading and Extracting Packages qsharp-0.3.1811.203 | 51.0 MB | ########################################################################8 | 75% [Errno 2] No such file or directory: 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Anaconda3-5.2.0-Windows-x86_64\\pkgs\\qsharp-0.3.1811.203-preview_py3.6\\info\\recipe\\packages\\Microsoft.Quantum.Development.Kit.0.3.1811.203-preview\\lib\\netstandard2.0\\Microsoft.Quantum.Simulation.Simulators.deps.json'
can this be provoked by the path having spaces inside?

Thank you in advance.
Karl

i posted that issue also as an "idea" on the feddback page:
https://quantum.uservoice.com/forums/906946-samples-and-documentation/suggestions/36806068-python-interop-problem-setting-up-conda-env

Higher-level numerics functionality

Many quantum algorithms like HHL rely on having higher level numeric operations available (e.g.: 1 / x, arcsin, etc.). It would be great to add operations supporting these applications to the Quantum Development Kit's standard libraries, building on existing arithmetic work and the enhancements under #33.

Operations to repeat a call 𝑛 times

Is your feature request related to a problem? Please describe.
Following offline discussions with @alan-geller and @tcNickolas, and following a suggestion from @crazy4pi314, it would be nice to have operations which repeatedly apply another operation 𝑛 times.

Describe the solution you'd like
Following the example of R, this feature request would introduce five new operations into the Microsoft.Quantum.Standard package:

namespace Microsoft.Quantum.Canon {
    operation Repeat<'TInput>(op : ('TInput => Unit), nTimes : Int, input : 'TInput) : Unit { ... }
    operation RepeatA<'TInput>(op : ('TInput => Unit is Adj), nTimes : Int, input : 'TInput) : Unit is Adj { ... }
    operation RepeatC<'TInput>(op : ('TInput => Unit is Ctl), nTimes : Int, input : 'TInput) : Unit is Ctl { ... }
    operation RepeatCA<'TInput>(op : ('TInput => Unit is Adj + Ctl), nTimes : Int, input : 'TInput) : Unit is Adj + Ctl { ... }
}

namespace Microsoft.Quantum.Arrays {
    operation Replicate<'TInput, 'TOutput>(op : ('TInput => 'TOutput), nTimes : Int, input : 'TInput) : 'TOutput[] { ... }
}

Describe alternatives you've considered
The following currently work in place of the Repeat and Replicate operations proposed above, but are unwieldy:

ApplyToEach(Delay(op, input, _), ConstantArray(nTimes, ()));
ForEach(Delay(op, input, _), ConstantArray(nTimes, ()));

Alternative names considered for Replicate:

  • Repeat: doesn't make clear that outputs are collected.
  • Sample: may work, but is too close to Microsoft.Quantum.MachineLearning.Sampled; the noun-vs-verb distinction is not held to uniformly enough to make the distinction clear.
  • DrawSample: may work, but verb "draw" is a bit esoteric.
  • DoNTimes: similar to Repeat, doesn't make clear that outputs are collected.
  • Collect: doesn't make clear what is being collected.
  • RepeatAndCollect: somewhat clear, but unnecessarily verbose

A variant of Microsoft.Quantum.Canon.ApplyWith where inner and outer operations take different arguments

Is your feature request related to a problem? Please describe.
The pattern described by Microsoft.Quantum.Canon.ApplyWith is quite common in quantum algorithm, and there are many common cases where inner and outer operations take different arguments.

Describe the solution you'd like
I would like to add Microsoft.Quantum.Canon.ApplyWith2 and its variants (A, CA, C) with the following signature:

operation ApplyWith2<'T,'U>( 
    (outer: ('T => Unit is Adj), outArg : 'T),
    (inner : ('U => Unit), inArg : 'U), 
    ) : Unit 
// Called as: 
ApplyWith2( (op1,qubi1), (op2,(qubit1, qubit2)) );
// Note that (op2,(qubit1, qubit2)) looks very close to usual call op2(qubit1, qubit2)

Describe alternatives you've considered
An alternative is to introduce

operation HoldOperation<'T> ( op : ('T => Unit), arg : 'T, dummy : Unit ) : Unit {
	op(arg);
}

and use partial application to make operations with different arguments to have type Unit => Unit.
This might have bigger run-time overhead and is a bit more cumbersome to use.

Additional context
I am happy to make a PR with extended version of ApplyWith. I would appreciate Q# community and in particular @cgranade suggesting a better name for ApplyWith2.

API documentation for DecomposeIntoTimeStepsCA is confusing.

As per discussions in #178, the notation used by DecomposeIntoTimeStepsCA is different than the notation used in the reference cited by that operation (namely, quant-ph/0508139).

Thanks for pointing out the difference between the paper quant-ph/0508139 and the proposed change Chris!

We can better match the notation of the paper by putting the missing factor of two into
let stepSizeOuter = _TrotterStepSize(order/2);
&
return 1.0 / (4.0 - PowD(4.0, 1.0 / (IntAsDouble(2*order) - 1.0)));

instead of the proposed change
let stepSizeOuter = _TrotterStepSize(order);
&
return 1.0 / (4.0 - PowD(4.0, 1.0 / (IntAsDouble(order) - 1.0)));

That said, proposed change is indeed consistent with the paper.
@guanghaolow

This creates confusion in trying to specify inputs to DecomposeIntoTimeStepsCA, such that a remark should be added to clarify this distinction.

Quantum AND gates (a.k.a. CCNOT with constant target)

Is your feature request related to a problem? Please describe.

By using CCNOT gates when the target is known to be in a zero state, one looses optimization potential to reduce the number of T gates, as described in arXiv:1212.5069 and arXiv:1709.06648.

Describe the solution you'd like

I suggest to add operations

operation ANDOp (control1 : Qubit, control2 : Qubit, target : Qubit) : Unit

and

operation ANDOpLowDepth (control1 : Qubit, control2 : Qubit, target : Qubit) : Unit

which implement the circuits described in Fig. 3 in arXiv:1709.06648 and Fig. 1(a) in arXiv:1212.5069, respectively.

The signature allows the gates to be wrapped inside the CCNOTop type.

ANDOp requires 4 T gates, T depth 2, and no ancilla. ANDOpLowDepth requires 4 T gates, T depth 1, and one ancilla. No T gate is required in the adjoint operation due to measurement based uncomputation.

Describe alternatives you've considered

Implementing the operations as private operations.

Additional context

A possible implementation is illustrated in microsoft/Quantum#121 (comment).

Some facts and assertions take message inputs, others don't.

Describe the bug
The signatures of different facts and assertions are not consistent with respect to supporting message : String inputs. For example:

// No message input.
function NearEqualityFactD(actual : Double, expected : Double) : Unit;
operation AssertPhase (expected : Double, qubit : Qubit, tolerance : Double) : Unit;

// Takes message input.
function EqualityFactI(actual : Int, expected : Int, message : String) : Unit;
function AllEqualityFactB(actual : Bool[], expected : Bool[], message : String) : Unit;

Various library functions and operations do not follow style guide.

Describe the bug
The name RandomInt suggests a function, not an operation, but sampling a pseudorandom number generator or a QRNG is not deterministic. Thus, the names of these operations should be changed to SampleRandomInt and similar with appropriate deprecation warnings added.

DecomposeIntoTimeStepsCA doc bug

Current documentation for DecomposeIntoTimeStepsCA says the only Trotter-Suzuki orders supported are one and two:

    /// ## trotterOrder
    /// Selects the order of the Trotter–Suzuki integrator to be used.
    /// Order 1 and 2 are currently supported.

Looking at the implementation, it appears though like arbitrary even orders are supported, too.

The documentation should hence be updated if higher orders are in fact supported. In case the code handling higher orders were not supported/known buggy(?), a comment to this effect should be added to the code.

A Quantum Approximate Optimization Algorithm (QAOA) feature request.

As confirmed with @cgranade, Microsoft Quantum Libraries lack the implementation of the Quantum Approximate Optimization Algorithm (QAOA, https://arxiv.org/pdf/1411.4028.pdf). There is a problem-specific implementation in Q# available here.

A general implementation within Quantum Libraries would be useful. For a fixed value of a parameter p (see the paper), the contribution should include the use of a classical optimizer to choose optimal starting angles.

Clarify the API description of the Fact function

The description here of "declares if a classical condition is true" isn't very clear. From what I understand, if the classical condition is true, nothing happens and computation is continued, whereas if false, it aborts computation and no further Q# code is run. The failure/abort point could be highlighted.

Improve chemistry library modularity and clean up code.

Goal: Address the following comment. "What totally make sense is to use Broombridge for input and output of a whole sample / algorithm. But my feeling (and limited understanding) so far is that the workflow makes things complicated because functionalities I've seen in the libraries seem to "entangle" or "tie" a number of objects and concepts that actually exist separately and for which a lot of modifications and research is done."

Addressed partially in this PR #58

To these ends, we want to separate the basic objects from current large classes to improve code reuse of smaller modules, and improve readability. Examples

  • FermionTerm currently has way too many overlapping constructors, comparers, and methods. This must be simplified.
  • FermionTerm should be inherit a simpler class for sequences of operators, and build off that.
  • FermionTerm should also have terms indexed by just integers. The current approach of indexing with SpinOrbitals is too unwieldy.
  • The index conversion of SpinOrbitals to integers should be invoked early and only once when the problem is defined.
  • FermionHamiltonian has too many metadata variables. This class should just be about the Hamiltonian, and we should create another class e.g. ProblemInstance than has a FermionHamiltonian member, and problem metadata. Right now, these are all packaged into one hard-to-understand class.
  • Initial state Ansatzes should be split off from FermionHamiltonian

TODO

  • Create generic Hamiltonian class for general creation, manipulation, and analysis of Hamiltonians.

    • Create orbital integral Hamiltonian class
    • Create fermion Hamiltonian class
    • Create Pauli Hamiltonian class.
    • Decide between multiple subclasses for different encoding schemes, e,g, generic Pauli Hamiltonian class, or single point-of-reference class.
  • Create generic initial state ansatz class

    • Create Hartree-Fock state class
    • Create Multi-Configurational state class
    • Create Unitary Coupled-Cluster class
  • Create abstract ladder (raising / lowering) operator class

    • Create fermion term classes (These are strongly typed depending on property to reduce constructor parameters and eliminate ambiguity in coefficient and ordering conventions).
      • FermionTerm class for normal ordered-and index-ordered fermion terms (used in state prepataion).
      • HermitianFermionTerm class for a Hermitian combination of fermion term, which has a different ordering version (used in Hamiltonian class)
  • Create accessible problem description container and configuration file for non-specialist users.

  • Create convenience functions and configuration files for common workflows.

Split Broombridge into multiple parts

  • Version control
  • Data structures
  • Serialization / Deserialization

Create explicit interface for converting between

  • Orbital integrals and fermions for both terms and Hamiltonians.
  • fermions and Paulis for both terms and Hamiltonians and states.
  • Broombridge and the relevant classes above.

Delay operation for delaying the operation application

Is your feature request related to a problem? Please describe.
Frequently it is convenient to partially apply all arguments, but delay the application of operation.
There is no Q# syntax for that.

Describe the solution you'd like
Introduce operation Delay and its variants with the following signature:

operation Delay<'T>( op : ('T => Unit), target : 'T, aux : Unit ) : Unit 
// Usage 
let delayedX = Delay(X,qubit,_); // now delayed X is of type (Unit => Unit)

together with a functional version Delayed with variants with signature:

function Delayed<'T>( op : ('T => Unit), target : 'T) : (Unit => Unit)
// Usage 
let delayedX = Delayed(X, qubit);

Describe alternatives you've considered
A potential alternative is to extend Q# to have a special syntax.

Additional context
It is convenient for passing arguments of type Unit => Unit to functions and operations.

Why does it occur ExecutionFailException?

An exception occurs in the following code. Are there any restrictions other than the exception message?

IntAsBoolean( 2, 100 )

Microsoft.Quantum.Simulation.Core.ExecutionFailException: 'number must be between 0 and 2^bits - 1'


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

Refactor Microsoft.Quantum.Simulation and Microsoft.Quantum.AmplitudeAmplification to use style guide.

Is your feature request related to a problem? Please describe.
With resolving #35 in April, we made a lot of progress on making the libraries more consistent, more discoverable, and easier to use. It would be good to continue that effort by using new Q# features like UDT named items, namespace aliases, and attributes (microsoft/qsharp-compiler#169) to make the APIs for data structures in the simulation and amplitude amplification namespaces easier to use.

This would also be a good chance to improve further our consistency with the Q# style guide, parallel to efforts such as microsoft/QuantumKatas#110.

Describe the solution you'd like

  • Remove AmpAmp prefix from function and operation names in Microsoft.Quantum.AmplitudeAmplification (redundant with namespace name).
  • Rename functions in Microsoft.Quantum.AmplitudeAmplification to use only noun or adjective pharases.
  • Rename operations in Microsoft.Quantum.AmplitudeAmplification to use only verb phrases.
  • Ensure that UDTs in Microsoft.Quantum.AmplitudeAmplification have named items.
  • Refactor Microsoft.Quantum.Simulation to move all type conversion functions that act on basic types to Microsoft.Quantum.Convert, use XAsY naming scheme.
  • Refactor Microsoft.Quantum.Simulation to rename type conversion functions specific to simulation data to use XAsY naming scheme.
  • Ensure that UDTs in Microsoft.Quantum.Simulation have named items.
  • Remove "accessor functions" such as GetGeneratorSystemFunction in favor of UDT named item accessor notation.

Incorrect Jordan Wigner C# Encoding?

Looking for some clarification into the implementation of the Jordan Wigner transform in Q#.

if (Enumerable.SequenceEqual(pqrsPermuted, prsq))
{
h123 = new double[] { 0.0, 0.0, coeff };
}
else if (Enumerable.SequenceEqual(pqrsPermuted, pqsr))
{
h123 = new double[] { -coeff, 0.0, 0.0 };
}
else if (Enumerable.SequenceEqual(pqrsPermuted, psrq))
{
h123 = new double[] { 0.0, -coeff, 0.0 };
}
else
{
h123 = new double[] { 0.0, 0.0, 0.0 };
}
v0123 = new double[] { -h123[0] - h123[1] + h123[2],
h123[0] - h123[1] + h123[2],
-h123[0] - h123[1] - h123[2],
-h123[0] + h123[1] + h123[2] };

Here, we have only one of the h^(1), h^(2), h^(3) terms associated with a coefficient. When we reference the paper associated with the implementation, two should be additive inverses, while the last is 0:

image

(pg 13, 14 of Whitfield et al. https://arxiv.org/pdf/1001.3855.pdf)

The coefficient orderings + labelings seem to differ greatly and produce different results.

Functions for identity and equality checking

Is your feature request related to a problem? Please describe.
I find myself writing these functions when making use of the array iteration functions such as Mapped and Filtered.

Describe the solution you'd like
I suggest to have functions in the library for Identity<'T>(a), EqualsX(a, b), NotEqualsX(a, b), where X in I, B, D, and L.

Here is an example how these functions can be used for retrieving all bits in an integer that are 1 in their binary expansion:

function IntegerBits(val : Int, bits : Int) : Int[] {
    let id = Id<(Int, Bool)>;
    let pred = Compose(EqualsB(_, true), Snd<Int, Bool>);
    return Mapped(Fst<Int, Bool>, Filtered(pred, MappedByIndex(id, IntAsBoolArray(val, bits))));
}

Describe alternatives you've considered
Writing the functions as local private functions.

Additional context
N/A

Trotter step not implemented?

Describe the bug
Trotterization is not implemented within the TrotterStepOracle method.
I was looking through the implementation of the TrotterStepOracle and saw the reference to the TrotterSimulationAlgorithm method:

let simulationAlgorithm = (TrotterSimulationAlgorithm(trotterStepSize, trotterOrder))!;
let oracle = simulationAlgorithm(trotterStepSize, evolutionGenerator, _);

When we look at the implementation of the TrotterSimulationAlgorithm itself:

function TrotterSimulationAlgorithm (trotterStepSize : Double, trotterOrder : Int) : SimulationAlgorithm
{
return SimulationAlgorithm(TrotterSimulationAlgorithmImpl(trotterStepSize, trotterOrder, _, _, _));
}

Which calls the TrotterSimulationAlgorithmImpl:

operation TrotterSimulationAlgorithmImpl (trotterStepSize : Double, trotterOrder : Int, maxTime : Double, evolutionGenerator : EvolutionGenerator, qubits : Qubit[]) : Unit
{
body (...)
{
let nTimeSlices = Ceiling(maxTime / trotterStepSize);
let resizedTrotterStepSize = maxTime / IntAsDouble(nTimeSlices);
for (idxTimeSlice in 0 .. nTimeSlices - 1)
{
(TrotterStep(evolutionGenerator, trotterOrder, resizedTrotterStepSize))(qubits);
}
}
adjoint invert;
controlled distribute;
controlled adjoint distribute;
}

So, don't we feed both trotterStepSize to both the trotterStepSize and maxTime, causing the number of time slices to be 1, regardless of the step size?

This also causes errors in the energy estimate, as the rescaleFactor assumes that the Trotterization step has been fully implemented. For example, test the MolecularHydrogen sample with a very small trotterStep. The expected energy balloons or varies wildly.

Expected behavior
The TrotterStepOracle should either apply multiple rounds of small exponentiated matrices or give a warning that Trotterization hasn't been implemented yet.

System information

  • macOS Mojave
  • Microsoft.Quantum.Chemistry 0.7.1905.3109

Expose interface for compiling arbitrary state preparation operations

The function Microsoft.Quantum.Preparation._CompileApproximateArbitraryStatePreparation does not adhere to current design principles, and thus has not been exposed for public use. Currently, this function cannot be converted to use the new internal keyword, however, as the QML library uses this function in its input encoding logic. The relevant compilation logic should be exposed publicly, such that the QML input encoding logic can depend on the new functionality.

Variants of ApplyIf that use Result type instead of Bool

Is your feature request related to a problem? Please describe.
Resource estimation of code involving measurements is a challenge for ResourceEstimator Q# simulator. Currently the only way to help ResourceEstimator to deal with measurement is to use AssertProb to provide measurement outcome probability. There are resource estimation scenarios where this is not sufficient.

Describe the solution you'd like
Adding combinators ApplyIfOne, ApplyIfZero, ApplyIfElse to Microsoft.Quantum.Canon will help to express patterns of code that ResourceEstimator has potential to handle.
Suggested signatures are the following ( +usual A, CA, C versions) :

operation ApplyIfOne<'T>( 
    measurementResult : Result, 
    (onResultOneOp : ('T => Unit), oneArg : 'T) 
) : Unit

operation ApplyIfZero<'T>( 
    measurementResult : Result,
    (onResultZeroOp : ('T => Unit), zeroArg : 'T) 
) : Unit

operation ApplyIfElse<'T,'U>(
    measurementResult : Result,
    (onResultZeroOp : ('T => Unit), zeroArg : 'T) ,
    (onResultOneOp : ('U => Unit), oneArg : 'U) 
) : Unit

// Example of calls: 
ApplyIfOne(res, (CX,(q1, q2)) ); 
// note how expression (CX, (q1, q2)) is reminiscent to usual call CX(q1,q2)
ApplyIfElse(res, (CX,(q1, q2)), (X,q3) );

Describe alternatives you've considered
One alternative is to replace type of onResultZeroOp and others by Unit => Unit and use

operation HoldOperation<'T> ( op : ('T => Unit), arg : 'T, dummy : Unit ) : Unit {
  op(arg);
}

to reduce general case to Unit => Unit, but it seems to produce cumbersome code and has potential run-time overhead.

Additional context
This is a prerequisite for potential improvements to QCTraceSimulator and ResourceEstimator.
Feedback from Q# community and from @cgranade in particular about the choice of names and signatures is very welcome.

Enable Source Link

Please describe what you would like the feature to accomplish.

I would like to see source code and debug symbol information when debugging code that uses NuGet packages from this repository.

Describe the solution you'd like

It would be nice to enable SourceLink support.

Describe alternatives you've considered

I am not aware of alternatives to SourceLink that are cross-platform.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.