예제 #1
0
        static void SimulateHubbardHamiltonianTest()
        {
            //////////////////////////////////////////////////////////////////////////
            // 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 hubbardOrbitalIntegralHamiltonian = new OrbitalIntegralHamiltonian();

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

            // Create fermion representation of Hamiltonian
            // In this case, we use the spin-orbital to integer
            // indexing convention `x = orbitalIdx + spin * nSites`; as it
            // minimizes the length of Jordan–Wigner strings
            var hubbardFermionHamiltonian = hubbardOrbitalIntegralHamiltonian.ToFermionHamiltonian(IndexConvention.HalfUp);

            #endregion


            #region Estimating energies by simulating quantum phase estimation
            // Create Jordan–Wigner representation of Hamiltonian
            var jordanWignerEncoding = hubbardFermionHamiltonian.ToPauliHamiltonian();

            // Create data structure to pass to QSharp.
            var qSharpData = jordanWignerEncoding.ToQSharpFormat().Pad();

            Console.WriteLine($"Estimate Hubbard Hamiltonian energy:");

            #endregion
        }
        // Checks if any errors occur while building Hamiltonian for both index conventions.
        public void BuildFermionHamiltonian()
        {
            var sourceHamiltonian = new OrbitalIntegralHamiltonian();

            sourceHamiltonian.Add(orbitalIntegrals);

            var targetHamiltonian0 = sourceHamiltonian.ToFermionHamiltonian(IndexConvention.HalfUp);

            var targetHamiltonian1 = sourceHamiltonian.ToFermionHamiltonian(IndexConvention.UpDown);
        }
예제 #3
0
파일: Program.cs 프로젝트: ziqi-ma/Quantum
        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 hubbardOrbitalIntegralHamiltonian = new OrbitalIntegralHamiltonian();

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

            // Create fermion representation of Hamiltonian
            // In this case, we use the spin-orbital to integer
            // indexing convention `x = orbitalIdx + spin * nSites`; as it
            // minimizes the length of Jordan–Wigner strings
            var hubbardFermionHamiltonian = hubbardOrbitalIntegralHamiltonian.ToFermionHamiltonian(IndexConvention.HalfUp);

            #endregion


            #region Estimating energies by simulating quantum phase estimation
            // Create Jordan–Wigner representation of Hamiltonian
            var jordanWignerEncoding = hubbardFermionHamiltonian.ToPauliHamiltonian();

            // Create data structure to pass to QSharp.
            var qSharpData = jordanWignerEncoding.ToQSharpFormat().Pad();

            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 should 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
        }
        void BuildOrbitalIntegralHamiltonian()
        {
            var hamiltonian = new OrbitalIntegralHamiltonian();

            hamiltonian.Add(orbitalIntegrals);
        }
