Пример #1
0
        // This method computes the gate count of simulation by all configurations passed to it.
        internal static async Task <IEnumerable <GateCountResults> > RunGateCount(string filename, IntegralDataFormat format, IEnumerable <HamiltonianSimulationConfig> configurations)
        {
            // Read Hamiltonian terms from file.
            IEnumerable <FermionHamiltonian> hamiltonians =
                format.Map(
                    (IntegralDataFormat.Liquid, () => FermionHamiltonian.LoadFromLiquid(filename)),
                    (IntegralDataFormat.YAML, () => FermionHamiltonian.LoadFromYAML(filename))
                    );

            var hamiltonian = hamiltonians.First();

            // Process Hamiltonitn to obtain optimized Jordan-Wigner representation.
            var jordanWignerEncoding = JordanWignerEncoding.Create(hamiltonian);

            // Convert to format for consumption by Q# algorithms.
            var qSharpData = jordanWignerEncoding.QSharpData();

            var gateCountResults = new List <GateCountResults>();

            foreach (var config in configurations)
            {
                GateCountResults results = await RunGateCount(qSharpData, config);

                results.HamiltonianName  = hamiltonian.Name;
                results.IntegralDataPath = filename;
                results.SpinOrbitals     = jordanWignerEncoding.NSpinOrbitals;
                gateCountResults.Add(results);
            }

            return(gateCountResults);
        }
Пример #2
0
        // Perform quantum simulation of Hamiltonian at desired bond length and
        // return estimate of energy.
        internal static (Double, Double) GetSimulationResult(int idxBond, string inputState = "Greedy")
        {
            // Choose the desired hamiltonian indexed by `idx`.
            var hamiltonian = hamiltonianData.ElementAt(idxBond);

            // Bond length conversion from Bohr radius to Angstrom
            var bondLength = Double.Parse(bondLengths[idxBond]);


            // Create Jordan-Wigner encodinf of Hamiltonian.
            var jordanWignerEncoding = JordanWignerEncoding.Create(hamiltonian);


            // Invoke quantum simulator and run `GetEnergyByTrotterization` in the first
            // molecular Hydrogen sample.
            using (var qSim = new QuantumSimulator())
            {
                var qSharpData = jordanWignerEncoding.QSharpData(inputState);
                Console.WriteLine($"Estimating at bond length {idxBond}:");

                var(phaseEst, energyEst) = GetEnergyByTrotterization.Run(qSim, qSharpData, bitsOfPrecision, trotterStepSize, IntegratorOrder).Result;

                return(bondLength, energyEst);
            }
        }
        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();
        }
        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 PQTermABFromGeneralHamiltonianTest()
        {
            var generalHamiltonian = new FermionHamiltonian(nOrbitals: 1, nElectrons: 1);

            generalHamiltonian.AddFermionTerm(PQTermType, new Int64[] { 0, 1 }, 2.0);
            var jwEvolutionSetData = JordanWignerEncoding.Create(generalHamiltonian);
            var termData           = jwEvolutionSetData.Terms;

            using (var qsim = new QuantumSimulator())
            {
                BlockEncodingStep.Run(qsim, generalHamiltonian.NOrbitals * 2, termData).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();
        }
        public void PQQRTermFromGeneralHamiltonianTest()
        {
            var generalHamiltonian = new FermionHamiltonian(nOrbitals: 2, nElectrons: 1);

            generalHamiltonian.AddFermionTerm(PQQRTermType, new Int64[] { 0, 1, 2, 0 }, 1.0);
            var jwEvolutionSetData = JordanWignerEncoding.Create(generalHamiltonian);
            var termData           = jwEvolutionSetData.Terms;

            using (var qsim = new QuantumSimulator())
            {
                PQQRTermFromGeneralHamiltonianTestOp.Run(qsim, termData).Wait();
            }
        }
        public void PQTermACFromGeneralHamiltonianTest()
        {
            var generalHamiltonian = new FermionHamiltonian(nOrbitals: 3, nElectrons: 1);

            generalHamiltonian.AddFermionTerm(PQTermType, new Int64[] { 0, 2 }, 2.0);
            var jwEvolutionSetData  = JordanWignerEncoding.Create(generalHamiltonian);
            var identityCoefficient = jwEvolutionSetData.energyOffset;
            var termData            = jwEvolutionSetData.Terms;

            using (var qsim = new QuantumSimulator())
            {
                PQTermACFromGeneralHamiltonianTestOp.Run(qsim, termData).Wait();
            }
        }
Пример #9
0
        internal static (Double, Double) GetSimulationResult(int idxBond, string inputState = "Greedy")
        {
            var hamiltonian          = hamiltonianData.ElementAt(idxBond);
            var bondLength           = Double.Parse(bondLengths[idxBond]);
            var jordanWignerEncoding = JordanWignerEncoding.Create(hamiltonian);

            using (var qSim = new QuantumSimulator())
            {
                var qSharpData = jordanWignerEncoding.QSharpData(inputState);
                Console.WriteLine($"Estimating at {bondLength} A;  {idxBond}-th bond length:");
                var(phaseEst, energyEst) = GetEnergyByTrotterization.Run(qSim, qSharpData, bitsOfPrecision, trotterStepSize, IntegratorOrder).Result;
                return(bondLength, energyEst);
            }
        }
        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;

            using (var qsim = new QuantumSimulator())
            {
                PQRSTermFromLiquidOrbitalTestOp.Run(qsim, termData).Wait();
            }
        }
        public void PQQPTermFromLiquidOrbitalTest()
        {
            string orbitals           = "0,1,1,0=1.0";
            var    generalHamiltonian = LoadData.LoadFromLiquid(orbitals);

            generalHamiltonian.NElectrons = 1L;
            var jwEvolutionSetData  = JordanWignerEncoding.Create(generalHamiltonian);
            var identityCoefficient = jwEvolutionSetData.energyOffset;
            var termData            = jwEvolutionSetData.Terms;

            using (var qsim = new QuantumSimulator())
            {
                BlockEncodingStep.Run(qsim, generalHamiltonian.NOrbitals * 2, termData).Wait();
            }
        }
