Skip to content
This repository was archived by the owner on Jan 12, 2024. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3,971 changes: 3,780 additions & 191 deletions NOTICE.txt

Large diffs are not rendered by default.

21 changes: 20 additions & 1 deletion Simulation.sln
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IonQExe", "src\Simulation\S
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "QCIExe", "src\Simulation\Simulators.Tests\TestProjects\QCIExe\QCIExe.csproj", "{C015FF41-9A51-4AF0-AEFC-2547D596B10A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TargetedExe", "src\Simulation\Simulators.Tests\TestProjects\TargetedExe\TargetedExe.csproj", "{D292BF18-3956-4827-820E-254C3F81EF09}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TargetedExe", "src\Simulation\Simulators.Tests\TestProjects\TargetedExe\TargetedExe.csproj", "{D292BF18-3956-4827-820E-254C3F81EF09}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IntrinsicTests", "src\Simulation\Simulators.Tests\TestProjects\IntrinsicTests\IntrinsicTests.csproj", "{D5D41201-101F-4C0D-B6A0-201D8FC3AB91}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Expand Down Expand Up @@ -477,6 +479,22 @@ Global
{D292BF18-3956-4827-820E-254C3F81EF09}.RelWithDebInfo|Any CPU.Build.0 = Release|Any CPU
{D292BF18-3956-4827-820E-254C3F81EF09}.RelWithDebInfo|x64.ActiveCfg = Release|Any CPU
{D292BF18-3956-4827-820E-254C3F81EF09}.RelWithDebInfo|x64.Build.0 = Release|Any CPU
{D5D41201-101F-4C0D-B6A0-201D8FC3AB91}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D5D41201-101F-4C0D-B6A0-201D8FC3AB91}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D5D41201-101F-4C0D-B6A0-201D8FC3AB91}.Debug|x64.ActiveCfg = Debug|Any CPU
{D5D41201-101F-4C0D-B6A0-201D8FC3AB91}.Debug|x64.Build.0 = Debug|Any CPU
{D5D41201-101F-4C0D-B6A0-201D8FC3AB91}.MinSizeRel|Any CPU.ActiveCfg = Debug|Any CPU
{D5D41201-101F-4C0D-B6A0-201D8FC3AB91}.MinSizeRel|Any CPU.Build.0 = Debug|Any CPU
{D5D41201-101F-4C0D-B6A0-201D8FC3AB91}.MinSizeRel|x64.ActiveCfg = Debug|Any CPU
{D5D41201-101F-4C0D-B6A0-201D8FC3AB91}.MinSizeRel|x64.Build.0 = Debug|Any CPU
{D5D41201-101F-4C0D-B6A0-201D8FC3AB91}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D5D41201-101F-4C0D-B6A0-201D8FC3AB91}.Release|Any CPU.Build.0 = Release|Any CPU
{D5D41201-101F-4C0D-B6A0-201D8FC3AB91}.Release|x64.ActiveCfg = Release|Any CPU
{D5D41201-101F-4C0D-B6A0-201D8FC3AB91}.Release|x64.Build.0 = Release|Any CPU
{D5D41201-101F-4C0D-B6A0-201D8FC3AB91}.RelWithDebInfo|Any CPU.ActiveCfg = Debug|Any CPU
{D5D41201-101F-4C0D-B6A0-201D8FC3AB91}.RelWithDebInfo|Any CPU.Build.0 = Debug|Any CPU
{D5D41201-101F-4C0D-B6A0-201D8FC3AB91}.RelWithDebInfo|x64.ActiveCfg = Debug|Any CPU
{D5D41201-101F-4C0D-B6A0-201D8FC3AB91}.RelWithDebInfo|x64.Build.0 = Debug|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -508,6 +526,7 @@ Global
{55833C6C-6E91-4413-9F77-96B3A09666B8} = {09C842CB-930C-4C7D-AD5F-E30DE4A55820}
{C015FF41-9A51-4AF0-AEFC-2547D596B10A} = {09C842CB-930C-4C7D-AD5F-E30DE4A55820}
{D292BF18-3956-4827-820E-254C3F81EF09} = {09C842CB-930C-4C7D-AD5F-E30DE4A55820}
{D5D41201-101F-4C0D-B6A0-201D8FC3AB91} = {09C842CB-930C-4C7D-AD5F-E30DE4A55820}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {929C0464-86D8-4F70-8835-0A5EAF930821}
Expand Down
52 changes: 52 additions & 0 deletions src/Simulation/Common/Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,5 +49,57 @@ where op.IsSubclassOf(typeof(T))
factory.Register(op.BaseType, op);
}
}

