quantumlib / openfermion Goto Github PK
View Code? Open in Web Editor NEWThe electronic structure package for quantum computers.
License: Apache License 2.0
The electronic structure package for quantum computers.
License: Apache License 2.0
Currently, installing OpenFermion on Windows with Python 3 (have not checked on Py2) fails due to a decoding error in the opening of README.rst
for the long description:
Traceback (most recent call last):
File "setup.py", line 22, in <module>
long_description = open('README.rst').read()
File "C:\Users\J44364\AppData\Local\Continuum\Anaconda3\lib\encodings\cp1252.p
y", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 5418: cha
racter maps to <undefined>
this is fixed by adding encoding="utf-8"
as an argument to open
.
Currently, the rotate_basis
method of the PolynomialTensor class only rotates the (1, 0) and (1, 1, 0, 0) tensors, i.e., the tensors corresponding to terms of the form a^\dagger_p a_q and a^\dagger_p a^\dagger_q a_r a_s. Ideally, it would correctly rotate all tensors that are stored in the PolynomialTensor instance.
The rotation of the (1, 0) tensor is straightforward (just a basis change for a matrix), and the implementation of the rotation for the (1, 1, 0, 0) tensor is described in equations (22) and (23) of the release paper. The task for this issue is to work out how to generalize these expressions to arbitrary tensors and implement it in the rotate_basis
method.
In the code for jordan_wigner
, InteractionOperators are handled with the helper function jordan_wigner_interaction_op
, rather than simply mapping to a FermionOperator first and then transforming with the existing code. This is supposedly for the sake of speed. However, I found that doing it this way on a Hubbard Hamiltonian is apparently around 10 times slower. Does anyone have an idea why? Was this actually tested for speed? Should we just ditch the helper function?
In [1]: from openfermion.hamiltonians import fermi_hubbard
In [2]: from openfermion.transforms import jordan_wigner, get_fermion_operator, get_interaction_operator
In [3]: hubbard_model = fermi_hubbard(4, 4, 1., 4., 2., 2.)
In [4]: iop = get_interaction_operator(hubbard_model)
In [5]: def jordan_wigner_iop(iop):
...: ferm_op = get_fermion_operator(iop)
...: qubit_op = jordan_wigner(ferm_op)
...: return qubit_op
...:
In [6]: %timeit -n 3 -r 7 qubit_op_1 = jordan_wigner_iop(iop)
250 ms ± 5.32 ms per loop (mean ± std. dev. of 7 runs, 3 loops each)
In [7]: %timeit -n 3 -r 7 qubit_op_2 = jordan_wigner(iop)
2.33 s ± 96.4 ms per loop (mean ± std. dev. of 7 runs, 3 loops each)
@TariniHardikar @kanavsetia @hsim13372 @jarrodmcc
Now that we have the alpha version of our cloud library up and running (thanks again to @Spaceenter who did a lot of work on this) we should start to add some more benchmarks. It would be nice to see a few different diatomics as well as atoms on the periodic table, the alkane series, and some triatomic energy surfaces for important molecules like water and ammonia. Some hydrogen lattices might be nice too. We should also try to get some larger systems including calculations in bigger basis sets and canonical benchmarks like the chromium dimer.
Again, part of the idea behind this library is to provide a set of canonical benchmarks so that we can compare calculations more easily in future research papers and part of the idea is to provide a precomputed molecular database for users who aren't experienced enough with electronic structure packages to converge the SCF calculations. Thus, I think this thread would also be an appropriate place for people to suggest molecular benchmarks they'd like to see added to the cloud library.
I think it would be nice to keep a list of publications that use OpenFermion in some way. Perhaps when people publish a new paper they can mention it here and give a small description. Since I have put out several papers using OpenFermion I will start us off. Maybe at some later point when (and if) we make an OpenFermion website other than GitHub, we can publish a nicer list of these papers.
is it possible to provide in the documentation a simple example of using this lib to compute
what is the current state of Schroedinger's cat using various circuits, etc versus random binary 0 or 1?
then if Alice and Bob are separated by a huge distance, 10 million light years. Alice wants to transport the cat's status to Bob. the current example uses transport. how does Alice transmit the information without breaking entanglement? how would simulate breaking? or creating entanglement? how do you know or calculate how long the coherence will last before noise overwhelms the system?
if Bob has to wait 10 million years for an answer, the answer doesn't matter, the cat, Alice and Bob will be dead long before the information arrives.
Schemes such as Dynamical Mean-Field Theory (DMFT) or Density Matrix Embedding Theory (DMET), to name just two ideas from a larger family, allow one study the properties of a much larger system by simulating a smaller "impurity" system that is coupled to a bath. Usually there is some iterative self-consistent procedure involved in computing the impurity and bath Hamiltonian.
Since these procedures are routinely used in the context of simulating fermionic systems (sometimes on a quantum computer), such routines are essential to eventual incorporate into OpenFermion. Here are some papers discussing these ideas:
https://arxiv.org/abs/1510.03859
https://arxiv.org/abs/1610.06910
https://arxiv.org/abs/1603.08443
https://arxiv.org/abs/1508.04328
Consider this thread a place to discuss how we should proceed with incorporating such routines into OpenFermion.
Hello OpenFermion developers
I have the code like
#!/usr/bin/env python3
from openfermion.hamiltonians import MolecularData
from openfermion.transforms import get_fermion_operator, get_sparse_operator, jordan_wigner
from openfermion.utils import get_ground_state
import numpy
import scipy
from scipy.sparse.linalg import eigsh
from scipy.linalg import eigh
# Load saved file for H.
geometry = [('Be', (0., 0., 0.))]
basis = 'cc-pVDZ'
multiplicity = 1
# Set Hamiltonian parameters.
active_space_start = 0
active_space_stop = 6
# Generate and populate instance of MolecularData.
molecule = MolecularData(geometry, basis, multiplicity, description="Be")
molecule.load()
# Get the Hamiltonian in an active space.
molecular_hamiltonian = molecule.get_molecular_hamiltonian(
occupied_indices=range(active_space_start),
active_indices=range(active_space_start, active_space_stop)
)
# Map operator to fermions and qubits.
fermion_hamiltonian = get_fermion_operator(molecular_hamiltonian)
qubit_hamiltonian = jordan_wigner(fermion_hamiltonian)
qubit_hamiltonian.compress()
print('The Jordan-Wigner Hamiltonian in canonical basis follows:\n{}'.format(qubit_hamiltonian))
# Get sparse operator and ground state energy.
sparse_hamiltonian = get_sparse_operator(qubit_hamiltonian).todense()
if True:
energy, state = eigh(sparse_hamiltonian)
else:
energy, state = eigsh(sparse_hamiltonian, 2, which='SA', maxiter=1e7)
print('Ground state energy before rotation is {} Hartree.\n'.format(energy[0]))
where eigsh branch always produce SIGSEGV while eigh always gave me reasonable eigenvectors.
what can be the problem of use eigsh?
my scipy version is 1.0.0
Best Vladimir.
I've been looking over PolynomialTensor
after seeing some PRs touch it, and had a few questions. I'm not very familiar with the class, so I think one of them might be a misunderstanding, but the others appear to be problems that are a) not sufficiently tested and b) could give errors in the code.
My questions have to do with several places where a TypeError
is raised, or tensors are considered unequal, if self.n_body_tensors.keys() != other.n_body_tensors.keys()
in https://github.com/quantumlib/OpenFermion/blob/master/src/openfermion/ops/_polynomial_tensor.py.
The questions I have are
keys()
doesn't guarantees order in its output, so I don't think these checks are particularly meaningful to begin with (they should at least use set(x.keys())
for comparison - if that's what we really want),self
but not in other
with the corresponding value in self
within EQ_TOLERANCE
of zero, the tensors should be equal, not unequal (shouldn't they?),TypeError
says that arguments are the wrong type, not that something else is wrong with them. So TypeError is not the right error to be raising here. But as in 2. I don't think this condition should lead to an error at all.Thoughts?
Some functions in hamiltonians/._hubbard
, hamiltonians/._mean_field_dwave
, hamiltonians/._special_operators
, and utils/_sparse_tools.py
have keyword arguments up_map
and down_map
to set the indexing scheme for spin; i.e., whether up spins map to even indices or to lower indices. #218 introduced this feature to the MolecularData structure, using a different method, opting to have a string rather than a function to indicate the indexing scheme. I think the latter method is more user-friendly and we should change the other functions to use it. That's the task for this issue.
@ncrubin are you okay with this? Or do you think we need the flexibility to choose arbitrary mappings? I figure if there are other useful mappings we can support those as additional options.
I'll add that if we go forward with this, I think the possible values for the keyword argument spin_indexing
should actually be even
or lower
, where the word describes the up spin indices.
We'd like to come up with a logo for OpenFermion. Among other things, if we get a good logo, the odds of eventually making OpenFermion schwag increases dramatically. We can probably get some professional assistance in actually drawing up the logo but it would help to crowd source some concepts for the design. Perhaps the logo should be a stylized way of writing OpenFermion with some symbol. For instance, look at the PySCF GitHub. It would be nice to replace the big "OpenFermion" letters with something more flashy.
Any logo should at least convey that the package has something to do with electrons. Ideally, the logo would also suggest some connection to quantum computing. One idea is that we could draw up a Bloch sphere (like this one) where the circumference (dotted in the one I linked to) is one of those Bohr model electron orbital/rings that everyone associates with electrons (like those in the PySCF logo). Any other ideas?
I have a FermionOperator, and I'd like to make the assumption that some of the orbitals are always empty and others are always full. (As I understand it, this is similar to the active space functionality in MolecularData
.) My question is, what's the best way to do this?
What I'm thinking of doing is implementing two methods for FermionOperator
, assume_occupied(index)
and assume_unoccupied(index)
, that will remove the ladder operators that act on a given orbital and multiply the coefficients for the corresponding terms by 0, +1, or -1 as appropriate. I'd also need to implement a prune()
method for SymbolicOperator
that determines which indices don't appear in any terms and then renumbers the indices accordingly.
The idea is that
FermionOperator('1.0 [4^ 5 6]').assume_occupied(5).prune()
would yield -1.0 [0^ 1]
.
Does this seem like a reasonable way to go?
The InteractionOperator class provides a convenient matrix represention of fermionic operators that conserve particle number and spin. However, there is another class of operators that I'd like a convenient matrix representation for: general (not necessarily particle-number-conserving) quadratic Hamiltonians.
There are several ways one could represent such Hamiltonians, and I think the most convenient (for me, right now) is in the Majorana basis:
H = i/2 * s^T * A * s + constant
where s is the vector of Majorana operators and A is a real antisymmetric (2n) x (2n) matrix, where n is the number of sites.
I propose that we create a data structure similar to InteractionOperator, which stores the matrix A and the constant. Maybe we can call it QuadraticMajoranaOp. Actually, I already wrote some code for this, but I figured I would ask for people's thoughts before spending more time cleaning it up.
I haven't thought much about whether it would be better to have a more general data structure.
As we expand the molecule library that is available in the cloud, we should develop an automated test for pulling those files down and running some basic sanity checks. For example it might be useful to attempt loading each of the required fields to verify none of the data was corrupted, and also load the 1- and 2-electron integrals as well as the orbitals, and verify that the Hartree-Fock energy is consistent with the rest of the file.
I want to add some code which optionally requires CVXOPT and GLPK (Gnu Linear Programming Kit).
The code will also work with scipy but scipy supports only the simplex method of linear programming, which is very slow for my application. The code will use scipy by default and raise an exception saying that CVXOPT and GLPK are not installed if one wants to use that but don't have these installed.
We should not add CVXOPT and GLPK to the requirements file (for PyPI to see) because GLPK might be difficult to install automatically for some systems. But we'll need to have it on travis so I can run my tests.
Does this seem like a reasonable plan?
For instance, it is very clear that I am the only person who made commits on this pull request, mghibaudi/OpenFermion-ProjectQ#14
And yet the CLA bot seems to think multiple people are committing.
Explained in this 2005 paper by Verstraete and Cirac, it is possible to transform local fermion Hamiltonians on a lattice in D dimensions into local spin Hamiltonians on a lattice in D dimensions. Myself and others I've spoken with recently, including @dabacon, would love to play around with this mapping. So it would be great to have it implemented in OpenFermion. This project would be a great introduction to OpenFermion but requires that one has enough physics background to get through the paper.
Implementing variational algorithms requires some classical outer loop routine which takes as input a collection of measurements together with a specification of the variational parameters and outputs new variational parameters which should be run by the circuit.
Several papers have explored different optimizers including (https://arxiv.org/abs/1704.05018) which focuses on simultaneous perturbation stochastic approximation and (https://arxiv.org/abs/1701.02691) which explores and compares several different optimizers.
But one can imagine these schemes getting even much more sophisticated. For instance, one might start the procedure by using the 2-RDM obtained via CISD as a Bayesian prior on what the measurement outcomes should be. In such an approach, the routine should not only output what variational parameters to try next, but also which terms to measure next (as certain terms will lower the variance of the estimator of the energy more than others according to the prior).
In a real device there is parameter drift and fluctuations in T1 (which affects measurements) which suggests that one should perhaps employ some sort of Kalman filtering as well.
If anyone wants to talk about these ideas or suggest new modules along these lines, consider this an open thread.
For some reason coveralls has a habit of commenting multiple times on pull requests, even when there is no new activity. I've used coveralls before but never seen this problem outside of our recently configured repos. The main reason I care is because I "watch" the repo and receive emails updates on all activity. It is somewhat obnoxious to have coveralls emailing me two or three times for most PRs. Here are a couple examples:
#3
#5
I made a virtualenv and did this
pip install --pre openfermion
and got
...
Cleaning up...
Command python setup.py egg_info failed with error code 1 in /usr/local/google/home/danielsank/.virtualenvs/openfermion/build/h5py
Traceback (most recent call last):
File "/usr/local/google/home/danielsank/.virtualenvs/openfermion/bin/pip", line 11, in <module>
sys.exit(main())
File "/usr/local/google/home/danielsank/.virtualenvs/openfermion/local/lib/python2.7/site-packages/pip/__init__.py", line 185, in main
return command.main(cmd_args)
File "/usr/local/google/home/danielsank/.virtualenvs/openfermion/local/lib/python2.7/site-packages/pip/basecommand.py", line 161, in main
text = '\n'.join(complete_log)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 72: ordinal not in range(128)
This was with python 2.7.6 and pip 1.5.4.
As I have done for myself, feel free to link your name to a personal webpage.
Currently, the save_operator
function in utils/_operator_utils.py
saves Fermion and QubitOperators using the data serialization module marshal
. I think it's desirable to save these objects in a human-readable format, like JSON. What do people think? This would probably best be implemented after resolving issue #43.
Also, I'm wondering why marshal
was chosen rather than the more standard pickle
or cPickle
.
Unfortunately Travis is not automatically running on open pull requests anymore. We are not aware of any straightforward way to force Travis to run. Until this problem is fixed, we cannot merge any new PRs. Thus, this is a very high priority issue.
This is a very broad topic, and one that is also long overdue for including in OpenFermion.
There are several interesting papers about reducing the number of qubits in second quantized Hamiltonians. The usual idea is that second quantization does not leverage good quantum numbers such as particle number and having definite spin, and thus wastes qubits. Here are a few papers that introduce valuable ideas along these lines. These papers outline ideas that would be straightforward to implement in OpenFermion:
https://arxiv.org/abs/1510.04048
https://arxiv.org/abs/1701.08213
https://arxiv.org/abs/1712.07067
In a very early version of this library (known then as OpenPQRS), we had a parent class from which both QubitOperator and FermionOperator inherited. This was an obvious design choice because the classes are extremely similar and differ in only a few places. However, when making FermiLib (the predecessor to OpenFermion) we decided that the QubitOperator class should be embedded in ProjectQ and so we removed this inheritance structure. But in OpenFermion, we have again moved both QubitOperator and FermionOperator into the same library.
There are many advantages to having both of these classes inherit from the same parent. For one thing, we'd need many fewer tests to cover the same functionality. More importantly, there are a variety of methods I would like to add to these classes but it would be annoying to need to add essentially the same function to both. For instance, I would like to add the abs method to both classes which returns the L1 norm of the operators by summing the absolute value of the coefficients. This should be added to the parent class. I think the parent should be called SymbolicOperator.
This is not an easy change it will likely take significant effort. However, fortunately, one will likely only need to change the files which define the QubitOperator and FermionOperator and test them since all other parts of the library will still import QubitOperator and FermionOperator the same.
I think it would be great to distribute OpenFermion with some more preloaded molecule files. Of course, one of the great things about OpenFermion is that one can use our Psi4 and PySCF plugins to generate these files; however, some people might not want to do that. For instance, OpenFermion runs on Windows but Psi4 and PySCF do not. But even if you can run the plugins, a database of preloaded molecules may serve many purposes.
For instance, suppose that one were to start by looking up the equilibrium geometries of the following common small molecules and ions (all under 20 qubits in the minimal basis): H2O, CH4, NH3, CH3(-), NH2, N2, H2, O2, F2, CO, OH(-), LiH, BeH2, BeO, HCl. One could then perform SCF/MP2/CISD/CCSD/FCI calculations on these molecules and save the MolecularData object. One could name the molecules things like "equilibrium_ammonia" (or maybe even something more systematic). One should look up the geometries using the NIST database: http://webbook.nist.gov/
There might be some finicky things one needs to do to get the SCF to converge for these systems. You'll also need to make sure you are running the calculations at the correct spin-multiplicity. But once these molecules are available it would be very convenient for users to load them. Even if you do use the plugins, it is a pain to look up the geometry information every time you want to test something out. But perhaps most importantly, by distributing a set of molecules in the code like this, we create a standard library, one which people can refer to in papers without any ambiguity. For instance, one could report how well a variational algorithm performs across the OpenFermion-small_molecules data set. Such standards should be put into a separate folder. Of course, we'd need to make sure there aren't so many files that an unfortunate amount of memory is needed just to download OpenFermion! Perhaps somehow the molecule files can be downloaded separately.
I think this is a good job for a chemist who is looking to get involved with the project. Of course, another amazing feature would be code that automatically grabs equilibrium geometries from the NIST database!
Now that we have a prototype logo, it is time to start thinking about schwag. While we're not committing to anything at this point, I think it would be nice to have some sort of schwag made in time for APS March Meeting. We do have some sort of a budget for this.
What kind of schwag would people like to see? Shirts? Fleeces? Hoodies? It would be great if people could make design suggestions (e.g. OpenFermion logo in black / orange on the front right breast of a grey t-shirt and "from openfermion import *" on the back). It would be even more awesome if people could suggest very make / models and give a link.
Let's try to limit suggestions to items under $150, keeping in mind that the cheaper the item, the more likely we are to be able to pull it off. Anyone is welcome to comment on this thread.
I believe there is an inconsistency in how basis transformations of PolynomialTensor are treated between the code and the paper. I think it applies to the implementation of both one- and two-body basis changes, but I'll explain it for one-body. In Eq. (21) of the paper, the molecular orbital functions are transformed by the matrix U. This corresponds to a transformation of the creation operators by the same matrix U. In other words, the column vector of creation operators (a^\dagger_1, ..., a^\dagger_N)^T is multiplied on the left by U. Let's assume that U is real and call it R instead. Then equivalently, the row vector of creation operators (a^\dagger_1, ..., a^\dagger_N) is multiplied on the right by R^T. This implies that for a one-body tensor of type (1, 0), i.e., with terms of the form a^\dagger_p a_q, the one-body tensor matrix M should be transformed as M' = R M R^T. We put R on the left side which will cancel out the R^T which transforms the creation operators; similarly, the R^T on the right side cancels out the R which transforms the annihilation operators. However, in the current implementation of one_body_basis_change
, the transformation is M' = R^T M R. Does this make sense to anyone? I'm happy to give a more detailed (prettier) explanation with LaTeX. If I'm correct, then I propose that we change the code to be consistent with the paper. Perhaps this can be resolved at the same time as #86 .
There are many reasons why one might want to study the physics of bosonic systems. Such is not the focus of OpenFermion but some limited functionalities for simulating bosons, or systems of interacting bosons and fermions, should be possible to incorporate. For instance, one might want to simulate models of molecules interacting with light which involve electrons and photons. There are also many reasons why one might wish to study systems with electron-phonon coupling, etc. Coupling fermionic systems to a harmonic bath is also common in the context of open quantum systems. If this is a direction which interests anyone, we should discuss implementation ideas here.
One thought is to first make a BosonOperator class. This would be much less onerous if (#43) is first closed, since then one can create the BosonOperator through inheritance. If one restricts the number of bosons which may occupy a single mode then it is also straightforward to provide transforms which map the bosonic operators to QubitOperators. In order to study models of fermion-boson coupling one would need a class that can represent mixed operators. That too will require some thought and discussion. An excellent solution is not immediately obvious.
All of our repos have demo jupyter notebooks in the examples folders. Very often it happens that somebody makes a change to the code that breaks these notebooks because there are no tests. We want some sort of test that just makes sure the jupyter notebook was able to run without errors.
We have decided that we will move away from the master/develop style git flow and just have a master branch. The master branch should always be a stable build but every once and a while if there is a lot of development we will tag a new release, bump the version number, and update PyPI.
Craig, can you take care of this? The idea should be to somehow delete master and then rename develop as master without losing any of the commit history in develop. Can it be done?
The README recommends the --user
flag for pip install. This is generally a very good idea, but it seems like an attempt to avoid the generally accepted "right" way to isolate installed python packages from the system python, namely with virtualenv
.
It seems that the Hamiltonians produced by plane_wave_external_potential
and dual_basis_external_potential
are non-Hermitian if the number of grid subdivisions is even and any atoms are not at the origin. For example, the program below returns False:
from openfermion.utils import Grid, is_hermitian
from openfermion.transforms import get_sparse_operator
from openfermion.hamiltonians import plane_wave_external_potential
grid = Grid(1, 4, 4.0)
geometry = [('H', (0.1,))]
H = plane_wave_external_potential(grid, geometry, True)
sparse = get_sparse_operator(H)
print(is_hermitian(sparse))
I think this is due to the "dualling" (meaning that momentum subtraction is done modulo the maximum momentum). When I remove the dualling in plane_wave_external_potential
, then the operator is Hermitian.
Does anyone have any thoughts on this? From https://arxiv.org/abs/1706.00023 it sounds like it might be ok to go without dualling for the plane wave basis, but that dualling is important for the dual basis. (For the systems I'm looking at, having an even number of subdivisions would be very convenient!)
hello,
OSX 10.12.6, clang-6.0, python2.7,numpy 1.14.0, scipy 1.0.0
installed openfermion from github repo as well as the plugins.
running the basic example
from openfermion.ops import FermionOperator, hermitian_conjugated
from openfermion.transforms import jordan_wigner, bravyi_kitaev
from openfermion.utils import eigenspectrum
# Initialize an operator.
fermion_operator = FermionOperator('2^ 0', 3.17)
fermion_operator += hermitian_conjugated(fermion_operator)
print(fermion_operator)
the following warning happens
.../h5py/init.py:36: FutureWarning: Conversion of the second argument of issubdtype from float
to np.floating
is deprecated. In future, it will be treated as np.float64 == np.dtype(float).type
.
can someone confirm this solution is correct?
3.17 [2^ 0] +
3.17 [0^ 2]
We would like to add a function to FermionOperator class that reorders the orbitals as
0,1,2,3,4,5,... -> 0,2,4,...,1,3,5...
(from updownupdown... to upupupupdowndowndown)
two ways we can do this:
just writing a function that takes in a FermionOperator and spits out a reordered FermionOperator. which is what I did to begin with but @msteudtner raised the following concern:
the FermionOperator does not know its order inherently and a user may end up adding/multiplying two differently ordered FermionOperators 🙀
we can make it a class method and let the FermionOperator know its order. This way it can check if its being added/multiplied with a another FermionOperator with the same order and if not - raises an error.
This seems to be the right way of doing it to me but it would require overloading basic class methods. (unless there is some magic trick we can pull off 🎆)
Documentation is up and working well for OpenFermion but we don't have the sphinx docs or readthedocs up for our three plugins.
When running tests in OpenFermion locally, one of the tests in utils/ gives a sparse efficiency warning. This should be addressed.
Whenever we cut a new release we need to write a list of the new features. I also forget what all the new features are by that time. We should keep a running list of new features in this "issue". Whenever you fix a bug or add a feature, just mention it here and when we cut the release we'll include what your write in the release notes. I'll start with a couple of points.
flake8 testing of https://github.com/quantumlib/OpenFermion on Python 3.6.3
$ flake8 . --count --select=E901,E999,F821,F822,F823 --show-source --statistics
./src/openfermion/ops/_interaction_rdm.py:53:28: F821 undefined name 'unpack_spatial_rdm'
one_rdm, two_rdm = unpack_spatial_rdm(one_rdm_a, one_rdm_b,
^
./src/openfermion/ops/_interaction_rdm.py:56:20: F821 undefined name 'constant'
return cls(constant, one_rdm, two_rdm)
^
Hello all
get_n_alpha_electrons() & get_n_beta_electrons() functions gives wrong results
https://github.com/quantumlib/OpenFermion/blob/master/src/openfermion/hamiltonians/_molecular_data.py#L734
Multiplicity is a property that describes an atom’s or molecule’s electronic structure. The total number of alpha and beta electrons in an atom/molecule are needed to calculate multiplicity.
Before calculating multiplicity you first calculate total spin (S).
S = (# of alpha electrons)(+1/2) + (# of beta electrons)(-1/2)
Multiplicity = |2S| + 1
So right answer should be:
alpha electrons = (# total electrons + (Multiplicity - 1)) / 2
beta electrons = (# total electrons - (Multiplicity - 1)) / 2
PS:
also output value should be an INTEGER type, to fit parse_psi4_ccsd_amplitudes() input parameters type in
https://github.com/quantumlib/OpenFermion-Psi4/blob/master/openfermionpsi4/_psi4_template#L230
PPS:
actually it gives for ground state of C atom (mult=3) 5.0 alpha and 1.0 beta electrons.
best Vladimir.
Pull request #221 starts a comprehensive list of features which we will merge once completed (help on that welcome, especially if making additions which explain your contribution). This should help raise awareness about the many functionalities currently implemented in OpenFermion.
However, the best way to show people a new feature is to write an example. I believe these are best demonstrated through ipython notebooks. Currently we have one huge demo but I think we should creating smaller, more specific demos. For instance, perhaps we should have a demo called "transforms" which discusses the many transforms currently implemented. Perhaps we should have a demo called "models" which discusses how to generate different Hamiltonian models. Any help in this regard would be appreciated.
In the readme, I'd do something like this
blah blah
blah blah
Perturbative gadgets are techniques for manipulating representations of qubit Hamiltonians which would be very useful in some contexts. They are particularly interesting in the context of quantum simulation and multiple papers have explored their application to electronic structure specifically. One can use perturative gadgets to reduce the many-body order of a QubitHamiltonian, or change the connectivity graph, or change the types of terms in the Hamiltonian, in a way that leaves the low energy portion of the "gadgetized" Hamiltonian spectra invariant. A few relevant papers in this area would be:
For electronic structure
https://arxiv.org/abs/1311.3967
https://arxiv.org/abs/1706.03637
Various other papers with important gadget constructions
https://arxiv.org/abs/quant-ph/0406180
https://arxiv.org/abs/quant-ph/0504050
https://arxiv.org/abs/0802.1874
https://arxiv.org/abs/1311.2555
https://arxiv.org/abs/1311.3161
https://arxiv.org/abs/1709.02705
Any code to implement these gadgets would be a welcome addition to OpenFermion. @yudongcao , a member of the OpenFermion community, is an expert in this topic in case people have questions.
As discussed in #122 it would be helpful if sums of FermionOperators and QubitOperators could be initialized from their string representation so that
my_fermion_operator - FermionOperator(str(my_fermion_operator)) = 0 and
my_qubit_operator - QubitOperator(str(qubit_operator)) = 0.
This should be easy for a beginner to implement.
There are tools such as VMD and Avogadro which are designed to visualize molecular orbitals and charge densities. Thus, one should be able to use these tools to visualize the 1-RDM output from molecular simulations in OpenFermion or its plugins. Such visualizations would steal the show at many of our quantum computing conferences. Imagine how awesome it would be to visualize how the wavefunction of a molecule is changing during the course of variational optimization in a VQE experiment! What is needed them in some plugin or module (together with usage instructions) which allows OpenFermion data structures to be rendered in open source visualization packages.
Several times now I have wanted to implement code which performs a BCH expansion on operator data structures in OpenFermion such as QubitOperator, FermionOperator, and sparse matrices. I started to write some code for this:
def bch_expand(x, y, order):
"""Compute log[e^x e^y] using the Baker-Campbell-Hausdorff formula
Args:
x: An operator for which multiplication and addition are supported.
For instance, a QubitOperator, FermionOperator or numpy array.
y: The same type as x.
order(int): The order to truncate the BCH expansions. Currently
function goes up to only third order.
Returns:
z: The truncated BCH operator.
Raises:
ValueError: operator x is not same type as operator y.
ValueError: invalid order parameter.
ValueError: order exceeds maximum order supported.
"""
# Initialize.
max_order = 4
if type(x) != type(y):
raise ValueError('Operator x is not same type as operator y.')
elif (not isinstance(order, int)) or order < 0:
raise ValueError('Invalid order parameter.')
# Zeroth order.
z = x + y
# First order.
if order > 0:
z += commutator(x, y) / 2.
# Second order.
if order > 1:
z += commutator(x, commutator(x, y)) / 12.
z += commutator(y, commutator(y, x)) / 12.
# Third order.
if order > 2:
z -= commutator(y, commutator(x, commutator(x, y))) / 24.
# Fourth order.
if order > 3:
z -= commutator(
y, commutator(y, commutator(y, commutator(y, x)))) / 720.
z -= commutator(
x, commutator(x, commutator(x, commutator(x, y)))) / 720.
z += commutator(
x, commutator(y, commutator(y, commutator(y, x)))) / 360.
z += commutator(
y, commutator(x, commutator(x, commutator(x, y)))) / 360.
z += commutator(
y, commutator(x, commutator(y, commutator(x, y)))) / 120.
z += commutator(
x, commutator(y, commutator(x, commutator(y, x)))) / 120.
# Return.
if order > max_order:
raise ValueError('Order exceeds maximum order supported.')
else:
return z
But I am thinking that what we really want to do is to implement the form derived by Dynkin in 1947 which would enable us to compute the series to arbitrary order without hard coding expression. Coding this up is a little involved but it is a good starter project for somebody. Some thought should also go into optimizing the performance of such code and also making good tests.
The utils folder is getting a bit bloated. I suggest that we move all code that is specialized to generating model Hamiltonians (i.e. hubbard, jellium, plane_wave, meanfield and possible molecular_data) to a different folder called "models". This will require changing imports in a lot of the code and also in docs/examples.rst and in the demo ipython notebook.
I'm working on the file ops/_quadratic_hamiltonian.py
. In there, I add the line
from openfermion.utils._slater_determinants import swap_columns, swap_rows
This causes the tests in the hamiltonians
folder to fail; i.e., when I run pytest hamiltonians/
, I get
________________ ERROR collecting src/openfermion/hamiltonians/_chemical_series_test.py ________________
ImportError while importing test module '/home/kjs/Projects/OpenFermion/src/openfermion/hamiltonians/_chemical_series_test.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
hamiltonians/__init__.py:13: in <module>
from ._chemical_series import (make_atomic_ring,
hamiltonians/_chemical_series.py:18: in <module>
from openfermion.hamiltonians._molecular_data import (MolecularData,
hamiltonians/_molecular_data.py:21: in <module>
from openfermion.ops import InteractionOperator, InteractionRDM
ops/__init__.py:23: in <module>
from ._quadratic_hamiltonian import QuadraticHamiltonian
ops/_quadratic_hamiltonian.py:22: in <module>
from openfermion.utils._slater_determinants import swap_columns, swap_rows
utils/__init__.py:39: in <module>
from ._trotter_error import error_bound, error_operator
utils/_trotter_error.py:20: in <module>
from openfermion.hamiltonians import MolecularData
E ImportError: cannot import name 'MolecularData'
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
It seems that there is a circular dependency
MolecularData -> ops -> utils -> MolecularData
and any file in the ops
folder which imports anything from utils
will cause this error. What is the best way to deal with it?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.