Пример #12
0
        // For each Hamiltonian,
        internal static (Double, Double) GetSimulationResult(int idxBond)
        {
            // Choose the desired hamiltonian indexed by `idx`.
            FermionHamiltonian hamiltonian = hamiltonianData.ElementAt(idxBond);

            // Bond length conversion from Bohr radius to Angstrom
            double bondLength = Double.Parse(hamiltonian.MiscellaneousInformation.Split(new char[] { ',' }).Last()) * 0.5291772;

            // Set the number of occupied spin-orbitals to 2.
            hamiltonian.NElectrons = 2;

            // Create Jordan-Wigner encodinf of Hamiltonian.
            JordanWignerEncoding jordanWignerEncoding = JordanWignerEncoding.Create(hamiltonian);

            // Choose bits of precision in quantum phase estimation
            Int64 bitsOfPrecision = 7;

            // Choose the Trotter step size.
            Double trotterStepSize = 1.0;

            // Choose the Trotter integrator order
            Int64 trotterOrder = 1;

            // Invoke quantum simulator and run `GetEnergyByTrotterization` in the first
            // molecular Hydrogen sample.
            using (var qSim = new QuantumSimulator())
            {
                var qSharpData = jordanWignerEncoding.QSharpData();
                System.Console.WriteLine($"Estimating at bond length {idxBond}:");
                // Loop if excited state energy is obtained.
                var energyEst = 0.0;
                do
                {
                    var(phaseEst, energyEstTmp) = GetEnergyByTrotterization.Run(qSim, qSharpData, bitsOfPrecision, trotterStepSize, trotterOrder).Result;
                    energyEst = energyEstTmp;
                } while (energyEst > -0.8);

                return(bondLength, energyEst);
            }
        }
