Skip to content
This repository was archived by the owner on Jan 12, 2024. It is now read-only.
Merged
51 changes: 42 additions & 9 deletions src/Simulation/CsharpGeneration.Tests/SimulationCodeTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -3685,10 +3685,21 @@ namespace Microsoft.Quantum.Tests.UnitTests
baseSim.OnLog += this.Output.WriteLine;
}

sim.Run<UnitTest1, QVoid, QVoid>(QVoid.Instance).Wait();
if (sim is IDisposable disposeSim)
try
{
sim.Execute<UnitTest1, QVoid, QVoid>(QVoid.Instance);
}
catch (Exception e)
{
#line 22 "%%"
Xunit.Assert.True(false, "Q# Test failed. For details see the Standard output below.");
}
finally
{
disposeSim.Dispose();
if (sim is IDisposable disposeSim)
{
disposeSim.Dispose();
}
}
}
}
Expand Down Expand Up @@ -3717,10 +3728,21 @@ namespace Microsoft.Quantum.Tests.UnitTests
baseSim.OnLog += this.Output.WriteLine;
}

sim.Run<UnitTest1, QVoid, QVoid>(QVoid.Instance).Wait();
if (sim is IDisposable disposeSim)
try
{
disposeSim.Dispose();
sim.Execute<UnitTest1, QVoid, QVoid>(QVoid.Instance);
}
catch (Exception e)
{
#line 22 "%%"
Xunit.Assert.True(false, "Q# Test failed. For details see the Standard output below.");
}
finally
{
if (sim is IDisposable disposeSim)
{
disposeSim.Dispose();
}
}
}
}
Expand Down Expand Up @@ -3778,10 +3800,21 @@ namespace Microsoft.Quantum.Tests.UnitTests
baseSim.OnLog += this.Output.WriteLine;
}

sim.Run<UnitTest2, QVoid, QVoid>(QVoid.Instance).Wait();
if (sim is IDisposable disposeSim)
try
{
sim.Execute<UnitTest2, QVoid, QVoid>(QVoid.Instance);
}
catch (Exception e)
{
disposeSim.Dispose();
#line 26 "%%"
Xunit.Assert.True(false, "Q# Test failed. For details see the Standard output below.");
}
finally
{
if (sim is IDisposable disposeSim)
{
disposeSim.Dispose();
}
}
}
}
Expand Down
24 changes: 21 additions & 3 deletions src/Simulation/CsharpGeneration/SimulationCode.fs
Original file line number Diff line number Diff line change
Expand Up @@ -1240,19 +1240,37 @@ module SimulationCode =
let disposeSim = ``ident`` "disposeSim"
let ``this.Output`` = ``ident`` "this" <|.|> ``ident`` "Output"
let ``sim.OnLog`` = baseSim <|.|> ``ident`` "OnLog"
let Run = generic "Run" ``<<`` [opName; "QVoid"; "QVoid"] ``>>``
let Execute = generic "Execute" ``<<`` [opName; "QVoid"; "QVoid"] ``>>``

let simCond = sim |> ``is assign`` "Microsoft.Quantum.Simulation.Common.SimulatorBase" baseSim .&&. ``this.Output`` .!=. ``null``

let getSimulator = ``var`` "sim" (``:=`` <| ``new`` (``ident`` <| targetName.ToString()) ``(`` [] ``)``)
let assignLogEvent =
``if`` ``(`` simCond ``)``
[ ``sim.OnLog`` <+=> (``this.Output`` <|.|> ``ident`` "WriteLine") ] None
let ``sim.Run.Wait`` = sim <.> (Run, [ ``ident`` "QVoid" <|.|> ``ident`` "Instance"]) <.> ((``ident`` "Wait"), []) |> statement
let ``sim.Execute`` = sim <.> (Execute, [ ``ident`` "QVoid" <|.|> ``ident`` "Instance"]) |> statement
let disposeOfRun =
``if`` ``(`` (sim |> ``is assign`` "IDisposable" disposeSim) ``)``
[ disposeSim <.> ((``ident`` "Dispose"), []) |> statement ] None

