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)); }
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); }
private static void SingleResourceTestNoCost <TypeQop>( RunParameterizedQop runner, ReaderWriterLock locker, int n, int m, bool isControlled, string filename, bool full_depth) { QCTraceSimulator estimator = GetTraceSimulator(full_depth); // construct simulator object // we must generate a new simulator in each round, to clear previous estimates var res = runner(estimator, n, isControlled, m).Result; // run test // Get results // Create string of a row of parameters string thisCircuitCosts = DisplayCSV.CSV(estimator.ToCSV(), typeof(TypeQop).FullName, false, string.Empty, false, string.Empty); // add the row to the string of the csv thisCircuitCosts += $"{n}, {m}"; try { locker.AcquireWriterLock(int.MaxValue); // absurd timeout value System.IO.File.AppendAllText(filename, thisCircuitCosts); } finally { locker.ReleaseWriterLock(); } }
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); }
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)); }
public static void ProcessSim <Qop>(QCTraceSimulator sim, string comment = "", bool full_depth = false, string suffix = "") { if (!full_depth) { DisplayCSV.CSV(sim.ToCSV(), typeof(Qop).FullName, false, comment, false, suffix); } else { // full depth only var depthEngine = new FileHelperAsyncEngine <DepthCounterCSV>(); using (depthEngine.BeginReadString(sim.ToCSV()[MetricsCountersNames.depthCounter])) { // The engine is IEnumerable foreach (DepthCounterCSV cust in depthEngine) { if (cust.Name == typeof(Qop).FullName) { Console.Write($"{cust.DepthAverage}"); } } } } }
public static void WriteResultsToFolder( this QCTraceSimulator sim, string outputFolder, string baseName ) { var gateStats = sim.ToCSV(); foreach (var x in gateStats) { System.IO.File.WriteAllLines( System.IO.Path.Join( outputFolder, $"{baseName}.{x.Key}.csv" ), new string[] { x.Value } ); } }
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); }
private static void SingleTwoArgResourceTest <TypeQop>( RunTwoArgQop runner, ReaderWriterLock locker, int n, int[] ms, bool isControlled, string filename, bool full_depth) { // Iterate through values of the second parameter foreach (int m in ms) { QCTraceSimulator estimator = GetTraceSimulator(full_depth); // construct simulator object // we must generate a new simulator in each round, to clear previous estimates var res = runner(estimator, n, m, isControlled).Result; // run test // Get results var roundDepth = estimator.GetMetric <TypeQop>(MetricsNames.DepthCounter.Depth); var roundTGates = estimator.GetMetric <TypeQop>(PrimitiveOperationsGroupsNames.T); // Create string of a row of parameters string thisCircuitCosts = DisplayCSV.CSV(estimator.ToCSV(), typeof(TypeQop).FullName, false, string.Empty, false, string.Empty); // add the row to the string of the csv thisCircuitCosts += $"{n}, {m}"; try { locker.AcquireWriterLock(int.MaxValue); // absurd timeout value System.IO.File.AppendAllText(filename, thisCircuitCosts); } finally { locker.ReleaseWriterLock(); } } }
public void ThreeCNOTs() { QCTraceSimulator sim = GetTraceSimForMetrics(); GetTest <ThreeCNOTsTest>(sim)(); void AssertEqualMetric(double value, string metric) { Assert.Equal(value, sim.GetMetric <ThreeCNOTsTest>(metric)); } AssertEqualMetric(3, DepthCounter.Metrics.Depth); AssertEqualMetric(3, PrimitiveOperationsGroupsNames.CNOT); AssertEqualMetric(3, WidthCounter.Metrics.ExtraWidth); AssertEqualMetric(0, DepthCounter.Metrics.StartTimeDifference); Dictionary <string, string> csvRes = sim.ToCSV(); foreach (KeyValuePair <string, string> kv in csvRes) { output.WriteLine($"Result of running {kv.Key} are:"); output.WriteLine(kv.Value); } }
public void CCNOTCircuitsMetricsTest() { // Get an instance of the appropriately configured QCTraceSimulator QCTraceSimulator sim = MetricCalculationUtils.GetSimulatorForMetricsCalculation(); // Run tests against trace simulator to collect metrics var result1 = CCNOTCircuitsTest.Run(sim).Result; // Let us check that number of T gates in all the circuits is as expected string Tcount = PrimitiveOperationsGroupsNames.T; // group of circuits with 7 T gates Assert.Equal(7, sim.GetMetric <TDepthOneCCNOT, CollectMetrics>(Tcount)); Assert.Equal(7, sim.GetMetric <CCNOT1, CollectMetrics>(Tcount)); Assert.Equal(7, sim.GetMetric <CCNOT2, CollectMetrics>(Tcount)); Assert.Equal(7, sim.GetMetric <CCNOT4, CollectMetrics>(Tcount)); // group of circuits with 4 T gates Assert.Equal(4, sim.GetMetric <CCNOT3, CollectMetrics>(Tcount)); Assert.Equal(4, sim.GetMetric <UpToPhaseCCNOT1, CollectMetrics>(Tcount)); Assert.Equal(4, sim.GetMetric <UpToPhaseCCNOT2, CollectMetrics>(Tcount)); // For UpToPhaseCCNOT3 the number of T gates in it is the number of T // gates used in CCNOT plus the number of T gates in Controlled-S double expectedTcount = sim.GetMetric <Intrinsic.S, UpToPhaseCCNOT3>( Tcount, functor: Simulation.Core.OperationFunctor.ControlledAdjoint) + sim.GetMetric <Intrinsic.CCNOT, UpToPhaseCCNOT3>(Tcount); Assert.Equal( expectedTcount, sim.GetMetric <UpToPhaseCCNOT3, CollectMetrics>(Tcount)); // The number of extra qubits used by the circuits string extraQubits = MetricsNames.WidthCounter.ExtraWidth; Assert.Equal(4, sim.GetMetric <TDepthOneCCNOT, CollectMetrics>(extraQubits)); Assert.Equal(0, sim.GetMetric <CCNOT1, CollectMetrics>(extraQubits)); Assert.Equal(0, sim.GetMetric <CCNOT2, CollectMetrics>(extraQubits)); Assert.Equal(0, sim.GetMetric <CCNOT4, CollectMetrics>(extraQubits)); Assert.Equal(0, sim.GetMetric <UpToPhaseCCNOT1, CollectMetrics>(extraQubits)); Assert.Equal(2, sim.GetMetric <CCNOT3, CollectMetrics>(extraQubits)); Assert.Equal(1, sim.GetMetric <UpToPhaseCCNOT2, CollectMetrics>(extraQubits)); // All of the CCNOT circuit take 3 qubits as an input string inputQubits = MetricsNames.WidthCounter.InputWidth; Assert.Equal(3, sim.GetMetric <TDepthOneCCNOT, CollectMetrics>(inputQubits)); Assert.Equal(3, sim.GetMetric <CCNOT1, CollectMetrics>(inputQubits)); Assert.Equal(3, sim.GetMetric <CCNOT2, CollectMetrics>(inputQubits)); Assert.Equal(3, sim.GetMetric <UpToPhaseCCNOT1, CollectMetrics>(inputQubits)); Assert.Equal(3, sim.GetMetric <CCNOT3, CollectMetrics>(inputQubits)); Assert.Equal(3, sim.GetMetric <UpToPhaseCCNOT2, CollectMetrics>(inputQubits)); // CCNOT3 uses one measurement Assert.Equal( 1, sim.GetMetric <CCNOT3, CollectMetrics>(PrimitiveOperationsGroupsNames.Measure)); // Finally, let us check T depth of various CCNOT circuits: string tDepth = MetricsNames.DepthCounter.Depth; Assert.Equal(1, sim.GetMetric <TDepthOneCCNOT, CollectMetrics>(tDepth)); Assert.Equal(1, sim.GetMetric <CCNOT3, CollectMetrics>(tDepth)); Assert.Equal(1, sim.GetMetric <UpToPhaseCCNOT2, CollectMetrics>(tDepth)); Assert.Equal(4, sim.GetMetric <CCNOT2, CollectMetrics>(tDepth)); Assert.Equal(5, sim.GetMetric <CCNOT4, CollectMetrics>(tDepth)); Assert.Equal(5, sim.GetMetric <CCNOT1, CollectMetrics>(tDepth)); // Finally we write all the collected statistics into CSV files string directory = Directory.GetCurrentDirectory(); output.WriteLine($"Writing all collected metrics result to" + $" {directory}"); foreach (var collectedData in sim.ToCSV()) { File.WriteAllText( Path.Combine(directory, "CCNOTCircuitsMetrics.{collectedData.Key}.csv"), collectedData.Value); } }
// This method computes the gate count of simulation a single configuration passed to it. internal static async Task <GateCountResults> RunGateCount(JordanWignerEncodingData qSharpData, HamiltonianSimulationConfig config) { // Creates and configures Trace simulator for accumulating gate counts. QCTraceSimulator sim = CreateAndConfigureTraceSim(); // Create stop-watch to measure the execution time Stopwatch stopWatch = new Stopwatch(); var gateCountResults = new GateCountResults(); #region Trace Simulator on Trotter step if (config.hamiltonianSimulationAlgorithm == HamiltonianSimulationConfig.HamiltonianSimulationAlgorithm.ProductFormula) { stopWatch.Reset(); stopWatch.Start(); var res = await RunTrotterStep.Run(sim, qSharpData); stopWatch.Stop(); gateCountResults = new GateCountResults { Method = "Trotter", ElapsedMilliseconds = stopWatch.ElapsedMilliseconds, RotationsCount = sim.GetMetric <RunTrotterStep>(PrimitiveOperationsGroupsNames.R), TCount = sim.GetMetric <RunTrotterStep>(PrimitiveOperationsGroupsNames.T), CNOTCount = sim.GetMetric <RunTrotterStep>(PrimitiveOperationsGroupsNames.CNOT), TraceSimulationStats = sim.ToCSV() }; // Dump all the statistics to CSV files, one file per statistics collector // FIXME: the names here aren't varied, and so the CSVs will get overwritten when running many // different Hamiltonians. var gateStats = sim.ToCSV(); foreach (var x in gateStats) { System.IO.File.WriteAllLines($"TrotterGateCountEstimates.{x.Key}.csv", new string[] { x.Value }); } } #endregion #region Trace Simulator on Qubitization step if (config.hamiltonianSimulationAlgorithm == HamiltonianSimulationConfig.HamiltonianSimulationAlgorithm.Qubitization) { if (config.qubitizationConfig.qubitizationStatePrep == HamiltonianSimulationConfig.QubitizationConfig.QubitizationStatePrep.MinimizeQubitCount) { stopWatch.Reset(); stopWatch.Start(); var res = await RunQubitizationStep.Run(sim, qSharpData); stopWatch.Stop(); gateCountResults = new GateCountResults { Method = "Qubitization", ElapsedMilliseconds = stopWatch.ElapsedMilliseconds, RotationsCount = sim.GetMetric <RunQubitizationStep>(PrimitiveOperationsGroupsNames.R), TCount = sim.GetMetric <RunQubitizationStep>(PrimitiveOperationsGroupsNames.T), CNOTCount = sim.GetMetric <RunQubitizationStep>(PrimitiveOperationsGroupsNames.CNOT), TraceSimulationStats = sim.ToCSV() }; // Dump all the statistics to CSV files, one file per statistics collector // FIXME: the names here aren't varied, and so the CSVs will get overwritten when running many // different Hamiltonians. var gateStats = sim.ToCSV(); foreach (var x in gateStats) { System.IO.File.WriteAllLines($"QubitizationGateCountEstimates.{x.Key}.csv", new string[] { x.Value }); } } } #endregion #region Trace Simulator on Optimized Qubitization step if (config.hamiltonianSimulationAlgorithm == HamiltonianSimulationConfig.HamiltonianSimulationAlgorithm.Qubitization) { if (config.qubitizationConfig.qubitizationStatePrep == HamiltonianSimulationConfig.QubitizationConfig.QubitizationStatePrep.MinimizeTGateCount) { stopWatch.Reset(); stopWatch.Start(); // This primarily affects the Qubit count and CNOT count. // The T-count only has a logarithmic dependence on this parameter. var targetError = 0.001; var res = await RunOptimizedQubitizationStep.Run(sim, qSharpData, targetError); stopWatch.Stop(); gateCountResults = new GateCountResults { Method = "Optimized Qubitization", ElapsedMilliseconds = stopWatch.ElapsedMilliseconds, RotationsCount = sim.GetMetric <RunOptimizedQubitizationStep>(PrimitiveOperationsGroupsNames.R), TCount = sim.GetMetric <RunOptimizedQubitizationStep>(PrimitiveOperationsGroupsNames.T), CNOTCount = sim.GetMetric <RunOptimizedQubitizationStep>(PrimitiveOperationsGroupsNames.CNOT), TraceSimulationStats = sim.ToCSV() }; // Dump all the statistics to CSV files, one file per statistics collector // FIXME: the names here aren't varied, and so the CSVs will get overwritten when running many // different Hamiltonians. var gateStats = sim.ToCSV(); foreach (var x in gateStats) { System.IO.File.WriteAllLines($"OptimizedQubitizationGateCountEstimates.{x.Key}.csv", new string[] { x.Value }); } } } #endregion return(gateCountResults); }
private static void SingleParameterizedResourceTest <TypeQop>( RunParameterizedQop runner, ReaderWriterLock locker, int n, int minParameter, int maxParameter, bool isControlled, string filename, bool full_depth, bool isAmortized) { // Track best cost var bestDepth = 9223372036854775807.0; var bestTGates = 9223372036854775807.0; // Iterate through values of the second parameter for (int j = minParameter; j < maxParameter; j++) { QCTraceSimulator estimator = GetTraceSimulator(full_depth); // construct simulator object // we must generate a new simulator in each round, to clear previous estimates var res = runner(estimator, n, isControlled, j).Result; // run test // Get results var roundDepth = estimator.GetMetric <TypeQop>(MetricsNames.DepthCounter.Depth); var roundTGates = estimator.GetMetric <TypeQop>(PrimitiveOperationsGroupsNames.T); // If amortized, we divide out the cost of this round if (isAmortized) { roundDepth = roundDepth / j; roundTGates = roundTGates / j; } // Create string of a row of parameters string thisCircuitCosts = DisplayCSV.CSV(estimator.ToCSV(), typeof(TypeQop).FullName, false, string.Empty, false, string.Empty); // add the row to the string of the csv thisCircuitCosts += $"{n}, {j}"; try { locker.AcquireWriterLock(int.MaxValue); // absurd timeout value System.IO.File.AppendAllText(filename, thisCircuitCosts); } finally { locker.ReleaseWriterLock(); } // Breaks if it's reached the minimum in both metrics // Assumes the metrics are convex if (roundDepth >= bestDepth && roundTGates >= bestTGates) { break; } else { if (roundDepth < bestDepth) { bestDepth = roundDepth; } if (roundTGates < bestTGates) { bestTGates = roundTGates; } } } }
private static void ParameterizedResourceTestSingleThreaded <TypeQop>( RunParameterizedQop runner, int[] ns, bool isControlled, bool isAmortized, string filename, bool full_depth, int[] minParameters, int[] maxParameters) { if (full_depth) { filename += "-all-gates"; } if (isControlled) { filename += "-controlled"; } filename += ".csv"; // Create table headers if file does not already exist if (!System.IO.File.Exists(filename)) { string estimation = string.Empty; estimation += " operation, CNOT count, 1-qubit Clifford count, T count, R count, M count, "; if (full_depth) { estimation += "Full depth, "; } else { estimation += "T depth, "; } estimation += "initial width, extra width, comment, size, parameter"; System.IO.File.WriteAllText(filename, estimation); } var bestParameter = minParameters[0]; for (int i = 0; i < ns.Length; i++) { // Starts a thread for each value in ns. // Each thread will independently search for an optimal size. var bestCost = 9223372036854775807.0; // Iterate through values of the second parameter for (int j = bestParameter; j < maxParameters[i]; j++) { QCTraceSimulator estimator = GetTraceSimulator(full_depth); // construct simulator object // we must generate a new simulator in each round, to clear previous estimates var res = runner(estimator, ns[i], isControlled, j).Result; // run test // Get results var roundCost = 0.0; if (DriverParameters.MinimizeDepthCostMetric) { // depth roundCost = estimator.GetMetric <TypeQop>(MetricsNames.DepthCounter.Depth); } else { roundCost = estimator.GetMetric <TypeQop>(PrimitiveOperationsGroupsNames.T); } // If amortized, we divide out the cost of this round if (isAmortized) { roundCost = roundCost / j; } // Create string of a row of parameters string thisCircuitCosts = DisplayCSV.CSV(estimator.ToCSV(), typeof(TypeQop).FullName, false, string.Empty, false, string.Empty); // add the row to the string of the csv thisCircuitCosts += $"{ns[i]}, {j}"; System.IO.File.AppendAllText(filename, thisCircuitCosts); // Breaks if it's reached the minimum in both metrics // Assumes the metrics are convex and increasing in n if (roundCost > bestCost) { break; } else if (roundCost < bestCost) { bestCost = roundCost; bestParameter = j; } } } }
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 } } }