Пример #13
0
        static void Main(string[] args)
        {
            // var FILENAME = "h2_2_sto6g_1.0au.yaml";
            var FILENAME = "h4_sto6g_0.000.yaml";
            // var FILENAME = "h20_nwchem.yaml";

            var STATE = "|G>";

            // 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);

            using (var qsim = new QuantumSimulator())
            {
                var res = PrepareStateMLE.Run(qsim, data).Result;
                Console.WriteLine($"MLE is {res}");
            }
        }
        public void JordanWignerOptimizedEvolutionSetTest()
        {
            var hamiltonian = JordanWignerEncoding.Create(GenerateTestHamiltonian());
            var termData    = hamiltonian.Terms;

            Assert.True(GenerateTestHamiltonian().VerifyFermionTerms());
            Assert.Equal(hamiltonian.energyOffset, 3.0 * 0.5 + 0.25 * 3.0);
            Assert.Contains(new HTerm((new QArray <Int64> (new[] { 0L }), new QArray <Double> (new[] { -0.5 * 1.0 - 0.25 * 1.0 }))), termData.Item1, new Extensions.HTermArrayComparer());
            Assert.Contains(new HTerm((new QArray <Int64> (new[] { 1L }), new QArray <Double> (new[] { -0.5 * 1.0 - 0.25 * 1.0 }))), termData.Item1, new Extensions.HTermArrayComparer());
            Assert.Contains(new HTerm((new QArray <Int64> (new[] { 2L }), new QArray <Double> (new[] { -0.5 * 1.0 - 2.0 * 0.25 * 1.0 }))), termData.Item1, new Extensions.HTermArrayComparer());
            Assert.Contains(new HTerm((new QArray <Int64> (new[] { 3L }), new QArray <Double> (new[] { -0.25 * 1.0 }))), termData.Item1, new Extensions.HTermArrayComparer());
            Assert.Contains(new HTerm((new QArray <Int64> (new[] { 6L }), new QArray <Double> (new[] { -0.25 * 1.0 }))), termData.Item1, new Extensions.HTermArrayComparer());

            Assert.Contains(new HTerm((new QArray <Int64> (new[] { 0L, 2L }), new QArray <Double> (new[] { 0.25 * 1.0 }))), termData.Item2, new Extensions.HTermArrayComparer());
            Assert.Contains(new HTerm((new QArray <Int64> (new[] { 1L, 3L }), new QArray <Double> (new[] { 0.25 * 1.0 }))), termData.Item2, new Extensions.HTermArrayComparer());
            Assert.Contains(new HTerm((new QArray <Int64> (new[] { 2L, 6L }), new QArray <Double> (new[] { 0.25 * 1.0 }))), termData.Item2, new Extensions.HTermArrayComparer());

            Assert.Contains(new HTerm((new QArray <Int64> (new[] { 0L, 2, 2, 1 }), new QArray <Double> (new[] { -0.125 * 1.0 }))), termData.Item3, new Extensions.HTermArrayComparer());
            Assert.Contains(new HTerm((new QArray <Int64> (new[] { 1L, 3, 3, 2 }), new QArray <Double> (new[] { -0.125 * 1.0 }))), termData.Item3, new Extensions.HTermArrayComparer());
            Assert.Contains(new HTerm((new QArray <Int64> (new[] { 2L, 6, 6, 5 }), new QArray <Double> (new[] { -0.125 * 1.0 }))), termData.Item3, new Extensions.HTermArrayComparer());

            // Test incomplete
        }
