<jupyter_start><jupyter_text>Copyright 2020 The OpenFermion Developers<jupyter_code>#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.<jupyter_output><empty_output><jupyter_text>Introduction to FQE       View on QuantumAI        Run in Google Colab        View source on GitHub        Download notebook   OpenFermion-FQE is an emulator for quantum computing specialized for simulations of Fermionic many-body problems, where FQE stands for 'Fermionic quantum emulator.' By focusing on Fermionic physics, OpenFermion-FQE realizes far more efficient emulation of quantum computing than generic quantum emulators such as Cirq, both in computation and memory costs; the speed-up and improved memory footprint originate from the use of the spin and number symmetries as well as highly optimized special algorithms.The examples of the problems that can be simulated by OpenFermion-FQE include those in molecular electronic structure, condensed matter physics, and nuclear physics.The initial version of OpenFermion-FQE has been developed in collaboration between [QSimulate](https://qsimulate.com)  and [Google Quantum AI](https://quantumai.google/). The source code is found in the GitHub repository (https://github.com/quantumlib/OpenFermion-FQE).This tutorial will describe the data structures and conventions of the library.<jupyter_code>try:
    import fqe
except ImportError:
    !pip install fqe --quiet
import fqe
import numpy as np<jupyter_output><empty_output><jupyter_text>The FQE Wavefunction The `Wavefunction` is an interface to the objects that hold the actual wavefunction data.  As mentioned, the wavefunction is partitioned into sectors with fixed particle and $Sz$ quantum number.  This partitioning information is the necessary information for initializing a `Wavefunction` object.  As an example, we consider initializing a wavefunction with four spatial orbitals, four electrons, and different $Sz$ expectation values.  The `Wavefunction` object takes a list of these sectors `[[n_electrons, sz, n_orbits]]`.<jupyter_code>wfn = fqe.Wavefunction([[4, 4, 4], [4, 2, 4], [4, 0, 4], [4, -2, 4], [4, -4, 4]])<jupyter_output><empty_output><jupyter_text>This command initializes a wavefunction with the following block structure: ![Image of wf sectors](./wf_init_sectors.png) Each sector corresponds to a set of bit strings $$\vert I \rangle = \vert I_{\alpha}I_{\beta}\rangle$$ that encode a fixed particle number and fixed $Sz$ expectation. The coefficients associated with the bitstrings in these sectors are formed into matrices.  This helps with efficient vectorized computations. The row-index of the array corresponds to the $\alpha$ spin-orbital number occupation index and the column-index corresponds to the $\beta$-strings.  The `Wavefunction` object provides tools to access sectors or perform basic mathematical operations on this *vector*.    Methods to initialize wavefunctions FQE wavefunctions can be initialized by calling the constructor directly.<jupyter_code>wfn_fqe = fqe.Wavefunction([[2, -2, 4]], broken=None)<jupyter_output><empty_output><jupyter_text>When wavefunctions are first created, they are initialized to empty values. We can see this by printing out the wavefunction.<jupyter_code>wfn_fqe.print_wfn()<jupyter_output><empty_output><jupyter_text>To set the values of a wavefunction, we can use the `set_wfn` method with a provided `strategy`.<jupyter_code>wfn_fqe.set_wfn(strategy="hartree-fock")
wfn_fqe.print_wfn()<jupyter_output><empty_output><jupyter_text>Users can access the wavefunction through the `get_sector` method.  This returns the entire matrix of data representing the specified sector of the wavefunction.  For example, we can grab the sector corresponding to $n = 2$ and $sz = -2$ by doing the following.<jupyter_code>interesting_states = wfn_fqe.get_coeff((2, -2))
print(interesting_states)<jupyter_output><empty_output><jupyter_text>Other than the `Wavefunction` constructor, several utility methods are available to initialize wavefunctions. The function `fqe.get_wavefunction` builds a wavefunction with definite particle number and spin.<jupyter_code>wfn_fqe = fqe.get_wavefunction(4, -2, 10)<jupyter_output><empty_output><jupyter_text>The function `fqe.get_wavefunction_multiple` constructs multiple wavefunctions with different particle number, spin, and orbital number.<jupyter_code>wfn_fqe1, wfn_fqe2 = fqe.get_wavefunction_multiple([[4, 0, 10], [5, -5, 10]])<jupyter_output><empty_output><jupyter_text>There are also functions like `fqe.get_number_conserving_wavefunction` and  `fqe.get_spin_conserving_wavefunction` to get number or spin conserving wavefunctions, respectively.<jupyter_code># Get a spin conserving wavefunction.
spin_conserving_wfn = fqe.get_spin_conserving_wavefunction(2, 4)

# Get a number conserving wavefunction.
number_conserving_wfn = fqe.get_number_conserving_wavefunction(2, 4)<jupyter_output><empty_output><jupyter_text>Conversions between FQE and Cirq wavefunction representations Wavefunctions on $n$ qubits in Cirq are represented by Numpy arrays with $2^n$ amplitudes.<jupyter_code>nqubits = 4