internal static long NextLongBelow(this System.Random random, long upperExclusive)
{
// Don't allow sampling non-positive numbers, so that we don't break
// Math.Log2.
if (upperExclusive <= 0)
{
throw new ArgumentException(
$"Must be positive, got {upperExclusive}.",
nameof(upperExclusive)
);
}
long SampleNBits(int nBits)
{
// Note that we can assume that nBytes is never more than 8,
// since we got there by looking at the bit length of
// upperExclusive, which is itself a 64-bit integer.
var nBytes = (nBits + 7) / 8;
var nExcessBits = nBytes * 8 - nBits;
var bytes = new byte[nBytes];
random.NextBytes(bytes);

// ToInt64 requires an array of exactly eight bytes.
// We can use IsLittleEndian to check which side we
// need to pad on to get there.
var padded = new byte[8];
bytes.CopyTo(padded,
// ToInt64 requires an array of exactly eight bytes.
// We can use IsLittleEndian to check which side we
// need to pad on to get there.
System.BitConverter.IsLittleEndian
? 0
: 8 - nBytes
);
return System.BitConverter.ToInt64(padded) >> nExcessBits;
};

var nBits = (int) (System.Math.Log(upperExclusive, 2) + 1);
var sample = SampleNBits(nBits);
while (sample >= upperExclusive)
{
sample = SampleNBits(nBits);
}
return sample;
}

internal static long NextLong(this System.Random random, long lower, long upper)
{
var delta = upper - lower;
return lower + random.NextLongBelow(delta + 1);
}

}
}
64 changes: 63 additions & 1 deletion src/Simulation/Common/SimulatorBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,13 @@ public abstract class SimulatorBase : AbstractFactory<AbstractCallable>, IOperat
public event Action<string>? OnLog = null;
public event Action<Exception, IEnumerable<StackFrame>>? OnException = null;


protected readonly int randomSeed;
protected readonly Lazy<System.Random> randomGenerator;
public int Seed => randomSeed;
protected System.Random RandomGenerator => randomGenerator.Value;



/// <summary>
/// An event fired whenever a simulator has additional diagnostic data
Expand All @@ -55,8 +62,12 @@ public abstract class SimulatorBase : AbstractFactory<AbstractCallable>, IOperat
/// </remarks>
public StackFrame[]? CallStack { get; private set; }

public SimulatorBase(IQubitManager? qubitManager = null)
public SimulatorBase(IQubitManager? qubitManager = null, int? seed = null)
{
this.randomSeed = seed ?? Guid.NewGuid().GetHashCode();
this.randomGenerator = new Lazy<System.Random>(
() => new System.Random(Seed)
);
this.QubitManager = qubitManager;

this.InitBuiltinOperations(this.GetType());
Expand Down Expand Up @@ -170,6 +181,7 @@ public virtual Task<O> Run<T, I, O>(I args) where T : AbstractCallable, ICallabl
public void EnableLogToConsole()
{
OnLog += Console.WriteLine;
OnDisplayableDiagnostic += Console.WriteLine;
}


Expand All @@ -179,6 +191,7 @@ public void EnableLogToConsole()
public void DisableLogToConsole()
{
OnLog -= Console.WriteLine;
OnDisplayableDiagnostic -= Console.WriteLine;
}

/// <summary>
Expand Down Expand Up @@ -420,6 +433,55 @@ public GetQubitsAvailableToBorrow(SimulatorBase m) : base(m)
sim.QubitManager.GetFreeQubitsCount();
}

/// <summary>
/// Implements the DrawRandomInt operation from the
/// Microsoft.Quantum.Random namespace.
/// </summary>
public class DrawRandomInt : Random.DrawRandomInt
{
private SimulatorBase sim;

public DrawRandomInt(SimulatorBase m) : base(m)
{
sim = m;
}

public override Func<(long, long), long> Body => arg =>
{
var (min, max) = arg;
if (max <= min)
{
throw new ExecutionFailException($"Max must be greater than min, but {max} <= {min}.");
}
return sim.RandomGenerator.NextLong(min, max);
};
}

/// <summary>
/// Implements the DrawRandomInt operation from the
/// Microsoft.Quantum.Random namespace.
/// </summary>
public class DrawRandomDouble : Random.DrawRandomDouble
{
private SimulatorBase sim;

public DrawRandomDouble(SimulatorBase m) : base(m)
{
sim = m;
}

public override Func<(double, double), double> Body => arg =>
{
var (min, max) = arg;
if (max <= min)
{
throw new ExecutionFailException($"Max must be greater than min, but {max} <= {min}.");
}
var delta = max - min;
return min + delta * sim.RandomGenerator.NextDouble();
};
}