Пример #15
0
        static void Main(string[] args)
        {
            Console.Write("Run QE or VQE? ");
            String runString = Console.ReadLine();

            #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);

            #endregion
            #region Hybrid Quantum/Classical accelerator
            // Feed created state and hamiltonian terms to VQE
            if (runString.Equals("VQE"))
            {
                Console.WriteLine("----- Begin VQE Simulation");
            }
            else
            {
                Console.WriteLine("----- Begin QE Simulation");
            }

            using (var qsim = new QuantumSimulator())
            {
                if (runString.Equals("VQE"))
                {
                    string useGroundState;
                    Console.Write("Use ground state? (yes or no): ");
                    useGroundState = Console.ReadLine();

                    var statePrepData = data.Item3; // statePrep data
                    var N             = statePrepData.Length;

                    double convertDoubleArrToJWInputStateArr(double[] x)
                    {
                        var JWInputStateArr = new QArray <JordanWignerInputState>();

                        for (int i = 0; i < N; i++)
                        {
                            var currJWInputState = statePrepData[i];
                            var positions        = currJWInputState.Item2;
                            JWInputStateArr.Add(new JordanWignerInputState(((x[i], 0.0), positions)));
                        }
                        return(Simulate_Variational.Run(qsim, data, 1.0, MOE, JWInputStateArr).Result);
                    }

                    Func <double[], double> Simulate_Wrapper = (double[] x) => convertDoubleArrToJWInputStateArr(x);

                    var solver = new NelderMead((int)N, Simulate_Wrapper);

                    // create initial condition vector
                    var initialConds = new double[N];
                    for (int i = 0; i < N; i++)
                    {
                        if (useGroundState.Equals("yes"))
                        {
                            var currJWInputState = statePrepData[i];
                            var groundStateGuess = currJWInputState.Item1;
                            initialConds[i] = groundStateGuess.Item1;
                        }
                        else
                        {
                            initialConds[i] = 0.0;
                        }
                    }

                    // Now, we can minimize it with:
                    bool success = solver.Minimize(initialConds);

                    // And get the solution vector using
                    double[] solution = solver.Solution;

                    // The minimum at this location would be:
                    double minimum = solver.Value;

                    Console.WriteLine($"Solution converged: {success}");
                    Console.WriteLine("The solution is: " + String.Join(" ", solution));
                    Console.WriteLine($"The minimum is: {minimum}");
                }
                else
                {
                    Console.WriteLine(Simulate.Run(qsim, data, 1.0, MOE).Result);
                }
            }
            #endregion
            #region Classical update scheme
            // Determine how to update the starting state using classical methods
            #endregion
        }
        static void Main(string[] args)
        {
            var logger = Logging.LoggerFactory.CreateLogger <Driver>();



            string LiquidFilename = "h2o.dat";

            var numElectrons = 2;


            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();

            logger.LogInformation($"Reading {LiquidFilename}");
            var generalHamiltonian = FermionHamiltonian.LoadFromLiquid($@"{LiquidFilename}").Single();

            generalHamiltonian.NElectrons = numElectrons;
            logger.LogInformation($"The loading of the file took {stopWatch.ElapsedMilliseconds}ms");
            stopWatch.Restart();


            generalHamiltonian.LogSpinOrbitals();


            var jwEncoding = JordanWignerEncoding.Create(generalHamiltonian);


            jwEncoding.LogSpinOrbitals();

            logger.LogInformation(" reading the file is complete");


            using (var qsim = new QuantumSimulator())
            {
                var qSData = jwEncoding.QSharpData();


                var bits = 10;


                var steps = 5;


                var trotterStep = .4;



                for (int i = 0; i < steps; i++)
                {
                    var(phaseEstimate, energyEstimate) = TrotterEnergyEstimator.Run(qsim, qSData, bits, trotterStep).Result;
                    logger.LogInformation($"Trotter estimation. phase: {phaseEstimate}; energy {energyEstimate}");
                }


                for (int i = 0; i < steps; i++)
                {
                    var(phaseEstimate, energyEstimate) = OptimizedTrotterEnergyEstimator.Run(qsim, qSData, bits - 1, trotterStep).Result;
                    logger.LogInformation($"Optimized Trotter estimation. phase {phaseEstimate}; energy {energyEstimate}");
                }

                for (int i = 0; i < steps; i++)
                {
                    var(phaseEstimate, energyEstimate) = QubitizationEnergyEstimator.Run(qsim, qSData, bits - 2).Result;
                    logger.LogInformation($"Qubitization estimation. phase: {phaseEstimate}; energy {energyEstimate}");
                }
            }
        }