let errMsg = ``literal`` "Q# Test failed. For details see the Standard output below."

let tryRunCatch =
``try``
[
``sim.Execute``
]
[
``catch`` (Some ("Exception", "e"))
[
(``ident`` "Xunit.Assert") <.> ((``ident`` "True"), [``false`` :> ExpressionSyntax; errMsg]) |> (statement >> ``#line`` (opStart + 1) opSourceFile)
]
]
(Some (``finally``
[
``disposeOfRun``
]))

``attributes``
[
``attribute`` None (``ident`` "Xunit.Fact") [];
Expand All @@ -1261,7 +1279,7 @@ module SimulationCode =
]
(``method`` "void" opName ``<<`` [] ``>>`` ``(`` [] ``)`` [``public``]
``{``
[getSimulator; assignLogEvent; ``sim.Run.Wait``; disposeOfRun]
[getSimulator; assignLogEvent; tryRunCatch]
``}``
|> ``with trivia`` (``#lineNr`` (opStart + 1) opSourceFile) // we need 1-based line numbers here, and opStart is zero-based
)
Expand Down
4 changes: 2 additions & 2 deletions src/Simulation/QCTraceSimulator/DepthCounter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,8 @@ public void OnOperationEnd(object[] returnedQubitsTraceData)
OperationCallRecord caller = operationCallStack.Peek();
HashedString callerName = caller.OperationName;

caller.ReleasedQubitsAvailableTime = Max(opRec.ReleasedQubitsAvailableTime, caller.ReleasedQubitsAvailableTime );
caller.ReleasedQubitsAvailableTime = Max(opRec.ReleasedQubitsAvailableTime, caller.ReleasedQubitsAvailableTime );
caller.ReleasedQubitsAvailableTime = Max(opRec.ReleasedQubitsAvailableTime, caller.ReleasedQubitsAvailableTime);
caller.ReturnedQubitsAvailableTime = Max(opRec.ReturnedQubitsAvailableTime, caller.ReturnedQubitsAvailableTime);

double[] metrics =
StatisticsRecord(
Expand Down
1 change: 0 additions & 1 deletion src/Simulation/QCTraceSimulator/DistinctInputsChecker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.Quantum.Simulation.Core;
using Microsoft.Quantum.Simulation.Simulators.QCTraceSimulators;

namespace Microsoft.Quantum.Simulation.QCTraceSimulatorRuntime
{
Expand Down
2 changes: 1 addition & 1 deletion src/Simulation/QCTraceSimulator/Exceptions.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

namespace Microsoft.Quantum.Simulation.Simulators.QCTraceSimulators
namespace Microsoft.Quantum.Simulation.QCTraceSimulatorRuntime
{
/// <summary>
/// This exception is thrown when the input to an
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
using System.Text;
using System.Threading.Tasks;
using Microsoft.Quantum.Simulation.Core;
using Microsoft.Quantum.Simulation.Simulators.QCTraceSimulators;

namespace Microsoft.Quantum.Simulation.QCTraceSimulatorRuntime
{
Expand Down
1 change: 0 additions & 1 deletion src/Simulation/QCTraceSimulator/QCTraceSimulatorCore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ namespace Microsoft.Quantum.Simulation.QCTraceSimulatorRuntime
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.Quantum.Simulation.Common;
using Microsoft.Quantum.Simulation.Simulators.QCTraceSimulators;
using System.Linq;

[Serializable]
Expand Down
2 changes: 0 additions & 2 deletions src/Simulation/QCTraceSimulator/QubitMetrics.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using Microsoft.Quantum.Simulation.Simulators.QCTraceSimulators;

namespace Microsoft.Quantum.Simulation.QCTraceSimulatorRuntime
{
/// <summary>
Expand Down
39 changes: 39 additions & 0 deletions src/Simulation/QsharpCore/Targeting.qs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

/// # Summary
/// This namespace provides functionality for targeting specific quantum processors.
namespace Microsoft.Quantum.Targeting {
/// # Summary
/// Compiler-recognized attribute used to mark a callable with the runtime capabilities it
/// requires.
///
/// # Named Items
/// ## Level
/// The name of the runtime capability level required by the callable.
///
/// ## Reason
/// A description of why the callable requires this runtime capability.
///
/// # Remarks
/// This attribute is automatically added to callables by the compiler, unless an instance of
/// this attribute already exists on the callable. It should not be used except in rare cases
/// where the compiler does not infer the required capability correctly.
///
/// Below is the list of capability level names, in order of increasing capabilities or
/// decreasing restrictions:
///
/// ## `"BasicQuantumFunctionality"`
/// Measurement results cannot be compared for equality.
///
/// ## `"BasicMeasurementFeedback"`
/// Measurement results can be compared for equality only in if-statement conditional
/// expressions in operations. The block of an if-statement that depends on a result cannot
/// contain set statements for mutable variables declared outside the block, or return
/// statements.
///
/// ## `"FullComputation"`
/// No runtime restrictions. Any Q# program can be executed.
@Attribute()
newtype RequiresCapability = (Level : String, Reason : String);
}
5 changes: 1 addition & 4 deletions src/Simulation/QsharpFoundation/Core.qs
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,14 @@ namespace Microsoft.Quantum.Core {
/// # Summary
/// Compiler-recognized attribute used to mark a type or callable as deprecated.
///
/// # Input
/// # Named Items
/// ## NewName
/// The full name of the type or callable to use instead.
/// Is set to the empty String if a type or callable has been deprecated without substitution.
///
@Attribute()
newtype Deprecated = (NewName : String);


/// # Summary
/// Returns a default instance of the specified type.
///
Expand Down Expand Up @@ -136,5 +135,3 @@ namespace Microsoft.Quantum.Core {
}

}


Original file line number Diff line number Diff line change
Expand Up @@ -177,32 +177,6 @@ from op in primitiveOperationAsCircuits
}
}

#region Helpers
static private (long, long) Reduce(long numerator, long denominatorPower)
{
if (numerator == 0)
{
return (0, 0);
}

if (numerator % 2 != 0)
{
return (numerator, denominatorPower);
}

long numNew = numerator;
long denomPowerNew = denominatorPower;

while (numNew % 2 == 0)
{
numNew /= 2;
denomPowerNew -= 1;
}

return (numNew, denomPowerNew);
}
#endregion

#region Primitive operations logic

private void DoPrimitiveOperation(PrimitiveOperationsGroups operation, IQArray<Qubit> target, bool invalidateConstraints = true)
Expand All @@ -228,7 +202,7 @@ private void RFrac(Pauli pauli, long numerator, long denominatorPower, Qubit tar
return; // global phase case
}

(long numNew, long denomPowerNew) = Reduce(numerator, denominatorPower);
(long numNew, long denomPowerNew) = CommonUtils.Reduce(numerator, denominatorPower);
switch (denomPowerNew)
{
case 3:
Expand Down
7 changes: 4 additions & 3 deletions src/Simulation/Simulators.Impl/QuantumSimulator/Measure.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,11 @@ public QSimMeasure(QuantumSimulator m) : base(m)
{
throw new InvalidOperationException($"Both input arrays for {this.GetType().Name} (paulis,qubits), must be of same size");
}
foreach (Qubit q in qubits)
if (qubits.Length == 1)
{
//setting qubit as measured to allow for release
q.IsMeasured = true;
// When we are operating on a single qubit we will collapse the state, so mark
// that qubit as measured.
qubits[0].IsMeasured = true;
}
return Measure(Simulator.Id, (uint)paulis.Length, paulis.ToArray(), qubits.GetIds()).ToResult();
};
Expand Down
9 changes: 9 additions & 0 deletions src/Simulation/Simulators.Tests/Circuits/CoreOperations.qs
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,7 @@ namespace Microsoft.Quantum.Tests.CoreOperations {

// Using a different namespace, so tests can be auto-discovered.
namespace Microsoft.Quantum.Simulation.Simulators.Tests.Circuits {
open Microsoft.Quantum.Simulation.Simulators.Tests.Circuits.Generics;
open Microsoft.Quantum.Intrinsic;
open Microsoft.Quantum.Convert;
open Microsoft.Quantum.Diagnostics;
Expand Down Expand Up @@ -559,6 +560,14 @@ namespace Microsoft.Quantum.Simulation.Simulators.Tests.Circuits {
}
}

operation ReleaseMeasureMultipleQubitCheck() : Unit {
using (qs = Qubit[2]) {
ApplyToEach(H, qs);
let r = Measure([PauliZ, PauliZ], qs);
// Should raise an exception
}
}

operation BorrowingQubitCheck () : Unit
{
using (q = Qubit())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,15 @@ public async Task MeasuredQubitReleaseTest()
await ReleaseMeasuredQubitCheck.Run(sim);
}

//test to check that qubits cannot be released after multiple qubit measure
[Fact]
public async Task MeasuredMultipleQubitsReleaseTest()
{
var sim = new QuantumSimulator();

await Assert.ThrowsAsync<ReleasedQubitsAreNotInZeroState>(() => ReleaseMeasureMultipleQubitCheck.Run(sim));
}

//test to check that qubit that is released and reallocated is in state |0>
[Fact]
public async Task ReallocateQubitInGroundStateTest()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
let arr = Default<Qubit[]>();
using (qs = Qubit[2]) {
Ignore(Measure([PauliX, PauliX], qs));
ResetAll(qs);
return "TargetedExe";
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@
<file src="..\Native\osx\*" target="runtimes\osx-x64\native" />
<file src="..\Native\linux\*" target="runtimes\linux-x64\native" />
<file src="..\Native\win10\*" target="runtimes\win-x64\native" />
<file src="..\Common\bin\$Configuration$\**\Microsoft.Quantum.Simulation.Common.xml" target="lib" />
<file src="..\Common\bin\$Configuration$\**\Microsoft.Quantum.Simulation.Common.pdb" target="lib" />
<file src="..\QCTraceSimulator\bin\$Configuration$\**\Microsoft.Quantum.Simulation.QCTraceSimulatorRuntime.xml" target="lib" />
<file src="..\QCTraceSimulator\bin\$Configuration$\**\Microsoft.Quantum.Simulation.QCTraceSimulatorRuntime.pdb" target="lib" />
<file src="..\Simulators\bin\$Configuration$\**\Microsoft.Quantum.Simulators.dll" target="lib" />
<file src="..\Simulators\bin\$Configuration$\**\Microsoft.Quantum.Simulators.xml" target="lib" />
<file src="..\Simulators\bin\$Configuration$\**\Microsoft.Quantum.Simulators.pdb" target="lib" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ namespace Microsoft.Quantum.Diagnostics {
/// # Summary
/// Given two operations, asserts that they act identically for all input states.
///
/// This assertion is implemented by using the Choi–Jamiłkowski isomorphism to reduce
/// This assertion is implemented by using the Choi–Jamiołkowski isomorphism to reduce
/// the assertion to one of a qubit state assertion on two entangled registers.
/// Thus, this operation needs only a single call to each operation being tested,
/// but requires twice as many qubits to be allocated.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Core\Microsoft.Quantum.Runtime.Core.csproj" />
<ProjectReference Include="..\QsharpFoundation\Microsoft.Quantum.QSharp.Foundation.csproj" />
<ProjectReference Include="..\CsharpGeneration\Microsoft.Quantum.CsharpGeneration.fsproj" PrivateAssets="All" IsQscReference="true" />
</ItemGroup>
Expand Down