void CCNOTGateCountExample() { var config = new QCTraceSimulatorConfiguration(); config.UsePrimitiveOperationsCounter = true; QCTraceSimulator sim = new QCTraceSimulator(config); QVoid res; res = CCNOTDriver.Run(sim).Result; res = CCNOTDriver.Run(sim).Result; double tCount = sim.GetMetric <Intrinsic.CCNOT, CCNOTDriver>(PrimitiveOperationsGroupsNames.T); double tCountAll = sim.GetMetric <CCNOTDriver>(PrimitiveOperationsGroupsNames.T); double cxCount = sim.GetMetric <Intrinsic.CCNOT, CCNOTDriver>(PrimitiveOperationsGroupsNames.CNOT); string csvSummary = sim.ToCSV()[MetricsCountersNames.primitiveOperationsCounter]; // above code is an example used in the documentation Assert.Equal(7.0, sim.GetMetricStatistic <Intrinsic.CCNOT, CCNOTDriver>(PrimitiveOperationsGroupsNames.T, MomentsStatistic.Statistics.Average)); Assert.Equal(7.0, tCount); Assert.Equal(8.0, sim.GetMetricStatistic <CCNOTDriver>(PrimitiveOperationsGroupsNames.T, MomentsStatistic.Statistics.Average)); Assert.Equal(0.0, sim.GetMetricStatistic <CCNOTDriver>(PrimitiveOperationsGroupsNames.T, MomentsStatistic.Statistics.Variance)); Assert.Equal(8.0, tCountAll); Assert.Equal(10.0, cxCount); Debug.WriteLine(csvSummary); output.WriteLine(csvSummary); }
void TCountTest() { var config = new QCTraceSimulatorConfiguration(); config.UsePrimitiveOperationsCounter = true; config.CallStackDepthLimit = 2; QCTraceSimulator sim = new QCTraceSimulator(config); var res = TCountOneGatesTest.Run(sim).Result; var res2 = TCountZeroGatesTest.Run(sim).Result; var tcount = PrimitiveOperationsGroupsNames.T; string csvSummary = sim.ToCSV()[MetricsCountersNames.primitiveOperationsCounter]; output.WriteLine(csvSummary); Assert.Equal(Double.NaN, sim.GetMetricStatistic <Intrinsic.T, TCountOneGatesTest>( PrimitiveOperationsGroupsNames.T, MomentsStatistic.Statistics.Variance)); Assert.Equal(1, sim.GetMetric <Intrinsic.T, TCountOneGatesTest>(tcount, functor: OperationFunctor.Adjoint)); Assert.Equal(1, sim.GetMetric <Intrinsic.T, TCountOneGatesTest>(tcount)); Assert.Equal(1, sim.GetMetric <Intrinsic.RFrac, TCountOneGatesTest>(tcount)); Assert.Equal(1, sim.GetMetric <Intrinsic.ExpFrac, TCountOneGatesTest>(tcount)); Assert.Equal(1, sim.GetMetric <Intrinsic.R1Frac, TCountOneGatesTest>(tcount)); Assert.Equal(0, sim.GetMetric <Intrinsic.S, TCountZeroGatesTest>(tcount, functor: OperationFunctor.Adjoint)); Assert.Equal(0, sim.GetMetric <Intrinsic.S, TCountZeroGatesTest>(tcount)); Assert.Equal(0, sim.GetMetric <Intrinsic.RFrac, TCountZeroGatesTest>(tcount)); Assert.Equal(0, sim.GetMetric <Intrinsic.ExpFrac, TCountZeroGatesTest>(tcount)); Assert.Equal(0, sim.GetMetric <Intrinsic.R1Frac, TCountZeroGatesTest>(tcount)); }
public void RunTest(Action <QCTraceSimulator> test) { // Set gate times (AKA depth) to match expected physical implementation. Defaults to T = 1.0, all else 0.0 // More info: https://docs.microsoft.com/en-us/quantum/quantum-computer-trace-simulator-depth-counter?view=qsharp-preview var gateTimes = new Dictionary <PrimitiveOperationsGroups, double> { [PrimitiveOperationsGroups.Measure] = 2.0, [PrimitiveOperationsGroups.T] = 1.0, [PrimitiveOperationsGroups.R] = 0.0, [PrimitiveOperationsGroups.QubitClifford] = 0.0, [PrimitiveOperationsGroups.CNOT] = 0.0, }; // Set config for trace simulator // More info: https://docs.microsoft.com/en-us/quantum/quantum-computer-trace-simulator-1?view=qsharp-preview var config = new QCTraceSimulatorConfiguration { usePrimitiveOperationsCounter = true, // Counts the number of primitive executions used by every operation invoked in a quantum program useWidthCounter = true, // Counts the number of qubits allocated and borrowed by each operation useDepthCounter = true, // Gathers counts of the depth of every operation in the program (depth represents the number of time steps required to complete the program) gateTimes = gateTimes, // Set custom gate times for depth counter useDistinctInputsChecker = true, // Prevents bugs e.g. using the same qubit as control and target in a CNOT gate useInvalidatedQubitsUseChecker = true, // Detects e.g. usage of the qubits of a mutable Qubit[] after the qubits have been released throwOnUnconstraintMeasurement = true // Will fail if there is at least one measurement not annotated using AssertProb or ForceMeasure }; var sim = new QCTraceSimulator(config); sim.OnLog += (msg) => { output.WriteLine(msg); }; sim.OnLog += (msg) => { Debug.WriteLine(msg); }; test(sim); }
public void TracerCoreConstructor() { QCTraceSimulatorConfiguration tracerCoreConfiguration = new QCTraceSimulatorConfiguration(); tracerCoreConfiguration.UsePrimitiveOperationsCounter = true; QCTraceSimulator tracerCore = new QCTraceSimulator(tracerCoreConfiguration); }
void MultiControilledXWidthExample() { var config = new QCTraceSimulatorConfiguration(); config.UseWidthCounter = true; config.CallStackDepthLimit = 2; var sim = new QCTraceSimulator(config); int totalNumberOfQubits = 5; var res = MultiControlledXDriver.Run(sim, totalNumberOfQubits).Result; double allocatedQubits = sim.GetMetric <Intrinsic.X, MultiControlledXDriver>( MetricsNames.WidthCounter.ExtraWidth, functor: OperationFunctor.Controlled); double inputWidth = sim.GetMetric <Intrinsic.X, MultiControlledXDriver>( MetricsNames.WidthCounter.InputWidth, functor: OperationFunctor.Controlled); string csvSummary = sim.ToCSV()[MetricsCountersNames.widthCounter]; // above code is an example used in the documentation Assert.Equal(totalNumberOfQubits, inputWidth); Assert.Equal(totalNumberOfQubits - 3, allocatedQubits); Debug.WriteLine(csvSummary); output.WriteLine(csvSummary); }
/// # Summary /// Returns a trace simulator object that is configured /// to measure depth, width, and primitive operation count. /// If `full_depth` is true, then it counts every gate as depth 1; /// otherwise it only counts T gates private static QCTraceSimulator GetTraceSimulator(bool full_depth) { var config = new QCTraceSimulatorConfiguration(); config.UseDepthCounter = true; config.UseWidthCounter = true; config.UsePrimitiveOperationsCounter = true; if (DriverParameters.MinimizeDepthCostMetric) { config.OptimizeDepth = true; } else if (DriverParameters.MinimizeTCostMetric) { // This is the more sensible choice until // the depth optimization problem is fixed config.OptimizeDepth = false; } else { config.OptimizeDepth = false; } if (full_depth) { config.TraceGateTimes[PrimitiveOperationsGroups.CNOT] = 1; config.TraceGateTimes[PrimitiveOperationsGroups.Measure] = 1; // count all one and 2 qubit measurements as depth 1 config.TraceGateTimes[PrimitiveOperationsGroups.QubitClifford] = 1; // qubit Clifford depth 1 } return(new QCTraceSimulator(config)); }
static void Main(string[] args) { var rng = new Random(5); var collectTofCount = true; var collectQubitCount = true; var useSchoolbook = false; var cases = new[] { 32, 64, 96, 128, 128 + 32, 256, 256 + 32, 512, 512 + 32, 1024, 1024 + 32, 2048, 2048 + 32, 4096, 4096 + 32 }; foreach (var i in cases) { var a = rng.NextBigInt(i); var b = rng.NextBigInt(i); var tof_sim = new ToffoliSimulator(); var config = new QCTraceSimulatorConfiguration(); config.usePrimitiveOperationsCounter = collectTofCount; config.useWidthCounter = collectQubitCount; var trace_sim = new QCTraceSimulator(config); BigInteger result = 0, result2 = 0; if (useSchoolbook) { result = RunSchoolbookMultiplicationCircuit.Run(tof_sim, a, b).Result; result2 = RunSchoolbookMultiplicationCircuit.Run(trace_sim, a, b).Result; } else { result = RunKaratsubaMultiplicationCircuit.Run(tof_sim, a, b).Result; result2 = RunKaratsubaMultiplicationCircuit.Run(trace_sim, a, b).Result; } if (result != a * b || result2 != result) { throw new ArithmeticException($"Wrong result. {a}*{b} != {result}, {result==result2}."); } double tofCount, qubitCount; if (useSchoolbook) { tofCount = collectTofCount ? trace_sim.GetMetric <RunSchoolbookMultiplicationCircuit>(PrimitiveOperationsGroupsNames.T) / 7 : -1; qubitCount = collectQubitCount ? trace_sim.GetMetric <RunSchoolbookMultiplicationCircuit>(MetricsNames.WidthCounter.ExtraWidth) : -1; } else { tofCount = collectTofCount ? trace_sim.GetMetric <RunKaratsubaMultiplicationCircuit>(PrimitiveOperationsGroupsNames.T) / 7 : -1; qubitCount = collectQubitCount ? trace_sim.GetMetric <RunKaratsubaMultiplicationCircuit>(MetricsNames.WidthCounter.ExtraWidth) : -1; } Console.WriteLine($"{i},{tofCount},{qubitCount}"); } }
QCTraceSimulator GetTraceSimForMetrics() { QCTraceSimulatorConfiguration traceSimCfg = new QCTraceSimulatorConfiguration(); traceSimCfg.UsePrimitiveOperationsCounter = true; traceSimCfg.UseDepthCounter = true; traceSimCfg.UseWidthCounter = true; traceSimCfg.TraceGateTimes[PrimitiveOperationsGroups.CNOT] = 1; return(new QCTraceSimulator(traceSimCfg)); }
private static QCTraceSimulator CreateAndConfigureTraceSim() { // Create and configure Trace Simulator var config = new QCTraceSimulatorConfiguration() { usePrimitiveOperationsCounter = true, throwOnUnconstraintMeasurement = false }; return(new QCTraceSimulator(config)); }
void TDepthTest() { var config = new QCTraceSimulatorConfiguration(); config.UseDepthCounter = true; config.CallStackDepthLimit = 1; QCTraceSimulator sim = new QCTraceSimulator(config); var res = TDepthOne.Run(sim).Result; string csvSummary = sim.ToCSV()[MetricsCountersNames.depthCounter]; Assert.Equal(1, sim.GetMetric <TDepthOne>(MetricsNames.DepthCounter.Depth)); }
static void Main(string[] args) { var config = new QCTraceSimulatorConfiguration(); config.throwOnUnconstraintMeasurement = false; config.useInvalidatedQubitsUseChecker = true; QCTraceSimulator qsim = new QCTraceSimulator(config); var res = CheckForReleasedQubit.Run(qsim).Result; }
static void Main(string[] args) { var config = new QCTraceSimulatorConfiguration(); config.throwOnUnconstraintMeasurement = false; config.useDistinctInputsChecker = true; QCTraceSimulator qsim = new QCTraceSimulator(config); var res = CheckDistinctInputs.Run(qsim).Result; }
/// # Summary /// Returns a trace simulator object that is configured /// to measure depth, width, and primitive operation count. /// If `full_depth` is true, then it counts every gate as depth 1; /// otherwise it only counts T gates private static QCTraceSimulator GetTraceSimulator(bool full_depth) { var config = new QCTraceSimulatorConfiguration(); config.UseDepthCounter = true; config.UseWidthCounter = true; config.UsePrimitiveOperationsCounter = true; if (full_depth) { config.TraceGateTimes[PrimitiveOperationsGroups.CNOT] = 1; config.TraceGateTimes[PrimitiveOperationsGroups.Measure] = 1; // count all one and 2 qubit measurements as depth 1 config.TraceGateTimes[PrimitiveOperationsGroups.QubitClifford] = 1; // qubit Clifford depth 1 } return(new QCTraceSimulator(config)); }
void CatStateTestCore <TCatState>(int powerOfTwo) where TCatState : AbstractCallable, ICallable <long, QVoid> { Debug.Assert(powerOfTwo > 0); double CXTime = 5; double HTime = 1; QCTraceSimulatorConfiguration traceSimCfg = new QCTraceSimulatorConfiguration(); traceSimCfg.UsePrimitiveOperationsCounter = true; traceSimCfg.UseDepthCounter = true; traceSimCfg.UseWidthCounter = true; traceSimCfg.TraceGateTimes[PrimitiveOperationsGroups.CNOT] = CXTime; traceSimCfg.TraceGateTimes[PrimitiveOperationsGroups.QubitClifford] = HTime; QCTraceSimulator traceSim = new QCTraceSimulator(traceSimCfg); output.WriteLine(string.Empty); output.WriteLine($"Starting cat state preparation on {1u << powerOfTwo} qubits"); var stopwatch = new Stopwatch(); stopwatch.Start(); traceSim.Run <TCatState, long, QVoid>(powerOfTwo).Wait(); stopwatch.Stop(); double cxCount = traceSim.GetMetric <TCatState>(PrimitiveOperationsGroupsNames.CNOT); Assert.Equal((1 << powerOfTwo) - 1, (long)cxCount); double depth = traceSim.GetMetric <TCatState>(DepthCounter.Metrics.Depth); Assert.Equal(HTime + powerOfTwo * CXTime, depth); void AssertEqualMetric(double value, string metric) { Assert.Equal(value, traceSim.GetMetric <TCatState>(metric)); } AssertEqualMetric(1u << powerOfTwo, WidthCounter.Metrics.ExtraWidth); AssertEqualMetric(0, WidthCounter.Metrics.BorrowedWith); AssertEqualMetric(0, WidthCounter.Metrics.InputWidth); AssertEqualMetric(0, WidthCounter.Metrics.ReturnWidth); output.WriteLine($"Calculation of metrics took: {stopwatch.ElapsedMilliseconds} ms"); output.WriteLine($"The depth is: {depth} given depth of CNOT was {CXTime} and depth of H was {HTime}"); output.WriteLine($"Number of CNOTs used is {cxCount}"); }
public QCTraceSimulatorImpl(QCTraceSimulatorConfiguration config) { configuration = Utils.DeepClone(config); Utils.FillDictionaryForEnumNames <PrimitiveOperationsGroups, int>(primitiveOperationsIdToNames); gateTimes = new double[primitiveOperationsIdToNames.Keys.Count]; for (int i = 0; i < primitiveOperationsIdToNames.Keys.Count; ++i) { if (!config.TraceGateTimes.ContainsKey((PrimitiveOperationsGroups)i)) { throw new Exception($"Gate time for {primitiveOperationsIdToNames[i]} must be specified."); } gateTimes[i] = config.TraceGateTimes[(PrimitiveOperationsGroups)i]; } tCoreConfig = new QCTraceSimulatorCoreConfiguration { ThrowOnUnconstrainedMeasurement = configuration.ThrowOnUnconstrainedMeasurement }; tCoreConfig.CallStackDepthLimit = config.CallStackDepthLimit; InitializeQCTracerCoreListeners(tCoreConfig.Listeners); metricNameToListener = new Dictionary <string, ICallGraphStatistics>(); foreach (IQCTraceSimulatorListener l in tCoreConfig.Listeners) { ICallGraphStatistics li = l as ICallGraphStatistics; if (li != null) { string[] variableNames = li.Results.GetVariablesNamesCopy(); foreach (string metric in variableNames) { metricNameToListener.Add(metric, li); } } } tracingCore = new QCTraceSimulatorCore(tCoreConfig); OnOperationStart += tracingCore.OnOperationStart; OnOperationEnd += tracingCore.OnOperationEnd; RegisterPrimitiveOperationsGivenAsCircuits(); }
static void Main(string[] args) { var config = new QCTraceSimulatorConfiguration(); config.useDepthCounter = true; QCTraceSimulator qsim = new QCTraceSimulator(config); var res = ExecuteCCNOTGate.Run(qsim).Result; double tDepthAll = qsim.GetMetric <ExecuteCCNOTGate>(DepthCounter.Metrics.Depth); System.Console.WriteLine(tDepthAll); }
static QCTraceSimulator getTraceSimulator(bool full_depth) { var config = new QCTraceSimulatorConfiguration(); config.OptimizeDepth = true; config.UseDepthCounter = true; config.UseWidthCounter = true; config.UseDistinctInputsChecker = true; config.UseInvalidatedQubitsUseChecker = true; config.UsePrimitiveOperationsCounter = true; config.ThrowOnUnconstrainedMeasurement = false; if (full_depth) { config.TraceGateTimes[PrimitiveOperationsGroups.CNOT] = 1; config.TraceGateTimes[PrimitiveOperationsGroups.Measure] = 1; // count all one and 2 qubit measurements as depth 1 config.TraceGateTimes[PrimitiveOperationsGroups.QubitClifford] = 1; // qubit Clifford depth 1 } return(new QCTraceSimulator(config)); }
/// <summary> /// Returns an instance of QCTraceSimulator configured to collect /// circuit metrics /// </summary> public static QCTraceSimulator GetSimulatorForMetricsCalculation() { // Setup QCTraceSimulator to collect all available metrics var config = new QCTraceSimulatorConfiguration { useDepthCounter = true, usePrimitiveOperationsCounter = true, useWidthCounter = true }; // Set up gate times to compute T depth config.gateTimes[PrimitiveOperationsGroups.CNOT] = 0; config.gateTimes[PrimitiveOperationsGroups.QubitClifford] = 0; config.gateTimes[PrimitiveOperationsGroups.Measure] = 0; config.gateTimes[PrimitiveOperationsGroups.R] = 0; config.gateTimes[PrimitiveOperationsGroups.T] = 1; // Create an instance of Quantum Computer Trace Simulator return(new QCTraceSimulator(config)); }
static void Main(string[] args) { var config = new QCTraceSimulatorConfiguration(); config.throwOnUnconstraintMeasurement = false; config.usePrimitiveOperationsCounter = true; QCTraceSimulator qsim = new QCTraceSimulator(config); var res = PrimitiveOperationsChecker.Run(qsim).Result; double tCountAll = qsim.GetMetric <PrimitiveOperationsChecker>(PrimitiveOperationsGroupsNames.T); System.Console.WriteLine(tCountAll); }
static void Main(string[] args) { var config = new QCTraceSimulatorConfiguration(); config.throwOnUnconstraintMeasurement = false; config.useWidthCounter = true; QCTraceSimulator qsim = new QCTraceSimulator(config); int totalQubits = 5; var res = GetWidthCounter.Run(qsim, totalQubits).Result; string csvSummary = qsim.ToCSV()[MetricsCountersNames.widthCounter]; System.Console.WriteLine(csvSummary); }
void CCNOTDepthCountExample() { var config = new QCTraceSimulatorConfiguration(); config.UseDepthCounter = true; config.CallStackDepthLimit = 2; QCTraceSimulator sim = new QCTraceSimulator(config); var res = CCNOTDriver.Run(sim).Result; double tDepth = sim.GetMetric <Intrinsic.CCNOT, CCNOTDriver>(MetricsNames.DepthCounter.Depth); double tDepthAll = sim.GetMetric <CCNOTDriver>(MetricsNames.DepthCounter.Depth); string csvSummary = sim.ToCSV()[MetricsCountersNames.depthCounter]; // above code is an example used in the documentation Assert.Equal(5.0, tDepth); Assert.Equal(6.0, tDepthAll); Debug.WriteLine(csvSummary); output.WriteLine(csvSummary); }
static void Main(string[] args) { // This is the name of the file we want to load if (args.Length < 6) { Console.WriteLine("Too few parameters provided!"); Console.WriteLine("Must provide the path to the YAML, input state label, precision, step size, trotter order, and sample size"); } else { string YAMLPath = args[0]; string inputState = $"|{args[1]}>"; int nBitsPrecision = Int16.Parse(args[2]); float trotterStepSize = float.Parse(args[3]); int trotterOrder = Int16.Parse(args[4]); var numberOfSamples = Int16.Parse(args[5]); Console.WriteLine($"Extracting the YAML from {YAMLPath}"); Console.WriteLine($"Input state: {inputState}"); Console.WriteLine($"Precision: {nBitsPrecision}"); Console.WriteLine($"Trotter step size: {trotterStepSize}"); Console.WriteLine($"Trotter order: {trotterOrder}"); Console.WriteLine($"Number of samples: {numberOfSamples}"); // This deserializes a Broombridge file, given its filename. var broombridge = Deserializers.DeserializeBroombridge(YAMLPath); // Note that the deserializer returns a list of `ProblemDescription` instances // as the file might describe multiple Hamiltonians. In this example, there is // only one Hamiltonian. So we use `.Single()`, which selects the only element of the list. var problem = broombridge.ProblemDescriptions.Single(); // This is a data structure representing the Jordan-Wigner encoding // of the Hamiltonian that we may pass to a Q# algorithm. // If no state is specified, the Hartree-Fock state is used by default. Console.WriteLine("Preparing Q# data format"); var qSharpData = problem.ToQSharpFormat(inputState); Console.WriteLine("----- Begin simulation -----"); using (var qsim = new QuantumSimulator(randomNumberGeneratorSeed: 42)) { // HelloQ.Run(qsim).Wait(); var runningSum = 0.0; for (int i = 0; i < numberOfSamples; i++) { var(phaseEst, energyEst) = GetEnergyByTrotterization.Run(qsim, qSharpData, nBitsPrecision, trotterStepSize, trotterOrder).Result; Console.WriteLine(energyEst); runningSum += energyEst; } Console.WriteLine("----- End simulation -----"); Console.WriteLine($"Average energy estimate: {runningSum / (float)numberOfSamples}"); } var config = new QCTraceSimulatorConfiguration(); config.usePrimitiveOperationsCounter = true; QCTraceSimulator estimator = new QCTraceSimulator(config); ApplyTrotterOracleOnce.Run(estimator, qSharpData, trotterStepSize, trotterOrder).Wait(); System.IO.Directory.CreateDirectory("_temp"); // var csvData = estimator.ToCSV(); // var csvStringData = String.Join(Environment.NewLine, csvData.Select(d => $"{d.Key};{d.Value};")); // System.IO.File.WriteAllText("./_temp/_costEstimateReference.csv", csvStringData); foreach (var collectedData in estimator.ToCSV()) { File.WriteAllText( Path.Combine("./_temp/", $"CCNOTCircuitsMetrics.{collectedData.Key}.csv"), collectedData.Value); } } }
static void Main(string[] args) { if (args.Length < 3) { Console.WriteLine("You did not provide the gatefile path, number of samples, and precision."); } else { // Extract important command line arguments string JSONPath = args[0]; int numberOfSamples = Int16.Parse(args[1]); var nBitsPrecision = Int64.Parse(args[2]); if (File.Exists(JSONPath)) { #region Extract Fermion Terms string raw_JSON = System.IO.File.ReadAllText(JSONPath); var output = JObject.Parse(raw_JSON); // get the constants specifically var constants = output["constants"]; // get important constants float trotterStepSize = (float)constants["trotterStep"]; double rescaleFactor = 1.0 / trotterStepSize; float energyOffset = (float)constants["energyOffset"]; int nSpinOrbitals = (int)constants["nSpinOrbitals"]; int trotterOrder = (int)constants["trotterOrder"]; #endregion #region Convert to Q# Format // var test = Auxiliary.ProduceLowLevelTerms(output); // Console.WriteLine(test); // var data = Auxiliary.ProduceCompleteHamiltonian(output); // var qSharpData = Auxiliary.CreateQSharpFormat(output); var data = Auxiliary.ProduceCompleteHamiltonian(output); #endregion #region Simulate Optimized Fermion Terms using (var qsim = new QuantumSimulator(randomNumberGeneratorSeed: 42)) { // keep track of the running total of the energy to produce the average energy amount var runningSum = 0.0; // iterate over the sample size for (int i = 0; i < numberOfSamples; i++) { var(phaseEst, energyEst) = EstimateEnergyLevel.Run(qsim, data, nBitsPrecision).Result; runningSum += energyEst; Console.WriteLine($"Predicted energy: {energyEst}"); } // Output to stdout Console.WriteLine($"Average predicted energy: {runningSum / (float)numberOfSamples}"); } #endregion #region Produce Cost Estimates var config = new QCTraceSimulatorConfiguration(); config.usePrimitiveOperationsCounter = true; QCTraceSimulator estimator = new QCTraceSimulator(config); ApplyTrotterOracleOnce.Run(estimator, data).Wait(); System.IO.Directory.CreateDirectory("_temp"); // System.IO.File.WriteAllLines("./_temp/_costEstimateOptimized.csv",estimator.ToCSV().Select(x => x.Key + " " + x.Value).ToArray()); foreach (var collectedData in estimator.ToCSV()) { File.WriteAllText( Path.Combine("./_temp/", $"CCNOTCircuitsMetrics.{collectedData.Key}.csv"), collectedData.Value); } #endregion } } }
static void Main(string[] args) { var rng = new Random(5); // Binary integers of the form 1XXX0000000... var cases = new List <int>(); for (var i = 8; i <= 2048; i <<= 1) { for (var j = 0; j < 8; j++) { cases.Add(i + (i >> 3) * j); } } // Header column. Console.WriteLine($"{String.Join(", ", cases)}"); var methods = new[] { "window", "legacy", "karatsuba" }; var columns = new List <String>(); columns.Add("n"); foreach (var method in methods) { columns.Add(method + " " + "toffolis"); columns.Add(method + " " + "qubits"); columns.Add(method + " " + "depth"); } Console.WriteLine(String.Join(", ", columns)); // Collect data. foreach (var n in cases) { var tofCounts = new double[methods.Length]; var qubitCounts = new double[methods.Length]; var depthCounts = new double[methods.Length]; var reps = Math.Max(1, Math.Min(10, 128 / n)); for (int r = 0; r < reps; r++) { for (int i = 0; i < methods.Length; i++) { var a = rng.NextBigInt(2 * n); var b = rng.NextBigInt(n); var c = rng.NextBigInt(n); var tof_sim = new ToffoliSimulator(); var tof_output = RunPlusEqualProductMethod.Run(tof_sim, a, b, c, methods[i]).Result; var config = new QCTraceSimulatorConfiguration(); config.usePrimitiveOperationsCounter = true; config.useWidthCounter = true; config.useDepthCounter = true; var trace_sim = new QCTraceSimulator(config); var trace_output = RunPlusEqualProductMethod.Run(trace_sim, a, b, c, methods[i]).Result; if (tof_output != a + b * c || trace_output != tof_output) { throw new ArithmeticException($"Wrong result using {methods[i]}. {a}+{b}*{c} == {a+b*c} != {tof_output} or {trace_output}."); } tofCounts[i] += trace_sim.GetMetric <RunPlusEqualProductMethod>(PrimitiveOperationsGroupsNames.T) / 7; qubitCounts[i] += trace_sim.GetMetric <RunPlusEqualProductMethod>(MetricsNames.WidthCounter.ExtraWidth); depthCounts[i] += trace_sim.GetMetric <RunPlusEqualProductMethod>(MetricsNames.DepthCounter.Depth); } } // Output row of results. var data = new List <double>(); data.Add(n); for (var i = 0; i < methods.Length; i++) { data.Add(tofCounts[i] / reps); data.Add(qubitCounts[i] / reps); data.Add(depthCounts[i] / reps); } Console.WriteLine(String.Join(", ", data)); } }
static void Main(string[] args) { #region Parameters of Operation // filename of the molecule to be emulated // var FILENAME = "h2_2_sto6g_1.0au.yaml"; var FILENAME = "h4_sto6g_0.000.yaml"; // var FILENAME = "h20_nwchem.yaml"; // use this state provided in the YAML. var STATE = "|G>"; // the margin of error to use when approximating the expected value var MOE = 0.1; // precision to iterate over with the state preparation gate // the number of trials is directly proportional to this constant's inverse // the gate will be applying a transform of the form (2 pi i \phi) where \phi // varies by the precision specified below var ANGULAR_PRECISION = 0.01; Console.WriteLine($"STATE: {STATE} | MOE: {MOE} | PRECISION: {ANGULAR_PRECISION}"); #endregion #region Creating the Hamiltonian and JW Terms // create the first hamiltonian from the YAML File var hamiltonian = FermionHamiltonian.LoadFromYAML($@"{FILENAME}").First(); // convert the hamiltonian into it's JW Encoding var JWEncoding = JordanWignerEncoding.Create(hamiltonian); var data = JWEncoding.QSharpData(STATE); // Console.WriteLine("----- Print Hamiltonian"); // Console.Write(hamiltonian); // Console.WriteLine("----- End Print Hamiltonian \n"); #endregion #region Hybrid Quantum/Classical accelerator // Feed created state and hamiltonian terms to VQE Console.WriteLine("----- Begin VQE Simulation"); //var N = 10; // number of qubits, calculate from data??? //var oneReal = (1.0, 0.0); //var inputCoeffs = new ComplexPolar[N]; //for (int i = 0; i < Length(inputCoeffs) - 1; i++) // { // inputCoeffs[i] = oneReal; // } ResourcesEstimator estimator = new ResourcesEstimator(); Simulate.Run(estimator, data, 1.0, MOE).Wait(); //Aux.Run(estimator).Wait(); var configCNOT = new QCTraceSimulatorConfiguration(); configCNOT.useDepthCounter = true; configCNOT.gateTimes[PrimitiveOperationsGroups.CNOT] = 1.0; configCNOT.gateTimes[PrimitiveOperationsGroups.Measure] = 0.0; configCNOT.gateTimes[PrimitiveOperationsGroups.QubitClifford] = 0.0; configCNOT.gateTimes[PrimitiveOperationsGroups.R] = 0.0; configCNOT.gateTimes[PrimitiveOperationsGroups.T] = 0.0; var traceSimCNOT = new QCTraceSimulator(configCNOT); Simulate.Run(traceSimCNOT, data, 1.0, MOE).Wait(); double cnotDepth = traceSimCNOT.GetMetric <Simulate>(DepthCounter.Metrics.Depth); var configT = new QCTraceSimulatorConfiguration(); configT.useDepthCounter = true; configT.gateTimes[PrimitiveOperationsGroups.CNOT] = 0.0; configT.gateTimes[PrimitiveOperationsGroups.Measure] = 0.0; configT.gateTimes[PrimitiveOperationsGroups.QubitClifford] = 0.0; configT.gateTimes[PrimitiveOperationsGroups.R] = 0.0; configT.gateTimes[PrimitiveOperationsGroups.T] = 1.0; var traceSimT = new QCTraceSimulator(configT); Simulate.Run(traceSimT, data, 1.0, MOE).Wait(); double tDepth = traceSimT.GetMetric <Simulate>(DepthCounter.Metrics.Depth); var configClifford = new QCTraceSimulatorConfiguration(); configClifford.useDepthCounter = true; configClifford.gateTimes[PrimitiveOperationsGroups.CNOT] = 0.0; configClifford.gateTimes[PrimitiveOperationsGroups.Measure] = 0.0; configClifford.gateTimes[PrimitiveOperationsGroups.QubitClifford] = 1.0; configClifford.gateTimes[PrimitiveOperationsGroups.R] = 0.0; configClifford.gateTimes[PrimitiveOperationsGroups.T] = 0.0; var traceSimClifford = new QCTraceSimulator(configClifford); Simulate.Run(traceSimClifford, data, 1.0, MOE).Wait(); double cliffordDepth = traceSimClifford.GetMetric <Simulate>(DepthCounter.Metrics.Depth); Console.WriteLine(estimator.ToTSV()); Console.WriteLine($"CNOT depth is {cnotDepth}"); Console.WriteLine($"T depth is {tDepth}"); Console.WriteLine($"Clifford depth is {cliffordDepth}"); #endregion #region Classical update scheme // Determine how to update the starting state using classical methods #endregion }
/// <summary> /// It initializes the ResourceEstimator with the given QCTraceSimulatorConfiguration. /// It is recommended to use <see cref="RecommendedConfig"/> to create a new config instance /// and tweak it, to make sure the data collection is correctly configured. /// </summary> public ResourcesEstimator(QCTraceSimulatorConfiguration config) : base(config) { }