Пример #17
0
        static void Main(string[] args)
        {
            //////////////////////////////////////////////////////////////////////////
            // Introduction //////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////////////////////

            // In this example, we will create a spin-orbital representation of the molecular
            // Hydrogen Hamiltonian `H`, given ovelap coefficients for its one- and
            // two - electron integrals.

            // We when perform quantum phase estimation to obtain an estimate of
            // the molecular Hydrogen ground state energy.

            #region Building the Hydrogen Hamiltonian through orbital integrals

            // One of the simplest representations of Hydrogen uses only two
            // molecular orbitals indexed by `0` and `1`.
            var nOrbitals = 2;

            // This representation also has two occupied spin-orbitals.
            var nElectrons = 2;

            // The Coulomb repulsion energy between nuclei is
            var energyOffset = 0.713776188;

            // One-electron integrals are listed below
            // <0|H|0> = -1.252477495
            // <1|H|1> = -0.475934275

            // Two-electron integrals are listed below
            // <00|H|00> = 0.674493166
            // <01|H|01> = 0.181287518
            // <01|H|10> = 0.663472101
            // <11|H|11> = 0.697398010
            // Note that orbitals are assumed to be real. Moreover, indistinguishability
            // of electrons means that the following integrals are equal.
            //   <PQ|H|RS> = <PR|H|QS> = <SQ|H|RP> = <SR|H|QP>
            // = <QP|H|SR> = <RP|H|SQ> = <QS|H|PR> = <RS|H|PQ>
            // Thus it sufficies to specify just any one of these terms from each symmetry
            // group.

            // These orbital integrals are represented using the OrbitalIntegral
            // data structure.
            var orbitalIntegrals = new OrbitalIntegral[]
            {
                new OrbitalIntegral(new[] { 0, 0 }, -1.252477495),
                new OrbitalIntegral(new[] { 1, 1 }, -0.475934275),
                new OrbitalIntegral(new[] { 0, 0, 0, 0 }, 0.674493166),
                new OrbitalIntegral(new[] { 0, 1, 0, 1 }, 0.181287518),
                new OrbitalIntegral(new[] { 0, 1, 1, 0 }, 0.663472101),
                new OrbitalIntegral(new[] { 1, 1, 1, 1 }, 0.697398010)
            };

            // We initialize a Fermion Hamiltonian data structure and add terms to it
            var hamiltonian = new FermionHamiltonian();
            hamiltonian.NOrbitals    = nOrbitals;
            hamiltonian.NElectrons   = nElectrons;
            hamiltonian.EnergyOffset = energyOffset;
            hamiltonian.AddFermionTerm(orbitalIntegrals);

            // These orbital integral terms are automatically expanded into
            // spin-orbitals. We may print the Hamiltonian to see verify what it contains.
            Console.WriteLine("----- Print Hamiltonian");
            Console.Write(hamiltonian);
            Console.WriteLine("----- End Print Hamiltonian \n");
            #endregion

            #region Jordan-Wigner representation
            // The Jordan-Wigner encoding converts the Fermion Hamiltonian,
            // expressed in terms of Fermionic operators, to a qubit Hamiltonian,
            // expressed in terms of Pauli matrices. This is an essential step
            // for simulating our constructed Hamiltonians on a qubit quantum
            // computer.
            Console.WriteLine("----- Creating Jordan-Wigner encoding");
            var jordanWignerEncoding = JordanWignerEncoding.Create(hamiltonian);
            Console.WriteLine("----- End Creating Jordan-Wigner encoding \n");
            #endregion

            #region Performing the simulation
            // We are now ready to run a quantum simulation of molecular Hydrogen.
            // We will use this to obtain an estimate of its ground state energy.

            // Here, we make an instance of the simulator used to run our Q# code.
            using (var qsim = new QuantumSimulator())
            {
                // This Jordan-Wigner data structure also contains a representation
                // of the Hamiltonian made for consumption by the Q# algorithms.
                var qSharpData = jordanWignerEncoding.QSharpData();

                // We specify the bits of precision desired in the phase estimation
                // algorithm
                var bits = 7;

                // We specify the step-size of the simulated time-evolution
                var trotterStep = 0.4;

                // Choose the Trotter integrator order
                Int64 trotterOrder = 1;

                // As the quantum algorithm is probabilistic, let us run a few trials.

                // This may be compared to true value of
                Console.WriteLine("Exact molecular Hydrogen ground state energy: -1.137260278.\n");
                Console.WriteLine("----- Performing quantum energy estimation by Trotter simulation algorithm");
                for (int i = 0; i < 5; i++)
                {
                    // EstimateEnergyByTrotterization
                    // Name shold make clear that it does it by trotterized
                    var(phaseEst, energyEst) = GetEnergyByTrotterization.Run(qsim, qSharpData, bits, trotterStep, trotterOrder).Result;

                    Console.WriteLine($"Rep #{i+1}/5: Energy estimate: {energyEst}; Phase estimate: {phaseEst}");
                }
                Console.WriteLine("----- End Performing quantum energy estimation by Trotter simulation algorithm\n");

                Console.WriteLine("----- Performing quantum energy estimation by Qubitization simulation algorithm");
                for (int i = 0; i < 1; i++)
                {
                    // EstimateEnergyByTrotterization
                    // Name shold make clear that it does it by trotterized
                    var(phaseEst, energyEst) = GetEnergyByQubitization.Run(qsim, qSharpData, bits).Result;

                    Console.WriteLine($"Rep #{i+1}/1: Energy estimate: {energyEst}; Phase estimate: {phaseEst}");
                }
                Console.WriteLine("----- End Performing quantum energy estimation by Qubitization simulation algorithm\n");
            }

            Console.WriteLine("Press Enter to continue...");
            if (System.Diagnostics.Debugger.IsAttached)
            {
                Console.ReadLine();
            }
            #endregion
        }