public virtual void StartOperation(ICallable operation, IApplyData inputValue)
{
OnOperationStart?.Invoke(operation, inputValue);
Expand Down
15 changes: 9 additions & 6 deletions src/Simulation/Core/TypeExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -165,12 +165,6 @@ public static Type[] GetTupleFieldTypes(this Type arg)
return op.Name;
}

// If object is an IApplyData, recursively extract arguments
if (o is IApplyData data)
{
return data.Value?.GetNonQubitArgumentsAsString();
}

// If object is a string, enclose it in quotations
if (o is string s)
{
Expand All @@ -197,6 +191,15 @@ public static Type[] GetTupleFieldTypes(this Type arg)
return (items.Any()) ? $"({string.Join(", ", items)})" : null;
}

// If object is an IApplyData, recursively extract arguments
if (o is IApplyData data)
{
if (data.Value != data)
{
return data.Value?.GetNonQubitArgumentsAsString();
}
}

// Otherwise, return argument as a string
return (o != null) ? o.ToString() : null;
}
Expand Down
48 changes: 24 additions & 24 deletions src/Simulation/CsharpGeneration.Tests/SimulationCodeTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -878,27 +878,27 @@ namespace N1
|> testOne genU2

[
template "Allocate" "Allocate" "Microsoft.Quantum.Intrinsic.Allocate"
template "MicrosoftQuantumIntrinsicH" "IUnitary<Qubit>" "Microsoft.Quantum.Intrinsic.H"
template "Allocate" "Allocate" "global::Microsoft.Quantum.Intrinsic.Allocate"
template "MicrosoftQuantumIntrinsicH" "IUnitary<Qubit>" "global::Microsoft.Quantum.Intrinsic.H"
template "H" "ICallable<Qubit, QVoid>" "H"
template "Release" "Release" "Microsoft.Quantum.Intrinsic.Release"
template "MicrosoftQuantumOverridesemptyFunction" "ICallable<QVoid, QVoid>" "Microsoft.Quantum.Overrides.emptyFunction"
template "Release" "Release" "global::Microsoft.Quantum.Intrinsic.Release"
template "MicrosoftQuantumOverridesemptyFunction" "ICallable<QVoid, QVoid>" "global::Microsoft.Quantum.Overrides.emptyFunction"
template "emptyFunction" "ICallable<QVoid, QVoid>" "emptyFunction"
]
|> testOne duplicatedDefinitionsCaller

[
template "Allocate" "Allocate" "Microsoft.Quantum.Intrinsic.Allocate"
template "CNOT" "IAdjointable<(Qubit, Qubit)>" "Microsoft.Quantum.Intrinsic.CNOT"
template "MicrosoftQuantumTestingHold" "ICallable" "Microsoft.Quantum.Testing.Hold<>"
template "Release" "Release" "Microsoft.Quantum.Intrinsic.Release"
template "Allocate" "Allocate" "global::Microsoft.Quantum.Intrinsic.Allocate"
template "CNOT" "IAdjointable<(Qubit, Qubit)>" "global::Microsoft.Quantum.Intrinsic.CNOT"
template "MicrosoftQuantumTestingHold" "ICallable" "global::Microsoft.Quantum.Testing.Hold<>"
template "Release" "Release" "global::Microsoft.Quantum.Intrinsic.Release"
template "ResultToString" "ICallable<Result,String>" "ResultToString"
template "X" "IUnitary<Qubit>" "Microsoft.Quantum.Intrinsic.X"
template "X" "IUnitary<Qubit>" "global::Microsoft.Quantum.Intrinsic.X"
template "genIter" "IUnitary" "genIter<>"
template "genMapper" "ICallable" "genMapper<,>"
template "genU1" "IUnitary" "genU1<>"
template "MicrosoftQuantumTestingnoOpGeneric" "IUnitary" "Microsoft.Quantum.Testing.noOpGeneric<>"
template "MicrosoftQuantumTestingnoOpResult" "IUnitary<Result>" "Microsoft.Quantum.Testing.noOpResult"
template "MicrosoftQuantumTestingnoOpGeneric" "IUnitary" "global::Microsoft.Quantum.Testing.noOpGeneric<>"
template "MicrosoftQuantumTestingnoOpResult" "IUnitary<Result>" "global::Microsoft.Quantum.Testing.noOpResult"
]
|> testOne usesGenerics

Expand All @@ -908,7 +908,7 @@ namespace N1
|> testOne callsGenericWithMultipleTypeParams

[
template "Z" "IUnitary<Qubit>" "Microsoft.Quantum.Intrinsic.Z"
template "Z" "IUnitary<Qubit>" "global::Microsoft.Quantum.Intrinsic.Z"
"this.self = this;"
]
|> testOne selfInvokingOperation
Expand All @@ -930,17 +930,17 @@ namespace N1

