Example #1
0
        public async Task <bool> QuantumSolve(int[,] puzzle)
        {
            // Parse the puzzle into constraints.
            int size = puzzle.GetLength(0);

            FindEdgesAndInitialNumberConstraints(
                puzzle,
                size,
                out var emptySquareEdges,
                out var startingNumberConstraints,
                out var emptySquares
                );
            var emptySquareEdgesQArray          = new QArray <(long, long)>(emptySquareEdges);
            var startingNumberConstraintsQArray = new QArray <(long, long)>(startingNumberConstraints);

            // Estimate the resources required for the solution.
            var estimator = new ResourcesEstimator();

            SolvePuzzle.Run(estimator, emptySquares.Count, size, emptySquareEdgesQArray, startingNumberConstraintsQArray).Wait();
            Console.WriteLine($"The number of qubits estimated: {estimator.Data.Rows.Find("QubitCount")["Sum"]}");

            // Solve the puzzle!
            var sim = new QuantumSimulator(throwOnReleasingQubitsNotInZeroState: true);

            var(foundSolution, solution) = await SolvePuzzle.Run(sim, emptySquares.Count, size, emptySquareEdgesQArray, startingNumberConstraintsQArray);

            if (foundSolution)
            {
                foreach (var(emptySquare, completion) in Enumerable.Zip(emptySquares, solution))
                {
                    puzzle[emptySquare.Row, emptySquare.Column] = (int)completion + 1;
                }
            }
            return(foundSolution);
        }
        public void VerifyTracingMultipleOperationsTest()
        {
            ResourcesEstimator sim = new ResourcesEstimator();

            Operation_1_of_2.Run(sim).Wait();
            DataTable data1 = sim.Data;

            Assert.Equal(1.0, data1.Rows.Find("CNOT")["Sum"]);
            Assert.Equal(1.0, data1.Rows.Find("QubitClifford")["Sum"]);
            Assert.Equal(1.0, data1.Rows.Find("T")["Sum"]);
            Assert.Equal(0.0, data1.Rows.Find("R")["Sum"]);
            Assert.Equal(0.0, data1.Rows.Find("Measure")["Sum"]);
            Assert.Equal(2.0, data1.Rows.Find("QubitCount")["Sum"]);

            Operation_2_of_2.Run(sim).Wait();
            DataTable data2 = sim.Data;

            // Aggregated stats for both operations.
            Assert.Equal(1.0 + 2.0, data2.Rows.Find("CNOT")["Sum"]);
            Assert.Equal(1.0 + 1.0, data2.Rows.Find("QubitClifford")["Sum"]);
            Assert.Equal(1.0 + 0.0, data2.Rows.Find("T")["Sum"]);
            Assert.Equal(0.0 + 1.0, data2.Rows.Find("R")["Sum"]);
            Assert.Equal(0.0 + 1.0, data2.Rows.Find("Measure")["Sum"]);
            Assert.Equal(2.0 + 3.0, data2.Rows.Find("QubitCount")["Sum"]);
            Assert.Equal(System.Math.Max(2.0, 3.0), data2.Rows.Find("QubitCount")["Max"]);

            // Run again to confirm two operations isn't the limit!
            VerySimpleEstimate.Run(sim).Wait();
            DataTable data3 = sim.Data;

            Assert.Equal(2.0 + 3.0 + 3.0, data3.Rows.Find("QubitCount")["Sum"]);
            Assert.Equal(3.0, data3.Rows.Find("QubitCount")["Max"]);
        }