예제 #5
0
        /// <summary>
        ///     Deserializes an FCIDUMP-formatted problem description.
        /// </summary>
        /// <param name="reader">A stream for reading FCIDUMP data.</param>
        /// <returns>
        ///      An electronic structure problem deserialized from the file.
        /// </returns>
        public static IEnumerable <ElectronicStructureProblem> Deserialize(TextReader reader)
        {
            // FCIDUMP files begin with a FORTRAN-formatted namelist, delimited
            // by &FCI and &END. We start by extracting that namelist.
            var allText = reader.ReadToEnd();
            var lines   = Regex.Split(allText, "\r\n|\r|\n");

            if (lines == null)
            {
                throw new IOException("Expected a non-empty FCIDUMP file.");
            }
            var header = System.String.Join("\n", lines.TakeWhile(line => line.Trim() != "&END")).Trim();
            var body   = lines !.SkipWhile(line => line.Trim() != "&END").Skip(1).ToList();

            // Make sure that the header starts with &FCI, as expected.
            if (!header.StartsWith("&FCI"))
            {
                throw new IOException("FCIDUMP file did not start with \"&FCI\" as expected.");
            }

            // Split out the &FCI and &END lines, turn the rest into a dictionary of namelist items.
            var namelist = Regex.Matches(
                header
                .Replace("&FCI", "")
                .Replace("&END", ""),
                pattern: "\\s*(?<identifier>\\w+)\\s*=\\s*(?<value>[^=]+),\\s*"
                )
                           .ToDictionary(
                match => match.Groups["identifier"].Value,
                match => match.Groups["value"].Value
                );

            var hamiltonian = new OrbitalIntegralHamiltonian();
            var arrayData   = body
                              .Select(line => line.Trim())
                              .Where(line => line.Length > 0)
                              .Select(
                line => line.Split(" ", StringSplitOptions.RemoveEmptyEntries)
                )
                              .Select(
                row => (
                    Double.Parse(row[0]),
                    row[1..].Select(Int32.Parse).Where(idx => idx != 0).ToZeroBasedIndices()
                    )
                );

            var(coulomb, _) = arrayData.Where(item => item.Item2.Length == 0).Single();
            hamiltonian.Add(arrayData
                            .Where(row => row.Item2.Length > 0)
                            .SelectMaybe(
                                row => row.Item2.Length % 2 == 0
                           ? new OrbitalIntegral(
                                    row.Item2, row.Item1, OrbitalIntegral.Convention.Mulliken
                                    ).ToCanonicalForm()
                           : null
                                )
                            .Distinct()
                            );

            // The identity term in deserialized Hamiltonians is the sum of the
            // Coloumb repulsion and the energy offset. Since only the former
            // exists in FCIDUMP, we set the identity term accordingly.
            hamiltonian.Add(new OrbitalIntegral(), coulomb);

            return(new List <ElectronicStructureProblem>
            {
                new ElectronicStructureProblem
                {
                    EnergyOffset = 0.0.WithUnits("hartree"),
                    CoulombRepulsion = coulomb.WithUnits("hartree"),
                    Metadata = new Dictionary <string, object>
                    {
                        ["Comment"] = "Imported from FCIDUMP"
                    },
                    NElectrons = Int32.Parse(namelist["NELEC"]),
                    NOrbitals = Int32.Parse(namelist["NORB"]),
                    OrbitalIntegralHamiltonian = hamiltonian
                }
            });
        }
