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 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 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);
        }
Exemplo n.º 4
0
        public void ControlledSWAPMetricsTest()
        {
            // Get an instance of the appropriately configured QCTraceSimulator
            QCTraceSimulator sim = MetricCalculationUtils.GetSimulatorForMetricsCalculation();

            // Run tests against trace simulator to collect metrics
            var result = ControlledSWAPTest.Run(sim).Result;

            // Let us check that number of T gates in all the circuits is as expected
            string Tcount = PrimitiveOperationsGroupsNames.T;

            Assert.Equal(7, sim.GetMetric <ControlledSWAP1, CollectMetrics>(Tcount));
            Assert.Equal(7, sim.GetMetric <ControlledSWAPUsingCCNOT, CollectMetrics>(Tcount));

            // Let us check the number of CNOT gates
            Assert.Equal(8, sim.GetMetric <ControlledSWAP1, CollectMetrics>(
                             PrimitiveOperationsGroupsNames.CNOT));
            // Number of single qubit Clifford gates
            Assert.Equal(2, sim.GetMetric <ControlledSWAP1, CollectMetrics>(
                             PrimitiveOperationsGroupsNames.QubitClifford));

            // And T depth
            Assert.Equal(4, sim.GetMetric <ControlledSWAP1, CollectMetrics>(
                             MetricsNames.DepthCounter.Depth));
        }
Exemplo n.º 5
0
        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}");
            }
        }
Exemplo n.º 6
0
        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 void RepeatUntilSuccessCircuitsMetricsTest()
        {
            // Get an instance of the appropriately configured QCTraceSimulator
            QCTraceSimulator sim = MetricCalculationUtils.GetSimulatorForMetricsCalculation();

            // Run tests against trace simulator to collect metrics
            var result = RepeatUntilSuccessCircuitsTest.Run(sim).Result;

            string TCount      = PrimitiveOperationsGroupsNames.T;
            string extraQubits = MetricsNames.WidthCounter.ExtraWidth;
            string min         = StatisticsNames.Min;
            string max         = StatisticsNames.Max;
            string avg         = StatisticsNames.Average;

            // Let us check how many ancillas we used
            // 4 for Nielsen & Chuang
            // version because we used CCNOT3 which itself required 2 ancillas
            Assert.Equal(4, sim.GetMetric <ExpIZArcTan2NC, caller>(extraQubits));
            // 2 for Paetznick & Svore version
            Assert.Equal(2, sim.GetMetric <ExpIZArcTan2PS, caller>(extraQubits));

            // One trial of ExpIZArcTan2NC requires at least 8 T gates
            Assert.True(8 <= sim.GetMetricStatistic <ExpIZArcTan2NC, caller>(TCount, min));

            // One trial of ExpIZArcTan2NC requires at least 3 T gates
            Assert.True(3 <= sim.GetMetricStatistic <ExpIZArcTan2PS, caller>(TCount, min));

            // The rest of the statistical information we print into test output
            // For ExpIZArcTan2NC:
            output.WriteLine($"Statistics collected for{nameof(ExpIZArcTan2NC)}");
            output.WriteLine($"Average number of T-gates:" +
                             $" {sim.GetMetricStatistic<ExpIZArcTan2NC, caller>(TCount, avg)}");
            output.WriteLine($"Minimal number of T-gates: " +
                             $"{sim.GetMetricStatistic<ExpIZArcTan2NC, caller>(TCount, min)}");
            output.WriteLine($"Maximal number of T-gates: " +
                             $"{sim.GetMetricStatistic<ExpIZArcTan2NC, caller>(TCount, max)}");

            // And for ExpIZArcTan2PS
            output.WriteLine($"Statistics collected for{nameof(ExpIZArcTan2PS)}");
            output.WriteLine($"Average number of T-gates:" +
                             $" {sim.GetMetricStatistic<ExpIZArcTan2PS, caller>(TCount, avg)}");
            output.WriteLine($"Minimal number of T-gates: " +
                             $"{sim.GetMetricStatistic<ExpIZArcTan2PS, caller>(TCount, min)}");
            output.WriteLine($"Maximal number of T-gates: " +
                             $"{sim.GetMetricStatistic<ExpIZArcTan2PS, caller>(TCount, max)}");
        }
        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));
        }
        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);
        }
Exemplo n.º 10
0
        [InlineData(2017L)] // numberOfControlQubits = 4,5,2017
        public void MultiControlledNOTMetricsTest(long numberOfControlQubits)
        {
            // Get an instance of the appropriately configured QCTraceSimulator
            QCTraceSimulator sim = MetricCalculationUtils.GetSimulatorForMetricsCalculation();

            // Run tests against trace simulator to collect metrics
            var result =
                MultiControlledNotWithDirtyQubitsMetrics.Run(sim, numberOfControlQubits).Result;

            string borrowedQubits  = MetricsNames.WidthCounter.BorrowedWith;
            string allocatedQubits = MetricsNames.WidthCounter.ExtraWidth;

            // Get the number of qubits borrowed by the MultiControlledXBorrow
            double numBorowed1 =
                sim.GetMetric <MultiControlledXBorrow, MultiControlledNotWithDirtyQubitsMetrics>(
                    borrowedQubits);

            // Get the number of qubits allocated by the MultiControlledXBorrow
            double numAllocated1 =
                sim.GetMetric <MultiControlledXBorrow, MultiControlledNotWithDirtyQubitsMetrics>(
                    allocatedQubits);

            Assert.Equal(numberOfControlQubits - 2, numBorowed1);
            Assert.Equal(0, numAllocated1);

            // Get the number of qubits borrowed by the MultiControlledXClean
            double numBorowed2 =
                sim.GetMetric <MultiControlledXClean, MultiControlledNotWithDirtyQubitsMetrics>(
                    borrowedQubits);

            // Get the number of qubits allocated by the MultiControlledXClean
            double numAllocated2 =
                sim.GetMetric <MultiControlledXClean, MultiControlledNotWithDirtyQubitsMetrics>(
                    allocatedQubits);

            Assert.Equal(numberOfControlQubits - 2, numAllocated2);
            Assert.Equal(0, numBorowed2);
        }
Exemplo n.º 11
0
        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();
                }
            }
        }
Exemplo n.º 12
0
        public void TwoCNOTs()
        {
            QCTraceSimulator sim = GetTraceSimForMetrics();

            GetTest <TwoCNOTsTest>(sim)();

            void AssertEqualMetric(double value, string metric)
            {
                Assert.Equal(value, sim.GetMetric <TwoCNOTsTest>(metric));
            }

            AssertEqualMetric(2, DepthCounter.Metrics.Depth);
            AssertEqualMetric(2, PrimitiveOperationsGroupsNames.CNOT);
            AssertEqualMetric(3, WidthCounter.Metrics.ExtraWidth);
            AssertEqualMetric(0, DepthCounter.Metrics.StartTimeDifference);
        }
Exemplo n.º 13
0
        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 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);
        }
Exemplo n.º 15
0
        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);
            }
        }
Exemplo n.º 16
0
        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));
            }
        }
Exemplo n.º 17
0
        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;
                    }
                }
            }
        }
Exemplo n.º 18
0
        // 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);
        }
Exemplo n.º 19
0
        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;
                    }
                }
            }
        }
Exemplo n.º 20
0
        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
        }
Exemplo n.º 21
0
        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);
            }
        }