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);
        }
Exemplo n.º 2
0
        public void TracerCoreConstructor()
        {
            QCTraceSimulatorConfiguration tracerCoreConfiguration = new QCTraceSimulatorConfiguration();

            tracerCoreConfiguration.UsePrimitiveOperationsCounter = true;
            QCTraceSimulator tracerCore = new QCTraceSimulator(tracerCoreConfiguration);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Creates the four Bell (maximally entangled two-qubit) states and measures the correlations
        /// between the two qubits.
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            using (var quantumSimulator = new QuantumSimulator())
            {
                QCTraceSimulator  traceSimulator = CreateTraceSimulator();
                IOperationFactory simulator;

                if (useTraceSimulator)
                {
                    simulator = traceSimulator;
                }
                else
                {
                    simulator = quantumSimulator;
                }

                Console.OutputEncoding = System.Text.Encoding.UTF8;

                Console.WriteLine("Puts two qubits in a Bell (maximally entangled) state, measuring " +
                                  "the first then checking if it correlates with the second. The Bell state is " +
                                  "created by applying a Hadamard gate to the first qubit then a CNOT to them both " +
                                  "using the first as a control.");
                Console.WriteLine();

                var initialValues = new[]
Exemplo n.º 4
0
        public void GetPrimitiveOperations()
        {
            QCTraceSimulator tracerCore = new QCTraceSimulator();

            var measureOp = tracerCore.Get <Intrinsic.Measure, Intrinsic.Measure>();

            Assert.NotNull(measureOp);

            var assertOp = tracerCore.Get <Intrinsic.Assert, Intrinsic.Assert>();

            Assert.NotNull(assertOp);

            var assertProb = tracerCore.Get <Intrinsic.AssertProb, Intrinsic.AssertProb>();

            Assert.NotNull(assertProb);

            var allocOp = tracerCore.Get <Intrinsic.Allocate, Intrinsic.Allocate>();

            Assert.NotNull(allocOp);

            var releaseOp = tracerCore.Get <Intrinsic.Release, Intrinsic.Release>();

            Assert.NotNull(releaseOp);

            var borrowOp = tracerCore.Get <Intrinsic.Borrow, Intrinsic.Borrow>();

            Assert.NotNull(borrowOp);

            var returnOp = tracerCore.Get <Intrinsic.Return, Intrinsic.Return>();

            Assert.NotNull(returnOp);
        }
        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));
        }
Exemplo n.º 7
0
        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);
        }
Exemplo n.º 8
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.º 9
0
        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();
            }
        }
Exemplo n.º 10
0
        public void TracerVerifyPrimitivesCompleteness()
        {
            QCTraceSimulator tracerCore = new QCTraceSimulator();

            var ops =
                from op in typeof(Intrinsic.X).Assembly.GetExportedTypes()
                where op.IsSubclassOf(typeof(AbstractCallable))
                where !op.IsNested
                select op;

            var missing = new List <Type>();

            foreach (var op in ops)
            {
                try
                {
                    var i = tracerCore.GetInstance(op);
                    Assert.NotNull(i);
                }
                catch (Exception)
                {
                    missing.Add(op);
                }
            }

            Assert.Empty(missing);
        }
Exemplo n.º 11
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.º 12
0
        public void UseReleasedQubitsTests()
        {
            QCTraceSimulator sim = new QCTraceSimulator(new QCTraceSimulatorConfiguration()
            {
                UseInvalidatedQubitsUseChecker = true
            });

            Assert.Throws <InvalidatedQubitsUseCheckerException>(GetTest <UseReleasedQubitTest>(sim));
        }
        public void PQRSTermFromGeneralHamiltonianTest()
        {
            var generalHamiltonian = new FermionHamiltonian(nOrbitals: 2, nElectrons: 1);

            generalHamiltonian.AddFermionTerm(PQRSTermType, new Int64[] { 0, 1, 3, 2 }, 2.0);
            var jwEvolutionSetData = JordanWignerEncoding.Create(generalHamiltonian);
            var termData           = jwEvolutionSetData.Terms;
            var qsim = new QCTraceSimulator(TraceConfig.config);

            RunOptimizedBlockEncoding.Run(qsim, generalHamiltonian.NOrbitals * 2, termData, targetError).Wait();
        }
        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 void PQRSTermFromLiquidOrbitalTest()
        {
            string orbitals           = "0,1,0,1=1.0";
            var    generalHamiltonian = LoadData.LoadFromLiquid(orbitals);

            generalHamiltonian.NElectrons = 1L;
            var jwEvolutionSetData = JordanWignerEncoding.Create(generalHamiltonian);
            var termData           = jwEvolutionSetData.Terms;
            var qsim = new QCTraceSimulator(TraceConfig.config);

            RunOptimizedBlockEncoding.Run(qsim, generalHamiltonian.NOrbitals * 2, termData, targetError).Wait();
        }
        public void PPTermFromGeneralHamiltonianTest()
        {
            var generalHamiltonian = new FermionHamiltonian(nOrbitals: 1, nElectrons: 1);

            generalHamiltonian.AddFermionTerm(PPTermType, new Int64[] { 0, 0 }, 1.0);
            generalHamiltonian.AddFermionTerm(PPTermType, new Int64[] { 1, 1 }, -1.0);
            var jwEvolutionSetData  = JordanWignerEncoding.Create(generalHamiltonian);
            var identityCoefficient = jwEvolutionSetData.energyOffset;
            var termData            = jwEvolutionSetData.Terms;
            var qsim = new QCTraceSimulator(TraceConfig.config);

            RunOptimizedBlockEncoding.Run(qsim, generalHamiltonian.NOrbitals * 2, termData, targetError).Wait();
        }
Exemplo n.º 17
0
        public void DistinctQubitsTests()
        {
            QCTraceSimulator sim = new QCTraceSimulator(new QCTraceSimulatorConfiguration()
            {
                UseDistinctInputsChecker = true
            });

            Assert.Throws <DistinctInputsCheckerException>(GetTest <DisctinctQubitTest>(sim));
            Assert.Throws <DistinctInputsCheckerException>(GetTest <DisctinctQubitCapturedTest>(sim));
            Assert.Throws <DistinctInputsCheckerException>(GetTest <DisctinctQubitCaptured2Test>(sim));
            Assert.Throws <DistinctInputsCheckerException>(GetTest <DisctinctQubitCaptured3Test>(sim));
            Assert.Throws <DistinctInputsCheckerException>(GetTest <DisctinctQubitCaptured4Test>(sim));
        }
        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;
        }
Exemplo n.º 20
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.º 21
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)}");
        }
Exemplo n.º 23
0
        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 }
                    );
            }
        }
Exemplo n.º 24
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);
        }
        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);
        }
Exemplo n.º 28
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.º 29
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.º 30
0
 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}");
                 }
             }
         }
     }
 }