Example #3
0
        static void Main(string[] args)
        {
            // Estimate quantum resources.
            Console.WriteLine("Resource estimation");
            Console.WriteLine("-------------------");
            var estimator = new ResourcesEstimator();

            BellTest.Run(estimator, 1000, Result.Zero).Wait();
            Console.WriteLine(estimator.ToTSV());

            // Actually run the experiment (assuming the resources are enough).
            Console.WriteLine();
            Console.WriteLine("Experiment");
            Console.WriteLine("----------");
            using (var qsim = new QuantumSimulator())
            {
                // Try initial values
                var initials = new Result[] { Result.Zero, Result.One };
                foreach (var initial in initials)
                {
                    var res = BellTest.Run(qsim, 1000, initial).Result;
                    var(numZeros, numOnes, agree) = res;
                    Console.WriteLine(
                        $"Init:{initial,-4} 0s={numZeros,-4} 1s={numOnes,-4} agree={agree,-4}");
                }
            }

            Console.WriteLine();
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
Example #4
0
        static async Task Main(string[] args)
        {
            using (var qsim = new QuantumSimulator())
            {   // create each quantum circuit case
                int[,] arr =
                {
                    { 9, 4, 2 },                   //number to factor, no. of bits, random number
                    { 9, 4, 4 },
                    //...list of all possible cases
                };
                int l = arr.GetLength(0);
                // iterate through each cases
                for (int i = 0; i < l; i++)
                {
                    ResourcesEstimator estimator = new ResourcesEstimator();
                    // run the machine class to estimate the resources used
                    await FindOrder.Run(estimator, arr[i, 0], arr[i, 1], arr[i, 2]);

                    // query the data of depth, width, gates count
                    Console.WriteLine(
                        "[" +
                        arr[i, 0] + "," +
                        arr[i, 2] + "," +
                        estimator.Data.Rows.Find("CNOT")["Sum"] + "," +
                        estimator.Data.Rows.Find("QubitClifford")["Sum"] + "," +
                        estimator.Data.Rows.Find("R")["Sum"] + "," +
                        estimator.Data.Rows.Find("Measure")["Sum"] + "," +
                        estimator.Data.Rows.Find("T")["Sum"] + "," +
                        estimator.Data.Rows.Find("Depth")["Sum"] + "," +
                        estimator.Data.Rows.Find("Width")["Sum"] + "," +
                        estimator.Data.Rows.Find("BorrowedWidth")["Sum"] + "],"
                        );
                }
            }
        }
Example #5
0
        /// <summary>
        /// Simulates the entry point.
        /// </summary>
        /// <param name="entryPoint">The entry point.</param>
        /// <param name="simulator">The simulator to use.</param>
        /// <returns>The exit code.</returns>
        private static async Task <int> Simulate(EntryPoint entryPoint, string simulator)
        {
            simulator = DefaultIfShadowed(Constants.SimulatorOptions.First(), simulator, EntryPoint.DefaultSimulator);
            switch (simulator)
            {
            case Constants.ResourcesEstimator:
                var resourcesEstimator = new ResourcesEstimator();
                await entryPoint.Run(resourcesEstimator);

                Console.WriteLine(resourcesEstimator.ToTSV());
                break;

            default:
                var(isCustom, createSimulator) = simulator switch
                {
                    Constants.QuantumSimulator =>
                    (false, new Func <IOperationFactory>(() => new QuantumSimulator())),
                    Constants.ToffoliSimulator =>
                    (false, new Func <IOperationFactory>(() => new ToffoliSimulator())),
                    _ => (true, EntryPoint.CreateDefaultCustomSimulator)
                };
                if (isCustom && simulator != EntryPoint.DefaultSimulator)
                {
                    DisplayCustomSimulatorError(simulator);
                    return(1);
                }
                await DisplayEntryPointResult(entryPoint, createSimulator);

                break;
            }
            return(0);
        }
Example #6
0
        /// <summary>
        /// Simulates the entry point.
        /// </summary>
        /// <param name="settings">The driver settings.</param>
        /// <param name="entryPoint">The entry point.</param>
        /// <param name="parseResult">The command-line parsing result.</param>
        /// <param name="simulator">The simulator to use.</param>
        /// <returns>The exit code.</returns>
        internal static async Task <int> Simulate(
            DriverSettings settings, IEntryPoint <TIn, TOut> entryPoint, ParseResult parseResult, string simulator)
        {
            if (simulator == settings.ResourcesEstimatorName)
            {
                // Force the explicit load of the QSharp.Core assembly so that the ResourcesEstimator
                // can discover it dynamically at runtime and override the defined callables.
                var coreAssemblyName =
                    (from aName in entryPoint.GetType().Assembly.GetReferencedAssemblies()
                     where aName.Name == "Microsoft.Quantum.QSharp.Core"
                     select aName).First();
                var coreAssembly = Assembly.Load(coreAssemblyName.FullName);

                var resourcesEstimator = new ResourcesEstimator(coreAssembly);
                await resourcesEstimator.Run <TCallable, TIn, TOut>(entryPoint.CreateArgument(parseResult));

                Console.WriteLine(resourcesEstimator.ToTSV());
            }
            else
            {
                var(isCustom, createSimulator) =
                    simulator == settings.QuantumSimulatorName
                        ? (false, () => new QuantumSimulator())
                        : simulator == settings.ToffoliSimulatorName
                        ? (false, new Func <IOperationFactory>(() => new ToffoliSimulator()))
                        : (true, entryPoint.CreateDefaultCustomSimulator);
                if (isCustom && simulator != entryPoint.DefaultSimulatorName)
                {
                    DisplayCustomSimulatorError(simulator);
                    return(1);
                }
                await RunSimulator(entryPoint, parseResult, createSimulator);
            }
            return(0);
        }
Example #7
0
        static void estimate(int action)
        {
            var estimator = new ResourcesEstimator();

            switch (action)
            {
            case 6:
                var res6 = MeasureQBit.Run(estimator, 1000, Result.Zero).Result;
                break;

            case 7:
                var res7 = FlipQBit.Run(estimator, 1000, Result.Zero).Result;
                break;

            case 8:
                var res8 = SuperposeQBit.Run(estimator, 1000, Result.Zero).Result;
                break;

            case 9:
                var res9 = EntangleQBits.Run(estimator, 1000, Result.Zero).Result;
                break;
            }

            System.Console.WriteLine(estimator.ToTSV());

            System.Console.WriteLine("");
            System.Console.WriteLine("CNOT: The count of CNOT(also known as the Controlled Pauli X gate) gates executed.");
            System.Console.WriteLine("QubitClifford: The count of any single qubit Clifford and Pauli gates executed.");
            System.Console.WriteLine("Measure: The count of any measurements executed.");
            System.Console.WriteLine("R: The count of any single qubit rotations executed, excluding T, Clifford and Pauli gates.");
            System.Console.WriteLine("T: The count of T gates and their conjugates, including the T gate, T_x = H.T.H, and T_y = Hy.T.Hy, executed.");
            System.Console.WriteLine("Depth: Depth of the quantum circuit executed by the Q# operation. By default, only T gates are counted in the depth, see depth counter for details.");
            System.Console.WriteLine("Width: Maximum number of qubits allocated during the execution of the Q# operation.");
            System.Console.WriteLine("BorrowedWidth: Maximum number of qubits borrowed inside the Q# operation.");
        }
Example #8
0
        static void Main(string[] args)
        {
            int adder = 0;

            if (args.Length >= 1)
            {
                adder = Int32.Parse(args[0]);
            }

            String[] header = { "Qubits", "CNOT", "T", "Depth", "Width" };
            WriteRow(header);
            int max = 1024;

            if (adder == 1)
            {
                max = 60;
            }
            for (int i = 8; i <= max; i *= 2)
            {
                Console.Write("" + i);
                Console.Write("\t");
                ResourcesEstimator estimator = new ResourcesEstimator();
                T_NBit.Run(estimator, i, adder).Wait();
                var data = estimator.Data;

                String[] row = { $"{data.Rows.Find("CNOT")["Sum"]}",  $"{data.Rows.Find("T")["Sum"]}",
                                 $"{data.Rows.Find("Depth")["Sum"]}", $"{data.Rows.Find("Width")["Sum"]}" };
                WriteRow(row);
            }
        }
Example #9
0
        static void Main(string[] args)
        {
            ResourcesEstimator estimator = new ResourcesEstimator();

            RunDeutschJozsaAlgorithm.Run(estimator).Wait();
            Console.WriteLine(estimator.ToTSV());
        }
Example #10
0
        static void _bellTestDoubleQubit()
        {
            using (var qsim = new QuantumSimulator()){
                var estimator = new ResourcesEstimator();
                BellTestTwoQubits.Run(estimator, 1000, Result.Zero).Wait();

                System.Console.WriteLine(estimator.ToTSV());

                System.Console.WriteLine("Press any key to continue...");
                Console.ReadKey();

                // Try initial values
                Result[] initials = new Result[] { Result.Zero, Result.One };

                System.Console.WriteLine("** BELL TEST TWO QUBITS **");

                foreach (Result initial in initials)
                {
                    var res = BellTestTwoQubits.Run(qsim, 1000, initial).Result;
                    var(numZeros, numOnes, agree) = res;
                    System.Console.WriteLine(
                        $"Init:{initial,-4} 0s={numZeros,-4} 1s={numOnes,-4} agree={agree, -4}");
                }
            }
        }
Example #11
0
        /// <summary>
        /// Simulates the entry point.
        /// </summary>
        /// <param name="settings">The driver settings.</param>
        /// <param name="entryPoint">The entry point.</param>
        /// <param name="parseResult">The command-line parsing result.</param>
        /// <param name="simulator">The simulator to use.</param>
        /// <returns>The exit code.</returns>
        internal static async Task <int> Simulate(
            DriverSettings settings, IEntryPoint <TIn, TOut> entryPoint, ParseResult parseResult, string simulator)
        {
            if (simulator == settings.ResourcesEstimatorName)
            {
                var resourcesEstimator = new ResourcesEstimator();
                await resourcesEstimator.Run <TCallable, TIn, TOut>(entryPoint.CreateArgument(parseResult));

                Console.WriteLine(resourcesEstimator.ToTSV());
            }
            else
            {
                var(isCustom, createSimulator) =
                    simulator == settings.QuantumSimulatorName
                        ? (false, () => new QuantumSimulator())
                        : simulator == settings.ToffoliSimulatorName
                        ? (false, new Func <IOperationFactory>(() => new ToffoliSimulator()))
                        : (true, entryPoint.CreateDefaultCustomSimulator);
                if (isCustom && simulator != entryPoint.DefaultSimulatorName)
                {
                    DisplayCustomSimulatorError(simulator);
                    return(1);
                }
                await RunSimulator(entryPoint, parseResult, createSimulator);
            }
            return(0);
        }
        static void Main(string[] args)
        {
            ResourcesEstimator estimator = new ResourcesEstimator();

            Adder.Run(estimator).Wait();
            Console.WriteLine(estimator.ToTSV());
        }
Example #13
0
        private static void RunResourcesEstimator()
        {
            var estimator = new ResourcesEstimator();

            Run(estimator);

            Console.WriteLine(estimator.ToTSV());
        }
Example #14
0
        public static void ResourceEstimator()
        {
            ResourcesEstimator sim = new ResourcesEstimator();

            ResourceEstTrainModel.Run(sim).Wait();
            var stats = sim.ToTSV();

            System.Console.Write("\n" + stats + "\n");
        }
        private DataTable RunDepthVersusWidthTest(bool optimizeDepth)
        {
            QCTraceSimulators.QCTraceSimulatorConfiguration config = ResourcesEstimator.RecommendedConfig();
            config.OptimizeDepth = optimizeDepth;
            var sim = new ResourcesEstimator(config);

            DepthVersusWidth.Run(sim).Wait();
            return(sim.Data);
        }
Example #16
0
        static async Task Main(string[] args)
        {
            var rng          = new System.Random();
            var queryAddress = rng.Next(0, 7);
            var estimator    = new ResourcesEstimator();
            var output       = await TestImplicitQRAM.Run(estimator, queryAddress);

            // Print out a table of required resources, using the
            // ToTSV method of the ResourcesEstimator.
            Console.WriteLine(estimator.ToTSV());
        }
        public async Task <Dictionary <string, double> > Estimate(string id, IDictionary <string, string> args, Action <string> logger) =>
        await IfReady(async() =>
        {
            var qsim = new ResourcesEstimator();
            qsim.DisableLogToConsole();
            qsim.OnLog += logger;

            var value = await Find(id).RunAsync(qsim, args);

            return(qsim.AsDictionary());
        });
Example #18
0
        static void Main(string[] args)
        {
            var estimator = new ResourcesEstimator();

            BellTest.Run(estimator, 1000, Result.Zero).Wait();

            System.Console.WriteLine(estimator.ToTSV());

            System.Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
        public void VerifyDataTest()
        {
            var sim = new ResourcesEstimator();

            VerySimpleEstimate.Run(sim).Wait();
            var data = sim.Data;

            Assert.Equal(1.0, data.Rows.Find("CNOT")["Sum"]);
            Assert.Equal(0.0, data.Rows.Find("R")["Sum"]);
            Assert.Equal(2.0, data.Rows.Find("QubitClifford")["Sum"]);
            Assert.Equal(3.0, data.Rows.Find("Width")["Sum"]);
        }
Example #20
0
        public void QubitReuseSequentialTest()
        {
            QCTraceSimulators.QCTraceSimulatorConfiguration config = ResourcesEstimator.RecommendedConfig();
            config.OptimizeDepth = true;
            var sim = new ResourcesEstimator(config);

            SequentialUse.Run(sim).Wait();

            Assert.Equal(11.0, sim.Data.Rows.Find("QubitCount")["Sum"]);
            Assert.Equal(20.0, sim.Data.Rows.Find("Width")["Sum"]);
            Assert.Equal(11.0, sim.Data.Rows.Find("Depth")["Sum"]);
        }
Example #21
0
        public void ReuseInBlockMixedTest()
        {
            QCTraceSimulators.QCTraceSimulatorConfiguration config = ResourcesEstimator.RecommendedConfig();
            config.OptimizeDepth = true;
            var sim = new ResourcesEstimator(config);

            ReuseInBlockMixed.Run(sim).Wait();

            Assert.Equal(8.0, sim.Data.Rows.Find("QubitCount")["Sum"]);
            Assert.Equal(2.0, sim.Data.Rows.Find("Width")["Sum"]);
            Assert.Equal(0.0, sim.Data.Rows.Find("Depth")["Sum"]);
        }
        public void DepthDifferentQubitsTest()
        {
            var sim = new ResourcesEstimator();

            // using(q = Qubit[3]) { T(q[0]); T(q[1]); T(q[3]); T(q[0]); }
            DepthDifferentQubits.Run(sim).Wait();
            var data = sim.Data;

            Assert.Equal(4.0, data.Rows.Find("T")["Sum"]);
            Assert.Equal(3.0, data.Rows.Find("Width")["Sum"]);
            Assert.Equal(2.0, data.Rows.Find("Depth")["Sum"]);
        }
        public void DepthVersusWidthTest()
        {
            var sim = new ResourcesEstimator();

            // using(q = Qubit()) { T(q); } using(q = Qubit()) { T(q); } (yes, twice)
            DepthVersusWidth.Run(sim).Wait();
            var data = sim.Data;

            Assert.Equal(2.0, data.Rows.Find("T")["Sum"]);
            Assert.Equal(1.0, data.Rows.Find("Width")["Sum"]);
            Assert.Equal(1.0, data.Rows.Find("Depth")["Sum"]);
        }
Example #24
0
        public void QubitReuseSimultaneousTest()
        {
            QCTraceSimulators.QCTraceSimulatorConfiguration config = ResourcesEstimator.RecommendedConfig();
            config.OptimizeDepth = true;
            var sim = new ResourcesEstimator(config);

            SimultaneousUse.Run(sim).Wait();

            Assert.Equal(11.0, sim.Data.Rows.Find("QubitCount")["Sum"]);
            Assert.Equal(20.0, sim.Data.Rows.Find("Width")["Sum"]);
            // Note that in RecommendedConfig only T gates are depth 1, the rest are depth 0.
            Assert.Equal(1.0, sim.Data.Rows.Find("Depth")["Sum"]);
        }
Example #25
0
        /// <summary>
        /// Returns the ResourcesEstimator data as metric=value
        /// </summary>
        public static Dictionary <string, double> AsDictionary(this ResourcesEstimator qsim)
        {
            var counts = new Dictionary <string, double>();

            foreach (DataRow row in qsim.Data.Rows)
            {
                string metric = (string)row["Metric"];
                double data   = (double)row["Sum"];

                counts[metric] = data;
            }

            return(counts);
        }
Example #26
0
        /// <summary>
        ///     Given an input representing the name of an operation and a JSON
        ///     serialization of its inputs, returns a task that can be awaited
        ///     on for resource estimates from running that operation.
        /// </summary>
        public async Task<ExecutionResult> RunAsync(string input, IChannel channel)
        {
            var (name, args) = ParseInput(input);

            var symbol = SymbolResolver.Resolve(name) as IQSharpSymbol;
            if (symbol == null) throw new InvalidOperationException($"Invalid operation name: {name}");

            var qsim = new ResourcesEstimator().WithStackTraceDisplay(channel);
            qsim.DisableLogToConsole();

            await symbol.Operation.RunAsync(qsim, args);

            return qsim.Data.ToExecutionResult();
        }
        public void RecommendedConfigTest()
        {
            var actual = ResourcesEstimator.RecommendedConfig();

            Assert.Equal(1u, actual.CallStackDepthLimit);

            // This disabled by default:
            Assert.False(actual.ThrowOnUnconstrainedMeasurement);
            Assert.False(actual.UseDistinctInputsChecker);
            Assert.False(actual.UseInvalidatedQubitsUseChecker);

            // Counters that we're expecting:
            Assert.True(actual.UsePrimitiveOperationsCounter);
            Assert.True(actual.UseDepthCounter);
            Assert.True(actual.UseWidthCounter);
        }
        public void VerifyCollectorsTest()
        {
            var sim = new ResourcesEstimator();

            foreach (var l in sim.CoreConfig.Listeners)
            {
                // All listeners we expected are ICallGraphStatistics
                var collector = l as ICallGraphStatistics;
                Assert.NotNull(collector);

                // We expect all of them to have the Moment (with Sum)
                var stats    = collector.Results.GetStatisticsNamesCopy();
                var expected = new MomentsStatistic().GetStatisticsNames();
                foreach (var n in expected)
                {
                    Assert.Contains(n, stats);
                }
            }
        }
Example #29
0
        static void Main(string[] args)
        {
            // using (var qsim = new QuantumSimulator())
            // {
            //     //HelloQ.Run(qsim, int.MaxValue, int.MaxValue).Wait();
            //     TooManyQubits.Run(qsim).Wait();
            // }

            var tsim = new ToffoliSimulator(qubitCount: 500000);

            TooManyQubits.Run(tsim).Wait();

            var estimator = new ResourcesEstimator();

            TeleportClassicalMessage.Run(estimator, false).Wait();

            var data = estimator.Data;

            Console.WriteLine(estimator.ToTSV());
        }
Example #30
0
        /// <summary>
        ///     Given an input representing the name of an operation and a JSON
        ///     serialization of its inputs, returns a task that can be awaited
        ///     on for resource estimates from running that operation.
        /// </summary>
        public async Task <ExecutionResult> RunAsync(string input, IChannel channel)
        {
            var inputParameters = ParseInputParameters(input, firstParameterInferredName: ParameterNameOperationName);

            var name   = inputParameters.DecodeParameter <string>(ParameterNameOperationName);
            var symbol = SymbolResolver.Resolve(name) as IQSharpSymbol;

            if (symbol == null)
            {
                throw new InvalidOperationException($"Invalid operation name: {name}");
            }

            var qsim = new ResourcesEstimator().WithStackTraceDisplay(channel);

            qsim.DisableLogToConsole();

            await symbol.Operation.RunAsync(qsim, inputParameters);

            return(qsim.Data.ToExecutionResult());
        }