cirq_wfn = np.random.rand(2**nqubits) + 1.0j * np.random.rand(2**nqubits)
cirq_wfn /= np.linalg.norm(cirq_wfn)

print("Cirq wavefunction:")
print(*cirq_wfn, sep="\n")<jupyter_output><empty_output><jupyter_text>To convert from this representation to the FQE representation, the function `fqe.from_cirq` can be used.<jupyter_code>fqe_wfn = fqe.from_cirq(cirq_wfn, thresh=0.0001)
fqe_wfn.print_wfn()<jupyter_output><empty_output><jupyter_text>> *Note*: The `thresh` argument is the value below which amplitudes are considered zero. We can convert back to the Cirq representation using `fqe._to_cirq`.<jupyter_code>cirq_wfn_from_fqe = fqe.to_cirq(fqe_wfn)

print("Cirq wavefunction from FQE:")
print(*cirq_wfn_from_fqe, sep="\n")
assert np.allclose(cirq_wfn_from_fqe, cirq_wfn)<jupyter_output><empty_output><jupyter_text>An important thing to note in these conversions is the ordering of the $\alpha$ and $\beta$ strings in the converted wavefunctions.  The FQE uses the OpenFermion convention of interleaved $\alpha$ and $\beta$ orbitals.  Thus when converting to Cirq we first convert each bitstring into an OpenFermion operator and then call normal ordering.  Printing and saving wavefunctions Printing is currently available as alpha beta strings followed by the coefficient as well as orbital occupation representation.<jupyter_code>print('String formatting')
fqe_wfn.print_wfn(fmt='str')
print('Occupation formatting')
fqe_wfn.print_wfn(fmt='occ')<jupyter_output><empty_output><jupyter_text>Wavefunctions can also be saved to disk using the `save` method which takes a filename and optional path.  Action on Wavefunctions: Fermionic algebra operations and their unitaries on the state FermionOperators can be directly passed in to create a new wavefunction based on application of the operators.  The FermionOperators are parsed according to the interleaved $\alpha$ $\beta$ indexing of the spin-orbitals.  This means that odd index FermionOperators correspond to $\beta$-spin orbitals and even are $\alpha$-spin orbitals.  Sharp Edge:The user must be careful to not break the symmetry of the wavefunction.  If a request to apply an operator to a state takes the wavefunction outside of the specified symmetry sector the FQE will not execute the command.  Effectively, the FQE requires the user to have more knowledge of what type of operations their `Wavefunction` object can support.<jupyter_code>from openfermion import FermionOperator, hermitian_conjugated

ops = FermionOperator('2^ 0', 1.2)

new_wfn = fqe_wfn.apply(ops + hermitian_conjugated(ops))<jupyter_output><empty_output><jupyter_text>Unitary operations Any simulator backend must be able to perform unitary evolution on a state.  The FQE accomplishes this by implementing code for evolving a state via the action of a unitary generated by fermionic generators.  Given a fermion operator $g$, the unitary $$e^{-i (g + g^{\dagger})}$$can be applied to the state.  It can be shown that this evolution operator can be rewritten as $$e^{-i(g + g^{\dagger})\epsilon } = \cos\left(\epsilon\right) \mathbb{I}_{s}(gg^{\dagger}) +  \cos\left(\epsilon\right) \mathbb{I}_{s}(g^{\dagger}g) - i\sin\left(\epsilon\right) \left(g + g^{\dagger}\right) \left[\mathbb{I}_{s}(gg^{\dagger}) + \mathbb{I}_{s}(g^{\dagger}g)\right] + \mathbb{I}_{!s}$$The $\mathbb{I}_{!s}$ is for setting the coefficients of the unitary that are not in the subspace $\mathcal{H}_{s} \subset \mathcal{H}$ where $gg^{\dagger}$ is 0.   The user can specify a fermionic monomial in OpenFermion and use the `time_evolve` method of the `Wavefunction` object to call the evolution. All the rules for preserving symmetries must be maintained as before.<jupyter_code>i, j, theta = 0, 1, np.pi / 3
op = (FermionOperator(((2 * i, 1), (2 * j, 0)), coefficient=-1j * theta) + 
      FermionOperator(((2 * j, 1), (2 * i, 0)), coefficient=1j * theta))

new_wfn = fqe_wfn.time_evolve(1.0, op)

new_wfn.print_wfn()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.08570829840737636, 'fraction_numerical': 0.00827745180217938, 'mean_word_length': 5.896676300578035, 'pattern_counts': {'":': 0, '<': 65, '<?xml version=': 0, '>': 66, 'https://': 4, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '16', 'dir': 'jupyter-structured-clean-dedup', 'id': '623903', 'license': 'Apache-2.0', 'n_tokens_mistral': 2936, 'n_tokens_neox': 2781, 'n_words': 1058, 'path': 'docs/fqe/guide/introduction.ipynb', 'repo_name': 'mkeshita/OpenFermion', 'size': '9544'}