let template = sprintf "typeof(%s)"
[
template "Microsoft.Quantum.Intrinsic.Allocate"
template "Microsoft.Quantum.Intrinsic.CNOT"
template "Microsoft.Quantum.Testing.Hold<>"
template "Microsoft.Quantum.Intrinsic.Release"
template "global::Microsoft.Quantum.Intrinsic.Allocate"
template "global::Microsoft.Quantum.Intrinsic.CNOT"
template "global::Microsoft.Quantum.Testing.Hold<>"
template "global::Microsoft.Quantum.Intrinsic.Release"
template "ResultToString"
template "Microsoft.Quantum.Intrinsic.X"
template "global::Microsoft.Quantum.Intrinsic.X"
template "genIter<>"
template "genMapper<,>"
template "genU1<>"
template "Microsoft.Quantum.Testing.noOpGeneric<>"
template "Microsoft.Quantum.Testing.noOpResult"
template "global::Microsoft.Quantum.Testing.noOpGeneric<>"
template "global::Microsoft.Quantum.Testing.noOpResult"
]
|> List.sort
|> testOne usesGenerics
Expand All @@ -961,7 +961,7 @@ namespace N1
|> testOne genRecursion

[
template "Microsoft.Quantum.Intrinsic.Z"
template "global::Microsoft.Quantum.Intrinsic.Z"
template "selfInvokingOperation"
]
|> testOne selfInvokingOperation
Expand Down Expand Up @@ -2465,7 +2465,7 @@ namespace N1

public override void Init()
{
this.X = this.Factory.Get<IUnitary<Qubit>>(typeof(Microsoft.Quantum.Intrinsic.X));
this.X = this.Factory.Get<IUnitary<Qubit>>(typeof(global::Microsoft.Quantum.Intrinsic.X));
}

public override IApplyData __dataIn(Qubit data) => data;
Expand Down Expand Up @@ -3563,9 +3563,9 @@ namespace Microsoft.Quantum.Tests.LineNumbers
;
public override void Init()
{
this.Allocate = this.Factory.Get<Allocate>(typeof(Microsoft.Quantum.Intrinsic.Allocate));
this.Release = this.Factory.Get<Release>(typeof(Microsoft.Quantum.Intrinsic.Release));
this.X = this.Factory.Get<IUnitary<Qubit>>(typeof(Microsoft.Quantum.Intrinsic.X));
this.Allocate = this.Factory.Get<Allocate>(typeof(global::Microsoft.Quantum.Intrinsic.Allocate));
this.Release = this.Factory.Get<Release>(typeof(global::Microsoft.Quantum.Intrinsic.Release));
this.X = this.Factory.Get<IUnitary<Qubit>>(typeof(global::Microsoft.Quantum.Intrinsic.X));
}

public override IApplyData __dataIn(Int64 data) => new QTuple<Int64>(data);
Expand Down
5 changes: 5 additions & 0 deletions src/Simulation/CsharpGeneration/Context.fs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,11 @@ type CodegenContext = {
| true, name -> name
| false, _ -> null

member public this.ExposeReferencesViaTestNames =
match this.assemblyConstants.TryGetValue AssemblyConstants.ExposeReferencesViaTestNames with
| true, propVal -> propVal = "true"
| false, _ -> false

member internal this.GenerateCodeForSource (fileName : NonNullable<string>) =
let targetsQuantumProcessor =
match this.assemblyConstants.TryGetValue AssemblyConstants.ProcessorArchitecture with
Expand Down
2 changes: 1 addition & 1 deletion src/Simulation/CsharpGeneration/EntryPoint.fs
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ let private createArgument context entryPoint =

/// A tuple of the callable's name, argument type name, and return type name.
let private callableTypeNames context (callable : QsCallable) =
let callableName = sprintf "%s.%s" callable.FullName.Namespace.Value callable.FullName.Name.Value
let callableName = sprintf "global::%s.%s" callable.FullName.Namespace.Value callable.FullName.Name.Value
let argTypeName = SimulationCode.roslynTypeName context callable.Signature.ArgumentType
let returnTypeName = SimulationCode.roslynTypeName context callable.Signature.ReturnType
callableName, argTypeName, returnTypeName
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

<ItemGroup>
<PackageReference Update="FSharp.Core" Version="4.7.0" />
<PackageReference Include="Microsoft.Quantum.Compiler" Version="0.12.20081703-beta" />
<PackageReference Include="Microsoft.Quantum.Compiler" Version="0.12.2008.2604-alpha" />
</ItemGroup>

<ItemGroup>
Expand Down
Loading