Пример #18
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 Convert Q# Hamiltonian

            #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;
            // }
            using (var qsim = new QuantumSimulator())
            {
                // Simulate.Run(qsim).Wait();
                // Console.WriteLine(arbitrary_test.Run(qsim, data).Result);
                Console.WriteLine(Simulate.Run(qsim, data, 1.0, MOE).Result);
            }
            #endregion
            #region Classical update scheme
            // Determine how to update the starting state using classical methods
            #endregion
        }
Пример #19
0
        static void Main(string[] args)
        {
            // Prompts user whether to run naive eigensolver (QE)
            // or variational eigensolver (VQE)
            // QE will use the ground state provided in Broombridge file (FILENAME, see below)
            // VQE will give the user the option to use the ground state from Broombridge
            // as initial conditions, if not the initial conditions are all zero
            Console.Write("Run QE or VQE? ");
            String runString = Console.ReadLine();

            #region Parameters of Operation
            // filename of the molecule to be emulated
            var FILENAME = "h20_nwchem.yaml";

            // suggested state to include in JW Terms
            var STATE = "|G>";

            // the margin of error to use when approximating the expected value
            // note - our current code currently maxes the number of runs to 50
            // this is to prevent an exponential number of runs required given
            // an arbitrary small margin of error
            // if you'd like to change this parameter, feel free to edit the repeat/until loop
            // in the "FindExpectedValue" method
            var MOE = 0.1;

            #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);

            // JW encoding data to be passed to Q#
            var data = JWEncoding.QSharpData(STATE);

            #endregion
            #region Hybrid Quantum/Classical accelerator

            // Communicate to the user the choice of eigensolver
            if (runString.Equals("VQE"))
            {
                Console.WriteLine("----- Begin VQE Setup");
            }
            else
            {
                Console.WriteLine("----- Begin QE Simulation");
            }

            using (var qsim = new QuantumSimulator())
            {
                // Block to run VQE
                if (runString.Equals("VQE"))
                {
                    string useGroundState;

                    // we begin by asking whether to use the YAML suggested ground or an ansatz
                    Console.Write("Use ground state? (yes or no): ");
                    useGroundState = Console.ReadLine();

                    // extract parameters for use below
                    var statePrepData = data.Item3;
                    var N             = statePrepData.Length;

                    // We'd like to have a method to create an input state given parameters
                    // method to convert optimized parameters, i.e. the
                    // coefficients of the creation/annihilation operators
                    // to JordanWignerInputStates that can be run in the
                    // simulation defined in Q#
                    double convertDoubleArrToJWInputStateArr(double[] x)
                    {
                        var JWInputStateArr = new QArray <JordanWignerInputState>();

                        for (int i = 0; i < N; i++)
                        {
                            var currJWInputState = statePrepData[i];
                            var positions        = currJWInputState.Item2; // registers to apply coefficients
                            JWInputStateArr.Add(new JordanWignerInputState(((x[i], 0.0), positions)));
                        }
                        return(Simulate_Variational.Run(qsim, data, MOE, JWInputStateArr).Result);
                    }

                    // wrapper function which feeds parameters to be optimized to minimize
                    // the output of the simulation of the molecule defined in FILENAME
                    Func <double[], double> Simulate_Wrapper = (double[] x) => convertDoubleArrToJWInputStateArr(x);

                    // create new Nelder-Mead solver on the simulation of the molecule
                    var solver = new NelderMead((int)N, Simulate_Wrapper);

                    // create initial condition vector
                    var initialConds = new double[N];
                    for (int i = 0; i < N; i++)
                    {
                        if (useGroundState.Equals("yes"))
                        {
                            var currJWInputState = statePrepData[i];
                            var groundStateGuess = currJWInputState.Item1;
                            initialConds[i] = groundStateGuess.Item1;
                        }
                        else
                        {
                            initialConds[i] = 0.0;
                        }
                    }

                    Console.WriteLine("----Beginning computational simulation----");

                    // Now, we can minimize it with:
                    bool success = solver.Minimize(initialConds);

                    // And get the solution vector using
                    double[] solution = solver.Solution;

                    // The minimum at this location would be:
                    double minimum = solver.Value;

                    // Communicate VQE results to the user
                    // success indicates wheter the solution converged
                    // solution is the vector of coefficients for the creation/annihilation
                    // operators defined in positions (defined in convertDoubleArrToJWInputStateArr)
                    // minimum is the value of the minimum energy found by VQE
                    Console.WriteLine($"Solution converged: {success}");
                    Console.WriteLine("The solution is: " + String.Join(" ", solution));
                    Console.WriteLine($"The minimum is: {minimum}");
                }
                else
                { // Run QE 5 times
                    Console.WriteLine(Simulate.Run(qsim, data, MOE, 5).Result);
                }
            }
            #endregion
        }
