### Install FermiNet and Dependencies Source: https://github.com/google-deepmind/ferminet/blob/main/README.md Installs FermiNet and its dependencies using pip within a virtual environment. ```shell virtualenv ~/venv/ferminet source ~/venv/ferminet/bin/activate pip install -e . ``` -------------------------------- ### Install JAX with CUDA Support Source: https://github.com/google-deepmind/ferminet/blob/main/README.md Installs JAX with CUDA support, ensuring the jaxlib version matches the CUDA installation. ```shell pip install --upgrade jax jaxlib==0.1.57+cuda110 -f https://storage.googleapis.com/jax-releases/jax_releases.html ``` -------------------------------- ### Set Training Parameters Source: https://github.com/google-deepmind/ferminet/blob/main/README.md Configure batch size and pre-training iterations before starting the training process. ```python cfg.batch_size = 256 cfg.pretrain.iterations = 100 train.train(cfg) ``` -------------------------------- ### Install Testing Dependencies and Run Tests Source: https://github.com/google-deepmind/ferminet/blob/main/README.md Installs testing dependencies and runs tests using pytest. ```shell pip install -e '.[testing]' python -m pytest ``` -------------------------------- ### Get Demixed Results for Energy and Observables Source: https://github.com/google-deepmind/ferminet/blob/main/ferminet/notebooks/excited_states_analysis.ipynb Demixes states from energy and observable matrices to compute standard deviations. Requires energy matrix and observable matrices as input. ```python def get_results(energy_matrix_and_var, *observable_matrices_and_var): """Given energy matrix and observable matrices, demix the states and compute the std deviations.""" energy_mat, energy_var = energy_matrix_and_var energy, demix = np.linalg.eig(energy_mat) demix = demix[:, np.argsort(energy)] energy = np.sort(energy) energy_std = get_demixed_std(energy_matrix_and_var, demix) observables = [np.linalg.inv(demix) @ mv[0] @ demix for mv in observable_matrices_and_var] observable_std = [get_demixed_std(mv, demix) for mv in observable_matrices_and_var] return energy, energy_std, observables, observable_std ``` -------------------------------- ### Run FermiNet with Command-Line Flags Source: https://github.com/google-deepmind/ferminet/blob/main/README.md Executes FermiNet using command-line flags to specify configuration files, system atoms, batch size, and pretraining iterations. ```shell ferminet --config ferminet/configs/atom.py --config.system.atom Li --config.batch_size 256 --config.pretrain.iterations 100 ``` -------------------------------- ### Create a PySCF Molecule Object Source: https://github.com/google-deepmind/ferminet/blob/main/README.md Demonstrates how to create a PySCF Molecule object for representing atomic systems. ```python from pyscf import gto mol = gto.Mole() mol.build( atom = 'H 0 0 1; H 0 0 -1', basis = 'sto-3g', unit='bohr') ``` -------------------------------- ### Define H2 Molecule and Training Parameters in a Script Source: https://github.com/google-deepmind/ferminet/blob/main/README.md Sets up the H2 molecule and training parameters within a Python script for direct execution. ```python import sys from absl import logging from ferminet.utils import system from ferminet import base_config from ferminet import train # Optional, for also printing training progress to STDOUT. # If running a script, you can also just use the --alsologtostderr flag. logging.get_absl_handler().python_handler.stream = sys.stdout logging.set_verbosity(logging.INFO) # Define H2 molecule cfg = base_config.default() cfg.system.electrons = (1,1) # (alpha electrons, beta electrons) cfg.system.molecule = [system.Atom('H', (0, 0, -1)), system.Atom('H', (0, 0, 1))] # Set training parameters cfg.batch_size = 256 cfg.pretrain.iterations = 100 train.train(cfg) ``` -------------------------------- ### Run FermiNet using Python Script Source: https://github.com/google-deepmind/ferminet/blob/main/README.md Executes FermiNet by directly calling the main Python script with command-line flags for configuration. ```shell python3 ferminet/main.py --config ferminet/configs/atom.py --config.system.atom Li --config.batch_size 256 --config.pretrain.iterations 100 ``` -------------------------------- ### Import Libraries for Ferminet Analysis Source: https://github.com/google-deepmind/ferminet/blob/main/ferminet/notebooks/excited_states_analysis.ipynb Imports necessary libraries including numpy for numerical operations, matplotlib for plotting, os for operating system interactions, and tqdm for progress bars. ```python import numpy as np import matplotlib.pyplot as plt import os from tqdm import tqdm ``` -------------------------------- ### Configure H2 Molecule in a Python File Source: https://github.com/google-deepmind/ferminet/blob/main/README.md Defines a configuration for the H2 molecule in a Python file, setting electron counts, atomic positions, batch size, and pretraining iterations. ```python from ferminet import base_config from ferminet.utils import system # Settings in a config files are loaded by executing the the get_config # function. def get_config(): # Get default options. cfg = base_config.default() # Set up molecule cfg.system.electrons = (1,1) cfg.system.molecule = [system.Atom('H', (0, 0, -1)), system.Atom('H', (0, 0, 1))] # Set training hyperparameters cfg.batch_size = 256 cfg.pretrain.iterations = 100 return cfg ``` -------------------------------- ### Plotting Transition Dipole Moments Source: https://github.com/google-deepmind/ferminet/blob/main/ferminet/notebooks/excited_states_analysis.ipynb Visualizes the true and estimated transition dipole moments using imshow. Ensure matplotlib is imported as plt. ```python fig, ax = plt.subplots(1, 2) ax[0].imshow(dipole.transpose((1, 2, 0))) ax[0].set_title('True') ax[1].imshow(observables[1].transpose((1, 2, 0))) ax[1].set_title('Estimated') ``` -------------------------------- ### Generate Synthetic Excited State Data Source: https://github.com/google-deepmind/ferminet/blob/main/ferminet/notebooks/excited_states_analysis.ipynb Creates synthetic data for excited state energies, spin magnitudes, dipole moments, and density matrices. This data mimics the format produced by Ferminet's training and inference code, serving as input for analysis. ```python t = 10_000 # number of steps k = 4 # number of excited states m = 5 # number of electrons eps = 1e-2 # noise level noisy = lambda x: x + eps * np.random.randn(*x.shape) energy = np.sort(np.random.randn(k) - 10) # energies of each state energy_mat = np.diag(energy) s2 = np.zeros((k, k)) # spin magnitude of each state # first and third excited state is triplet s2[1, 1] = 2.0 s2[3, 3] = 2.0 # dipole moments, including transition dipole moments dipole = np.zeros((3, k, k)) dipole[:, 1, 1] = np.random.randn(3) # first excited state is polar dipole[:, 0, 2] = np.random.randn(3) # ground to second excited state is bright dipole[:, 2, 0] = dipole[:, 0, 2] # transition dipole moments are symmetric # one-electron reduced density matrix basis = 10 # number of elements of the basis set density_matrix = np.zeros((2, nbasis, nbasis, k, k)) # first dimension is alpha/beta spin for i in range(k): density_matrix[:, :m, :m, i, i] = np.eye(m) # occupy first 5 orbitals to start # first state: promote highest alpha electron into lowest unoccupied orbital density_matrix[0, m-1, m-1, 1, 1] = 0 density_matrix[0, m, m, 1, 1] = 1 # second state: promote highest beta electron into lowest unoccupied orbital density_matrix[1, m-1, m-1, 2, 2] = 0 density_matrix[1, m, m, 2, 2] = 1 # third state: double excitation of both alpha and beta electron density_matrix[0, m-1, m-1, 3, 3] = 0 density_matrix[0, m, m, 3, 3] = 1 density_matrix[1, m-1, m-1, 3, 3] = 0 density_matrix[1, m, m, 3, 3] = 1 # mix the states together randomly mix = np.random.randn(k, k) energy_mat = mix @ energy_mat @ np.linalg.inv(mix) s2_mat = mix @ s2 @ np.linalg.inv(mix) dipole_mat = mix @ dipole @ np.linalg.inv(mix) density_mat = mix @ density_matrix @ np.linalg.inv(mix) ``` -------------------------------- ### Load and Process Data from File Source: https://github.com/google-deepmind/ferminet/blob/main/ferminet/notebooks/excited_states_analysis.ipynb Loads arrays from a specified file, calculating the average and variance. Supports loading all data or a specified tail of the data. ```python def load_data(fname, tail=0): """Load the arrays from a file and take the average and variance. Args: fname: Name of file to load. tail: If 0, load all arrays in the file. If n !=0, load the last n arrays. Returns: Average value of the arrays in the file and the variance. """ with open(fname, "rb") as f: fsize = os.fstat(f.fileno()).st_size data = np.load(f) var_data = second_mom(data) arr_size = f.tell() fsize -= fsize % arr_size # cut off any half-saved data if tail: n = tail f.seek(fsize - (tail + 1) * arr_size) data = np.load(f) var_data = second_mom(data) else: n = fsize // arr_size for _ in tqdm(range(n-1)): out = np.load(f) data += out var_data += second_mom(out) mean_data = data / n return mean_data, var_data / n ** 2 - second_mom(mean_data) / n # divide by n an extra time because variance goes down as 1/n with sample size ``` -------------------------------- ### Visualizing Oscillator Strengths Source: https://github.com/google-deepmind/ferminet/blob/main/ferminet/notebooks/excited_states_analysis.ipynb Displays the calculated oscillator strengths using imshow. This plot highlights transitions from the ground state to excited states. ```python plt.imshow(f) # the only bright transition is from the ground state to 2nd excited state ``` -------------------------------- ### Configure FermiNet with a PySCF Molecule Source: https://github.com/google-deepmind/ferminet/blob/main/README.md Configures FermiNet to use a pre-existing PySCF Molecule object for system definition. ```python from ferminet import base_config from ferminet import train # Add H2 molecule cfg = base_config.default() cfg.system.pyscf_mol = mol ``` -------------------------------- ### Load Synthetic Data for Analysis Source: https://github.com/google-deepmind/ferminet/blob/main/ferminet/notebooks/excited_states_analysis.ipynb Loads synthetic data for energy, spin, dipole, and density matrices using the load_data function. Specifies to load the last 1000 entries. ```python energy_mat_and_var = load_data("energy_matrix.npy", tail=1000) s2_mat_and_var = load_data("s2_matrix.npy", tail=1000) dipole_mat_and_var = load_data("dipole_matrix.npy", tail=1000) density_mat_and_var = load_data("density_matrix.npy", tail=1000) ``` -------------------------------- ### Visualize Spin Magnitude (S2) Matrix Source: https://github.com/google-deepmind/ferminet/blob/main/ferminet/notebooks/excited_states_analysis.ipynb Displays the true and estimated spin magnitude (S2) matrices using imshow. Expected to show diagonal entries for alternating singlet and triplet states. ```python fig, ax = plt.subplots(1, 2) ax[0].imshow(s2) ax[0].set_title('True') ax[1].imshow(observables[0]) ax[1].set_title('Estimated') ``` -------------------------------- ### Perform Excited States Analysis Source: https://github.com/google-deepmind/ferminet/blob/main/ferminet/notebooks/excited_states_analysis.ipynb Computes the estimated energies, standard deviations, and observable properties using the get_results function with loaded synthetic data. ```python energy_est, energy_std, observables, observable_std = get_results(energy_mat_and_var, s2_mat_and_var, dipole_mat_and_var, density_mat_and_var) ``` -------------------------------- ### Save Synthetic Data to .npy Files Source: https://github.com/google-deepmind/ferminet/blob/main/ferminet/notebooks/excited_states_analysis.ipynb Appends noisy versions of the generated energy, spin magnitude, dipole moment, and density matrices to their respective `.npy` files. This simulates the iterative saving process during a calculation. ```python with ( open("energy_matrix.npy", "ab") as energy_file, open("s2_matrix.npy", "ab") as s2_file, open("dipole_matrix.npy", "ab") as dipole_file, open("density_matrix.npy", "ab") as density_file ): for _ in tqdm(range(t)): np.save(energy_file, noisy(energy_mat)) np.save(s2_file, noisy(s2_mat)) np.save(dipole_file, noisy(dipole_mat)) np.save(density_file, noisy(density_mat)) ``` -------------------------------- ### Visualizing Estimated Density Matrix Source: https://github.com/google-deepmind/ferminet/blob/main/ferminet/notebooks/excited_states_analysis.ipynb Plots the estimated one-electron reduced density matrix, allowing comparison with the true value. Assumes k is defined. ```python fig, ax = plt.subplots(2, k) for i in range(2): for j in range(k): ax[i, j].imshow(observables[2][i, :, :, j, j]) ``` -------------------------------- ### Display Estimated Energy Values Source: https://github.com/google-deepmind/ferminet/blob/main/ferminet/notebooks/excited_states_analysis.ipynb Prints the estimated energy values obtained from the analysis. ```python energy_est ``` -------------------------------- ### Calculating Oscillator Strengths Source: https://github.com/google-deepmind/ferminet/blob/main/ferminet/notebooks/excited_states_analysis.ipynb Computes oscillator strengths using energy differences and the corrected transition dipole moments. Requires numpy as np. ```python f = 2/3 * (energy_est[:, None] - energy_est[None, :]) * np.sum(dipole.transpose((1, 2, 0)) * dipole.transpose((2, 1, 0)), axis=-1) ``` -------------------------------- ### Visualizing True Density Matrix Source: https://github.com/google-deepmind/ferminet/blob/main/ferminet/notebooks/excited_states_analysis.ipynb Plots the true one-electron reduced density matrix for alpha and beta electrons across different basis set elements. Assumes k is defined. ```python fig, ax = plt.subplots(2, k) for i in range(2): for j in range(k): ax[i, j].imshow(density_matrix[i, :, :, j, j]) ``` -------------------------------- ### Plotting Corrected Transition Dipole Moments Source: https://github.com/google-deepmind/ferminet/blob/main/ferminet/notebooks/excited_states_analysis.ipynb Visualizes the true and estimated transition dipole moments after multiplying by their transpose to correct off-diagonal terms. Ensure matplotlib is imported as plt. ```python fig, ax = plt.subplots(1, 2) ax[0].imshow(dipole.transpose((1, 2, 0)) * dipole.transpose((2, 1, 0))) ax[0].set_title('True') ax[1].imshow(observables[1].transpose((1, 2, 0)) * observables[1].transpose((2, 1, 0))) ax[1].set_title('Estimated') ``` -------------------------------- ### Check Energy Estimate Against Standard Deviation Source: https://github.com/google-deepmind/ferminet/blob/main/ferminet/notebooks/excited_states_analysis.ipynb Verifies if the true energy values are within two standard deviations of the estimated energy values. ```python # check if the recovered energy is within two standard deviations of the estimated energy np.all(np.abs(energy - energy_est) < 2 * np.diag(energy_std)) ``` -------------------------------- ### Calculate Second Moment of Data Source: https://github.com/google-deepmind/ferminet/blob/main/ferminet/notebooks/excited_states_analysis.ipynb Computes the outer product along the last two dimensions of an input array. Used for variance calculations. ```python def second_mom(x): """Take the outer product along the last two dimensions.""" shape = x.shape x = x.reshape(*shape[:-2], shape[-2] * shape[-1]) return x[..., :, None] * x[..., None, :] ``` -------------------------------- ### Calculate Demixed Standard Deviation Source: https://github.com/google-deepmind/ferminet/blob/main/ferminet/notebooks/excited_states_analysis.ipynb Computes the standard deviation per variable from raw covariance matrices using a demixing transformation. ```python def get_demixed_std(matrix_and_var, demix): """Get the standard deviation per variable from the raw covariance.""" mat, var = matrix_and_var vv = np.kron(np.linalg.inv(demix), demix.T) cov_demixed = vv @ var @ vv.T var_demixed = diag(cov_demixed).reshape(*mat.shape) return np.sqrt(var_demixed) ``` -------------------------------- ### Extract Diagonal Elements Source: https://github.com/google-deepmind/ferminet/blob/main/ferminet/notebooks/excited_states_analysis.ipynb Extracts the diagonal elements along the last two axes of a square matrix. Assumes the last two dimensions are equal. ```python def diag(x): """Take diagonal along last two axes.""" assert x.shape[-1] == x.shape[-2] y = np.zeros(x.shape[:-1]) for i in range(x.shape[-1]): y[..., i] = x[..., i, i] return y ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.