예제 #6
0
        internal static ElectronicStructureProblem DeserializeSingleProblem(string line)
        {
            var problem = new ElectronicStructureProblem()
            {
                Metadata = new Dictionary <string, object>()
            };

            var regexMiscellaneous = new Regex(@"((info=(?<info>[^\s]*)))");
            var regexnuc           = new Regex(@"nuc=(?<nuc>-?\s*\d*.\d*)");
            var regexPQ            = new Regex(@"(^|\s+)(?<p>\d+),(?<q>\d+)\D*=\s*(?<coeff>-?\s*\d*.\d*)e?(?<exponent>-?\d*)");
            var regexPQRS          = new Regex(@"(^|\s+)(?<p>\d+)\D+(?<q>\d+)\D+(?<r>\d+)\D+(?<s>\d+)\D*=\s*(?<coeff>-?\s*\d*.\d*)e?(?<exponent>-?\d*)");

            double coulombRepulsion = 0.0;
            var    fileHIJTerms     = new Dictionary <int[], double>(new Extensions.ArrayEqualityComparer <int>());
            var    fileHIJKLTerms   = new Dictionary <int[], double>(new Extensions.ArrayEqualityComparer <int>());
            var    hamiltonian      = new OrbitalIntegralHamiltonian();

            var nOrbitals = 0L;

            Match stringMisc = regexMiscellaneous.Match(line);

            if (stringMisc.Success)
            {
                problem.Metadata["misc_info"] = stringMisc.Groups["info"].ToString();
            }


            Match stringnuc = regexnuc.Match(line);

            if (stringnuc.Success)
            {
                coulombRepulsion = double.Parse(stringnuc.Groups["nuc"].ToString()).ToDoubleCoeff();
                hamiltonian.Add(TermType.OrbitalIntegral.Identity, new OrbitalIntegral(), coulombRepulsion);
            }
            foreach (Match stringPQ in regexPQ.Matches(line))
            {
                if (stringPQ.Success)
                {
                    var p              = int.Parse(stringPQ.Groups["p"].ToString());
                    var q              = int.Parse(stringPQ.Groups["q"].ToString());
                    var coeff          = double.Parse(stringPQ.Groups["coeff"].ToString());
                    var exponentString = stringPQ.Groups["exponent"].ToString();
                    var exponent       = 0.0;
                    if (exponentString != "")
                    {
                        exponent = double.Parse(stringPQ.Groups["exponent"].ToString());
                    }
                    nOrbitals = new long[] { nOrbitals, p + 1, q + 1 }.Max();

                    var orbitalIntegral          = new OrbitalIntegral(new int[] { p, q }, coeff * (10.0).Pow(exponent));
                    var orbitalIntegralCanonical = orbitalIntegral.ToCanonicalForm();


                    if (fileHIJTerms.ContainsKey(orbitalIntegralCanonical.OrbitalIndices))
                    {
                        // Check consistency
                        if (fileHIJTerms[orbitalIntegralCanonical.OrbitalIndices] != orbitalIntegral.Coefficient)
                        {
                            // Consistency check failed.
                            throw new System.NotSupportedException(
                                      $"fileHPQTerm Consistency check fail. " +
                                      $"Orbital integral {orbitalIntegral} coefficient {orbitalIntegral.Coefficient}" +
                                      $"does not match recorded {orbitalIntegralCanonical} coefficient {fileHIJTerms[orbitalIntegral.OrbitalIndices]}.");
                        }
                        else
                        {
                            // Consistency check passed.
                        }
                    }
                    else
                    {
                        fileHIJTerms.Add(orbitalIntegralCanonical.OrbitalIndices, orbitalIntegralCanonical.Coefficient);
                    }
                }
            }
            foreach (Match stringPQRS in regexPQRS.Matches(line))
            {
                if (stringPQRS.Success)
                {
                    var p              = int.Parse(stringPQRS.Groups["p"].ToString());
                    var q              = int.Parse(stringPQRS.Groups["q"].ToString());
                    var r              = int.Parse(stringPQRS.Groups["r"].ToString());
                    var s              = int.Parse(stringPQRS.Groups["s"].ToString());
                    var coeff          = double.Parse(stringPQRS.Groups["coeff"].ToString());
                    var exponentString = stringPQRS.Groups["exponent"].ToString();
                    var exponent       = 0.0;
                    if (exponentString != "")
                    {
                        exponent = double.Parse(stringPQRS.Groups["exponent"].ToString());
                    }
                    nOrbitals = new long[] { nOrbitals, p + 1, q + 1, r + 1, s + 1 }.Max();

                    var orbitalIntegral          = new OrbitalIntegral(new int[] { p, q, r, s }, coeff * (10.0).Pow(exponent));
                    var orbitalIntegralCanonical = orbitalIntegral.ToCanonicalForm();


                    if (fileHIJKLTerms.ContainsKey(orbitalIntegralCanonical.OrbitalIndices))
                    {
                        // Check consistency
                        if (fileHIJKLTerms[orbitalIntegralCanonical.OrbitalIndices] != orbitalIntegral.Coefficient)
                        {
                            // Consistency check failed.
                            throw new System.NotSupportedException(
                                      $"fileHPQRSTerm Consistency check fail. " +
                                      $"Orbital integral {orbitalIntegral.OrbitalIndices} coefficient {orbitalIntegral.Coefficient}" +
                                      $"does not match recorded {orbitalIntegralCanonical.OrbitalIndices} coefficient {fileHIJKLTerms[orbitalIntegral.OrbitalIndices]}.");
                        }
                        else
                        {
                            // Consistency check passed.
                        }
                    }
                    else
                    {
                        fileHIJKLTerms.Add(orbitalIntegralCanonical.OrbitalIndices, orbitalIntegralCanonical.Coefficient);
                    }
                }
            }

            hamiltonian.Add(fileHIJTerms.Select(o => new OrbitalIntegral(o.Key, o.Value)).ToList());

            hamiltonian.Add(fileHIJKLTerms.Select(o => new OrbitalIntegral(o.Key, o.Value)).ToList());

            problem.OrbitalIntegralHamiltonian = hamiltonian;
            problem.NOrbitals        = System.Convert.ToInt32(nOrbitals);
            problem.CoulombRepulsion = coulombRepulsion.WithUnits("hartree");

            return(problem);
        }