Пример #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
        }
Пример #21
0
        static void Main(string[] args)
        {
            var logger = Logging.LoggerFactory.CreateLogger <Program>();

            // Directory containing integral data generated by Microsoft.
            //Example Liquid data format files

            /*
             * "h2_sto3g_4.dat" // 4 SO
             * "B_sto6g.dat" // 10 SO
             * "Be_sto6g_10.dat" // 10 SO
             * "h2o_sto6g_14.dat" // 14 SO
             * "h2s_sto6g_22.dat" // 22 SO
             * "co2_sto3g_30.dat" // 30 SO
             * "co2_p321_54.dat" // 54 SO
             * "fe2s2_sto3g.dat" // 110 SO
             * "nitrogenase_tzvp_54.dat" // 108 SO
             */

            string LiquidRoot     = @"..\IntegralData\Liquid\";
            string LiquidFilename = "h2_sto3g_4.dat";
            // Number of electrons. This must be specified for the liquid format.
            var LiquidElectrons = 2;

            // Read Hamiltonian terms from file.
            // Stopwatch for logging time to process file.
            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();

            // For loading data in the format consumed by Liquid.
            logger.LogInformation($"Processing {LiquidFilename}");
            var generalHamiltonian = FermionHamiltonian.LoadFromLiquid($@"{LiquidRoot}\{LiquidFilename}").Single();

            generalHamiltonian.NElectrons = LiquidElectrons;
            logger.LogInformation($"Liquid Load took {stopWatch.ElapsedMilliseconds}ms");
            stopWatch.Restart();

            // For loading data in the YAML format.
            //string YAMLRoot = @"..\IntegralData\YAML\";
            //string YAMLFilename = "lih_sto-3g_0.800_int.yaml";
            //var generalHamiltonian = FermionHamiltonian.LoadFromYAML($@"{YAMLRoot}\{YAMLFilename}").Single();
            //logger.LogInformation($"YAML Load took {stopWatch.ElapsedMilliseconds}ms");
            //stopWatch.Restart();

            // Logs spin orbital data in Logger.Message.
            generalHamiltonian.LogSpinOrbitals();

            // Process Hamiltonitn to obtain Jordan-Wigner representation.
            // Comment on what an evolutionset is.
            var jordanWignerEncoding = JordanWignerEncoding.Create(generalHamiltonian);

            // Logs Jordan-Wigner representation data in Logger.Message.
            jordanWignerEncoding.LogSpinOrbitals();

            logger.LogInformation("End read file");

            // We begin by making an instance of the simulator that we will use to run our Q# code.
            using (var qsim = new QuantumSimulator())
            {
                // Converts jordanWignerEncoding into format consumable by Q#.
                var qSharpData = jordanWignerEncoding.QSharpData();

                #region Calling into Q#
                // Bits of precision in phase estimation.
                var bits = 10;

                // Repetitions to find minimum energy.
                var reps = 5;

                // Run phase estimation simulation using Jordan-Wigner Trotterization.
                var runJW = true;

                // Trotter step size.
                var trotterStep = .4;

                // Run phase estimation simulation using Jordan-Wigner Trotterization with optimzied circuit.
                var runJWOptimized = true;

                // Run phase estimation simulation using Jordan-Wigner qubitization.
                var runJWQubitization = true;

                if (runJW)
                {
                    for (int i = 0; i < reps; i++)
                    {
                        var(phaseEst, energyEst) = TrotterEstimateEnergy.Run(qsim, qSharpData, bits, trotterStep).Result;
                        logger.LogInformation($"Trotter simulation. phase: {phaseEst}; energy {energyEst}");
                    }
                }
                if (runJWOptimized)
                {
                    for (int i = 0; i < reps; i++)
                    {
                        var(phaseEst, energyEst) = OptimizedTrotterEstimateEnergy.Run(qsim, qSharpData, bits - 1, trotterStep).Result;
                        logger.LogInformation($"Optimized Trotter simulation. phase {phaseEst}; energy {energyEst}");
                    }
                }
                if (runJWQubitization)
                {
                    for (int i = 0; i < reps; i++)
                    {
                        var(phaseEst, energyEst) = QubitizationEstimateEnergy.Run(qsim, qSharpData, bits - 2).Result;
                        logger.LogInformation($"Qubitization simulation. phase: {phaseEst}; energy {energyEst}");
                    }
                }

                #endregion
            }


            if (System.Diagnostics.Debugger.IsAttached)
            {
                System.Console.ReadLine();
            }
        }
Пример #22
0
        static void Main(string[] args)
        {
            //////////////////////////////////////////////////////////////////////////
            // Introduction //////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////////////////////

            // In this example, we will estimate the ground state energy of
            // 1D Hubbard Hamiltonian using the quantum chemistry library.

            // The 1D Hubbard model has `n` sites. Let `i` be the site index,
            // `s` = 1,0 be the spin index, where 0 is up and 1 is down, `t` be the
            // hopping coefficient, `u` the repulsion coefficient, and aᵢₛ the fermionic
            // annihilation operator on the fermion indexed by `(i,s)`. The Hamiltonian
            // of this model is
            //
            //     H ≔ - t Σᵢ (a†ᵢₛ aᵢ₊₁ₛ + a†ᵢ₊₁ₛ aᵢₛ) + u Σᵢ a†ᵢ₀ a†ᵢ₁ aᵢ₁ aᵢ₀
            //
            // Note that we use closed boundary conditions.

            #region Building the Hubbard Hamiltonian through orbital integrals

            var t      = 0.2; // hopping coefficient
            var u      = 1.0; // repulsion coefficient
            var nSites = 6;   // number of sites;
            // Construct Hubbard Hamiltonian
            var hubbardHamiltonian = new FermionHamiltonian(nOrbitals: nSites, nElectrons: nSites);

            foreach (var i in Enumerable.Range(0, nSites))
            {
                hubbardHamiltonian.AddFermionTerm(new OrbitalIntegral(new[] { i, (i + 1) % nSites }, -t));
                hubbardHamiltonian.AddFermionTerm(new OrbitalIntegral(new[] { i, i, i, i }, u));
            }

            // Let us verify that both Hamiltonians are identical
            hubbardHamiltonian.SortAndAccumulate();
            Console.WriteLine($"Hubbard Hamiltonian:");
            Console.WriteLine(hubbardHamiltonian + "\n");
            #endregion


            #region Estimating energies by simulating quantum phase estimation
            var jordanWignerEncoding = JordanWignerEncoding.Create(hubbardHamiltonian);
            var qSharpData           = jordanWignerEncoding.QSharpData();

            Console.WriteLine($"Estimate Hubbard Hamiltonian energy:");
            // Bits of precision in phase estimation.
            var bits = 7;

            // Repetitions to find minimum energy.
            var reps = 5;

            // Trotter step size
            var trotterStep = 0.5;

            using (var qsim = new QuantumSimulator())
            {
                for (int i = 0; i < reps; i++)
                {
                    // EstimateEnergyByTrotterization
                    // Name shold make clear that it does it by trotterized
                    var(phaseEst, energyEst) = GetEnergy.Run(qsim, qSharpData, bits, trotterStep).Result;

                    Console.WriteLine($"Rep #{i}: Energy estimate: {energyEst}; Phase estimate: {phaseEst}");
                }
            }

            Console.WriteLine("Press Enter to continue...");
            if (System.Diagnostics.Debugger.IsAttached)
            {
                Console.ReadLine();
            }
            #endregion
        }