# Notebook from anonymousr007/QHack-2022-Open-Hackathon-Project
Path: MMS_VQE.ipynb

# QHack 2022 Open Hackathon Project: Matrix-Model Simulations using VQE
Team Name: anonymousr007

Team Member: [Rishabh Singh](https://github.com/anonymousr007)
_____no_output_____# Introduction_____no_output_____Matrix quantum mechanics plays various important roles in theoretical physics, such as a holographic description of quantum black holes.Understanding quantum black holes and the role of entanglement in a holographic setup is of paramount importance for the development of better quantum algorithms (quantum error correction codes) and for the realization of a quantum theory of gravity. Quantum computing offer us potentially useful approaches to study the dynamics of matrix quantum mechanics. Gauge/gravity duality translates difficult (or intractable) problems in quantum gravity to well-defined problems in non-gravitational quantum theories. Although it originated from string/M-theory, connections to various other fields including quantum information theory, condensed matter theory, and cosmology, have been recognized by now with research programs actively pursued. Quantum mechanics with matrix degrees of freedom (matrix QM, or matrix models in the following) play important roles in gauge/gravity duality. More specifically, Yang–Mills-type matrix models can provide us with a nonperturbative formulation of superstring/M-theory. In certain regions of the parameter space (i.e., strong coupling and large-N), weakly-coupled gravity with small stringy corrections can be described by matrix models.Therefore, matrix models can offer us an ideal setup to study quantum corrections to gravity. By solving the matrix models, it should be possible to study fascinating problems such as the microscopic mechanism of black hole evaporation.

## Quantum Computer

- On a quantum computer, quantum states are directly realized.
- Quantum Computing does not suffer from the sign problem
- The Hamiltonian time evolution can be simulated straightforwardly.
- Some research directions that could benefit from direct quantum simulations are the formation and evaporation of a black hole, or a wormhole, and quantum teleportation.
- The biggest challenge is that we do not yet have a reliable large-scale quantum computer.
- Although we can emulate a quantum computer on a classical computer, these simulations are restricted to systems with only a small number of qubits.
- Furthermore, the effects of the regularization needed to map a theory on a quantum device are not well understood yet.

## Variational Quantum Eigensolver (VQE)

- The Variational Quantum Eigensolver (VQE) is expected to be a useful quantum-classical hybrid algorithm in the Noisy Intermediate Scale Quantum (NISQ) era.
- Being a variational method, the VQE can have systematic errors: a priori, we do not know if we can get the right answer, because the simulation might be
trapped in a local optimum.
- This is a general problem for variational methods.
- Quantum computing represents the computation in terms of qubits and quantum gates which can represent larger Hamiltonians and Hilbert spaces on quantum hardware than classical computers that are limited by memory constraints.
- Also, quantum computing represents fermions straightforwardly in a similar way to how they represent bosons and, as mentioned above, are not susceptible to the sign problem like classical methods using Monte Carlo algorithms.
- Some of the disadvantages of NISQ devices include the lack of quantum error correction for quantum gates and the presence of noise which can lead to inaccurate quantum gates and decoherence of the qubits during the computation.
- For hybrid quantum-classical computations that we discuss here, the advantages are that many parts of a hybrid quantum-classical variational calculation, such as optimization, can be done efficiently on a classical computer, while expectation values can be computed on a quantum computer.
- This leads to a lower depth for the circuits, making them less susceptible to decoherence.
- However, these methods include complicated state-preparation protocols and variational ansatze for the wave function that need to be specified
to have strong overlaps with the true ground state. Such wave functions may need a high-depth quantum circuit which is difficult to implement on a NISQ hardware, and it is prone to decoherence._____no_output_____# Abstract

This project aims to use a truncated (regularized) Hamiltonian for the matrix quantum mechanics models. This Hamiltonian is constructed by considering a truncated Hilbert space in the Fock basis. The truncated Hilbert space is constructed starting from the individual matrix degrees of freedom.

Two types of matrix quantum mechanics models are used

- A Yang-Mills-type bosonic 2-matrix model with SU(2) gauge group, which has 6 bosonic degrees of freedom in total.
- A Supersymmetric 2-matrix model with SU(2) gauge group which corresponds to with the minimal number of degrees of freedom 6 bosons and 3 fermions.

Quantum mechanics with matrix degrees of freedom plays an important role in gauge-gravity duality. Gauge-gravity duality translates difficult problems in quantum gravity to well-defined problems in non-gravitational quantum theories. Although it originated from string–M-theory, connections to various other fields, including

- Quantum Information Theory
- Condensed Matter Theory
- Cosmology
- Holographic simulation of Quantum Black Holes
- Complex high-dimensional supergravity theories

We use the **Variational Quantum EigenSolver (VQE)** to estimate the low-energy spectrum As for the VQE, the specific architecture that we use does not show a satisfactory performance at strong coupling, perhaps due to the variational forms parametrized by the quantum circuits not adequately probing the full gauge-invariant Hilbert space. This result shows that going beyond the VQE and using more complicated or fully quantum algorithms is not the correct way to approach matrix quantum mechanics for now, because they would require even deeper quantum circuits that are more prone to noise on actual quantum hardware._____no_output_____

#@title Check the box below if you have a GPU

HAS_GPU = True #@param {type: "boolean"}
if HAS_GPU:
  print("Installing qiskit with GPU support")
  !pip3 -q install qiskit[visualization] qiskit-aer-gpu pylatexenc
else:
  print("Installing qiskit")
  !pip3 -q install qiskit[visualization] pylatexencInstalling qiskit with GPU support
!pip install qiskitRequirement already satisfied: qiskit in /usr/local/lib/python3.7/dist-packages (0.34.2)
Requirement already satisfied: qiskit-ibmq-provider==0.18.3 in /usr/local/lib/python3.7/dist-packages (from qiskit) (0.18.3)
Requirement already satisfied: qiskit-terra==0.19.2 in /usr/local/lib/python3.7/dist-packages (from qiskit) (0.19.2)
Requirement already satisfied: qiskit-aer==0.10.3 in /usr/local/lib/python3.7/dist-packages (from qiskit) (0.10.3)
Requirement already satisfied: qiskit-ignis==0.7.0 in /usr/local/lib/python3.7/dist-packages (from qiskit) (0.7.0)
Requirement already satisfied: scipy>=1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-aer==0.10.3->qiskit) (1.7.3)
Requirement already satisfied: numpy>=1.16.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-aer==0.10.3->qiskit) (1.21.5)
Requirement already satisfied: requests-ntlm>=1.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.18.3->qiskit) (1.1.0)
Requirement already satisfied: websocket-client>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.18.3->qiskit) (1.2.3)
Requirement already satisfied: python-dateutil>=2.8.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.18.3->qiskit) (2.8.2)
Requirement already satisfied: urllib3>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.18.3->qiskit) (1.24.3)
Requirement already satisfied: requests>=2.19 in /usr/local/lib/python3.7/dist-packages (from qiskit-ibmq-provider==0.18.3->qiskit) (2.23.0)
Requirement already satisfied: setuptools>=40.1.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ignis==0.7.0->qiskit) (57.4.0)
Requirement already satisfied: retworkx>=0.8.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-ignis==0.7.0->qiskit) (0.11.0)
Requirement already satisfied: sympy>=1.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.2->qiskit) (1.7.1)
Requirement already satisfied: psutil>=5 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.2->qiskit) (5.4.8)
Requirement already satisfied: ply>=3.10 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.2->qiskit) (3.11)
Requirement already satisfied: tweedledum<2.0,>=1.1 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.2->qiskit) (1.1.1)
Requirement already satisfied: dill>=0.3 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.2->qiskit) (0.3.4)
Requirement already satisfied: stevedore>=3.0.0 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.2->qiskit) (3.5.0)
Requirement already satisfied: python-constraint>=1.4 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.2->qiskit) (1.4.0)
Requirement already satisfied: symengine>=0.8 in /usr/local/lib/python3.7/dist-packages (from qiskit-terra==0.19.2->qiskit) (0.9.0)
Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.8.0->qiskit-ibmq-provider==0.18.3->qiskit) (1.15.0)
Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.3->qiskit) (2.10)
Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.3->qiskit) (3.0.4)
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.18.3->qiskit) (2021.10.8)
Requirement already satisfied: ntlm-auth>=1.0.2 in /usr/local/lib/python3.7/dist-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.18.3->qiskit) (1.5.0)
Requirement already satisfied: cryptography>=1.3 in /usr/local/lib/python3.7/dist-packages (from requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.18.3->qiskit) (36.0.1)
Requirement already satisfied: cffi>=1.12 in /usr/local/lib/python3.7/dist-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.18.3->qiskit) (1.15.0)
Requirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi>=1.12->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.18.3->qiskit) (2.21)
Requirement already satisfied: importlib-metadata>=1.7.0 in /usr/local/lib/python3.7/dist-packages (from stevedore>=3.0.0->qiskit-terra==0.19.2->qiskit) (4.11.1)
Requirement already satisfied: pbr!=2.1.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from stevedore>=3.0.0->qiskit-terra==0.19.2->qiskit) (5.8.1)
Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=1.7.0->stevedore>=3.0.0->qiskit-terra==0.19.2->qiskit) (3.7.0)
Requirement already satisfied: typing-extensions>=3.6.4 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=1.7.0->stevedore>=3.0.0->qiskit-terra==0.19.2->qiskit) (3.10.0.2)
Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy>=1.3->qiskit-terra==0.19.2->qiskit) (1.2.1)

# Libraries_____no_output_____

# Let us begin by importing necessary libraries.
import time
import sys
import numpy as np
import matplotlib.pyplot as plt
import warnings
%matplotlib inline

# qiskit
from qiskit import Aer
from qiskit.algorithms import VQE, NumPyEigensolver
from qiskit.algorithms.optimizers import SLSQP, SPSA
from qiskit.circuit.library import EfficientSU2
from qiskit.opflow import MatrixOp
from qiskit.utils import algorithm_globals, QuantumInstance

# scipy
from scipy.sparse import diags, identity, kron
from scipy.sparse.linalg import eigsh_____no_output_____

# Basis operators for a single boson

We define the annihilation operator in a $N \times N$ representation for each bosonic matrix, and we define the identity operator.
Combining them for all bosonic matrices will allow us to construct the Hamiltonian._____no_output_____

n = 2  # cutoff for Fock space. The number of qubits used will be K = log2(N)
annihilation_operator = np.array(np.diagflat(np.sqrt(np.linspace(1,n-1,n-1)),k=1))
identity = np.identity(n)_____no_output_____print(annihilation_operator)[[0. 1.]
 [0. 0.]]
print(identity)[[1. 0.]
 [0. 1.]]
bosonic_dof = 6  # number of bosonic dof as matrices: SU(2) -> 2^2-1=6 generators
bosonList = [annihilation_operator]
for bosons in range(0, bosonic_dof-1):
  bosonList.append(identity)
with np.printoptions(precision=3, suppress=True, linewidth=120, threshold=sys.maxsize):
  for i in bosonList:
    print(f"{i}\n")[[0. 1.]
 [0. 0.]]

[[1. 0.]
 [0. 1.]]

[[1. 0.]
 [0. 1.]]

[[1. 0.]
 [0. 1.]]

[[1. 0.]
 [0. 1.]]

[[1. 0.]
 [0. 1.]]

# This for loop takes the appropriate Kronecker products for each boson.
for i in range(0, bosonic_dof):
  for j in range(0, bosonic_dof - 1):
    # For the nth boson, the nth Kronecker product is with the annihilation operator.
    if j == i-1 and i != 0:
        bosonList[i] = np.kron(bosonList[i], annihilation_operator)
    # Else, the nth Kronecker product is with the identity matrix.
    else:
        bosonList[i] = np.kron(bosonList[i], identity) _____no_output_____[x.shape for x in bosonList]_____no_output_____fig, ax = plt.subplots(ncols=6, figsize=(18, 6))
fig.subplots_adjust(left=0.02, bottom=0.06, right=0.95, top=0.94, wspace=0.5, hspace=1)
for i,axi in enumerate(np.ravel(ax)):
  pos = axi.imshow(bosonList[i], cmap='jet')
  fig.colorbar(pos, ax=axi)
  axi.set_title(f"Boson {i+1}")
fig.suptitle('Operators', fontsize=16)
fig.subplots_adjust(top=0.9)_____no_output_____

# Creating the Bosons and the Quartic Hamiltonians

The following cell defines a function which creates the bosons, then it creates the simple quartic and full quartic SU2 Hamiltonians. The function recieves the number of bosons and the size of the bosons as arguments. For example, for 6 bosons that are 8x8, the function call would look like bosonHamiltonians(6, 8). The function returns the two Hamiltonians.

First, an annihilation operator and identity matrix is created. Each of the 6 bosons is constructed by taking the Kronecker product of the annihilation operator with the identity matrix, in a specific order. For the $n^{th}$ boson, the annhiliation operator will be in the $n^{th}$ position of the Kronecker product. For example, the first boson's Kronecker product would look like $$\hat{a} \otimes I \otimes I \otimes I \otimes I \otimes I$$ where $\hat{a}$ is the annihilation operator and $I$ is the identity matrix. The 2nd boson would look like $$I \otimes \hat{a} \otimes I \otimes I \otimes I \otimes I$$ and so on._____no_output_____

def bosonHamiltonians(num_boson, bosonMatrixDim, coupling=0.1):
    # This function takes the number of bosons (num_boson) and the size of the bosons (bosonMatrixDim)
    # as arguments. If the size of the boson is 2 x 2, for example, then bosonMatrixDim = 2.
    # coupling is lambda/2 and lambda is the 'tHooft coupling'

    # Create the n x n annhiliation operator. Here, we create a list with all the integers from
    # the square root of 1 to the square root of n-1, where n x n is the size of the boson.
    # This list is injected as the upper diagonal in an array of zeros.
    ann_op = np.array(np.diagflat(np.sqrt(np.linspace(1,bosonMatrixDim-1,bosonMatrixDim-1)),k=1))

    # Create the n x n identity matrix.
    id = np.identity(bosonMatrixDim)

    # Create a list which holds the six bosons. bosonList[0] is the first boson. bosonList[5] is the 6th boson.
    # For the first boson, the Kronecker product starts with the annihilation operator.
    bosonList = [ann_op]

    # This for loop creates the list of bosons before the Kronecker products are taken. The first one was
    # already created in the previous line.
    for bosons in range(0,num_boson-1):
        bosonList.append(id)

    # This for loop takes the appropriate Kronecker products for each boson.
    for i in range(0,num_boson):
        for j in range(0,num_boson-1):

            # For the nth boson, the nth Kronecker product is with the annihilation operator.
            if j == i-1 and i != 0:
                bosonList[i] = np.kron(bosonList[i], ann_op)
            # Else, the nth Kronecker product is with the identity matrix.
            else:
                bosonList[i] = np.kron(bosonList[i], id)

    # Create the position operators. Normalized as in the notes
    x = []
    for r in range(0, num_boson):
        x.append((1/np.sqrt(2))*(bosonList[r] + np.transpose(np.conjugate(bosonList[r]))))

    # Create the simple quadratic Hamiltonian.
    H2MM = 0

    for i in range(0,num_boson):
        # The @ symbol is a shorthand for matrix multiplication. It's equivalent to using np.matmul().
        H2MM = H2MM + (np.transpose(np.conjugate(bosonList[i])) @ bosonList[i])

    H2MM = H2MM + 0.5*num_boson*np.identity(bosonMatrixDim**(num_boson))

    # Create the full quartic SU(2) Hamiltonian.
    x_sq = []

    for i in x:
        x_sq.append(i @ i)

    H4MM1 = (H2MM + coupling*((x_sq[2] @ x_sq[3])
                              + (x_sq[2] @ x_sq[4])
                              + (x_sq[1] @ x_sq[3])
                              + (x_sq[1] @ x_sq[5])
                              + (x_sq[0] @ x_sq[4])
                              + (x_sq[0] @ x_sq[5])
                              - 2*((x[0] @ x[2]) @ (x[3] @ x[5]))
                              - 2*((x[0] @ x[1]) @ (x[3] @ x[4]))
                              - 2*((x[1] @ x[2]) @ (x[4] @ x[5]))))
    return H2MM, H4MM1

# Set the number of bosons here. For the proper full quartic SU(2) Hamiltonian, this has to be 6.
num_boson = 6

# Set the size of the bosons here. For an n x n boson, bosonMatrixDim = n.
# 5 crashes this colab with 12Gb of RAM ->  tries 6 of these tcmalloc: large alloc 1953128448 bytes
bosonMatrixDim = 2

# the function actually creates intermediate matrices x and x2 so the memory footprint is even higher...for N=5 it requires ~50GB of RAM
H2MM, H4MM1 = bosonHamiltonians(num_boson, bosonMatrixDim, coupling=0.1)  # we can change the coupling by adding coupling=0.5 to the args

# Set the Hamiltonian that you want to run the VQE algorithm with here.
hamiltonian = H4MM1

# Use numpy to find the eigenvalues of the simple quartic Hamiltonian
# this can take a long time for large matrices
val,vec=np.linalg.eig(hamiltonian)
z = np.argsort(val)
z = z[0:len(hamiltonian)]
energies=(val[z])

if hamiltonian.all() == H4MM1.all():
    # Sometimes there are negligible imaginary parts (e.g. order of 10^-16), so I take the real parts only.
    print('Full Quartic SU2 Eigenvalues:\n\n', np.real(energies))
else:
    print('Simple Quartic Eigenvalues:\n\n', energies)Full Quartic SU2 Eigenvalues:

 [3.14807787 4.14674965 4.14674965 4.14674965 4.14674965 4.14674965
 4.14674965 5.04817155 5.09501244 5.09501244 5.09501244 5.09501244
 5.09501244 5.09501244 5.2        5.2        5.2        5.2
 5.2        5.2        5.2        5.2        6.         6.
 6.10024938 6.10024938 6.10024938 6.10024938 6.10024938 6.10024938
 6.2        6.2        6.2        6.2        6.2        6.2
 6.2        6.2        6.2        6.2        6.2        6.2
 7.05192213 7.10498756 7.10498756 7.10498756 7.10498756 7.10498756
 7.10498756 7.2        7.2        7.2        7.2        7.2
 7.2        7.2        7.2        8.15300098 8.15300098 8.15300098
 8.15300098 8.15300098 8.15300098 9.15182845]

# Convert the Hamiltonian
Now, we take the Hamiltonian matrix and map it onto a qubit operator. There may be better ways to do this now that `qiskit` has added new ways to map Hamiltonians to qubit operators.

In fact, we should skip the creation of the Hamiltonian as a matrix and directly used operators in `qiskit`_____no_output_____

start_time = time.time()
warnings.filterwarnings("ignore")

qubit_operator = MatrixOp(primitive=hamiltonian)
print("Size of Hamiltonian:", np.shape(hamiltonian))

end_time = time.time()

runtime = end_time-start_time
print('Program runtime: ',runtime)Size of Hamiltonian: (64, 64)
Program runtime:  0.0030336380004882812
print(qubit_operator)Operator([[3.15+0.j, 0.  +0.j, 0.  +0.j, ..., 0.  +0.j, 0.  +0.j,
           0.  +0.j],
          [0.  +0.j, 4.15+0.j, 0.  +0.j, ..., 0.  +0.j, 0.  +0.j,
           0.  +0.j],
          [0.  +0.j, 0.  +0.j, 4.15+0.j, ..., 0.  +0.j, 0.  +0.j,
           0.  +0.j],
          ...,
          [0.  +0.j, 0.  +0.j, 0.  +0.j, ..., 8.15+0.j, 0.  +0.j,
           0.  +0.j],
          [0.  +0.j, 0.  +0.j, 0.  +0.j, ..., 0.  +0.j, 8.15+0.j,
           0.  +0.j],
          [0.  +0.j, 0.  +0.j, 0.  +0.j, ..., 0.  +0.j, 0.  +0.j,
           9.15+0.j]],
         input_dims=(2, 2, 2, 2, 2, 2), output_dims=(2, 2, 2, 2, 2, 2))
print("Total number of qubits: ",qubit_operator.num_qubits)
print("Type of qubitOp: ",type(qubit_operator).__name__)Total number of qubits:  6
Type of qubitOp:  MatrixOp
ansatz = EfficientSU2(qubit_operator.num_qubits, su2_gates=['ry'], entanglement="full", reps=1)
ansatz.draw(output='mpl')_____no_output_____np.log2(hamiltonian.shape[0])_____no_output_____

# Looping the VQE algorithm over several optimizers_____no_output_____## Statevector simulator_____no_output_____

warnings.filterwarnings("ignore")
seed = 0
algorithm_globals.random_seed = seed
if HAS_GPU:
  backend = Aer.get_backend("statevector_simulator", method="statevector_gpu")
else:
  backend = Aer.get_backend("statevector_simulator", max_parallel_threads=6, max_parallel_experiments=0)
quantum_instance = QuantumInstance(backend, seed_transpiler = seed, seed_simulator = seed)_____no_output_____counts = []
values = []

def store_intermediate_result(eval_count, parameters, mean, std):
    counts.append(eval_count)
    values.append(mean)

optimizer = SLSQP(maxiter=1000)

vqe = VQE(ansatz=ansatz, optimizer=optimizer, quantum_instance=quantum_instance, callback=store_intermediate_result)
result = vqe.compute_minimum_eigenvalue(qubit_operator)
vqe_result = np.real(result.eigenvalue)
print(f"VQE gs energy: {vqe_result}")VQE gs energy: 3.150000100711781
# Plot all of the optimizers in a single convergence plot. If you see that the optimizer isn't converging,
# increase the maximum iterations or maximum function evaluations in the optimizer list above.

labelList = ["SLSQP"]

plt.plot(counts, values)
plt.axhline(y=np.real(energies[0]),xmin=0,xmax=counts[-1],color='k',linestyle='--',label="Exact Energy")
plt.xlabel('Eval count')
plt.ylabel('Energy')
plt.title('Energy convergence')
plt.legend(loc='upper right', labels=labelList)_____no_output_____

## QASM Simulator_____no_output_____

warnings.filterwarnings("ignore")

backendQasm = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend=backendQasm, shots=1024)
optimizer = SPSA(maxiter=10000)

counts = []
values = []

def store_intermediate_result(eval_count, parameters, mean, std):
    counts.append(eval_count)
    values.append(mean)

vqe = VQE(ansatz=ansatz, optimizer=optimizer, quantum_instance=quantum_instance, callback=store_intermediate_result)

result = vqe.compute_minimum_eigenvalue(qubit_operator)
vqe_result = np.real(result.eigenvalue)
print(f"VQE gs energy (QASM): {vqe_result}")VQE gs energy (QASM): 3.15
# Plot convergence plot for the SPSA optimizer
plt.plot(counts, values, label="SPSA")
plt.plot(counts,[np.real(energies[0])]*len(counts), 'k--',label="Exact Energy")
plt.xlabel('Eval count')
plt.ylabel('Energy')
plt.title('Energy convergence of SPSA optimizer (QASM)')
plt.legend(loc='upper right')_____no_output_____import qiskit.tools.jupyter
%qiskit_version_table_____no_output_____


# Notebook from seriousbamboo/xqtl-pipeline
Path: code/molecular_phenotypes/bulk_expression.ipynb

# RNA-seq calling and QC

This document shows the use of various modules to prepare reference data, perform RNA-seq calling, expression level quantification and quality control. In particular,

1. [`reference_data.ipynb`](../data_preprocessing/reference_data.html)
2. [`RNA_calling.ipynb`](calling/RNA_calling.html)
3. [`readCount_QC.ipynb`](QC/readCount_QC.html)

A minimal working example is available on [Google Drive](https://drive.google.com/drive/u/0/folders/11kQv7PXozsKkgeqADH-28bC_kZ-w_oHo)._____no_output_____## Download reference data (first time use)_____no_output_____

sos run reference_data download_hg_reference --cwd reference_data
sos run reference_data download_gene_annotation --cwd reference_data
sos run reference_data download_ercc_reference --cwd reference_data_____no_output_____

## Reformat reference data (first time use)_____no_output_____

sos run reference_data.ipynb hg_reference \
    --cwd reference_data \
    --ercc-reference reference_data/ERCC92.fa \
    --hg-reference reference_data/GRCh38_full_analysis_set_plus_decoy_hla.fa \
    --container container/rna_quantification.sif_____no_output_____

**Notice: you need to know if your RNA-seq data is stranded or unstranded. If it is stranded, you should add `--stranded` to the command below.**_____no_output_____

sos run reference_data.ipynb gene_annotation \
    --cwd reference_data \
    --ercc-gtf reference_data/ERCC92.gtf \
    --hg-gtf reference_data/Homo_sapiens.GRCh38.103.chr.gtf \
    --hg-reference reference_data/GRCh38_full_analysis_set_plus_decoy_hla.noALT_noHLA_noDecoy_ERCC.fasta \
    --container container/rna_quantification.sif _____no_output_____

## Index reference data_____no_output_____

sos run reference_data.ipynb STAR_index \
    --cwd reference_data \
    --hg-reference reference_data/GRCh38_full_analysis_set_plus_decoy_hla.noALT_noHLA_noDecoy_ERCC.fasta \
    --hg-gtf reference_data/Homo_sapiens.GRCh38.103.chr.reformatted.ERCC.gtf \
    --container container/rna_quantification.sif \
    --mem 40G_____no_output_____sos run reference_data.ipynb RSEM_index \
    --cwd reference_data \
    --hg-reference reference_data/GRCh38_full_analysis_set_plus_decoy_hla.noALT_noHLA_noDecoy_ERCC.fasta \
    --hg-gtf reference_data/Homo_sapiens.GRCh38.103.chr.reformatted.ERCC.gtf \
    --container container/rna_quantification.sif \
    --mem 40G_____no_output_____

## Perform data quality summary via `fastqc`_____no_output_____

sos run RNA_calling.ipynb fastqc \
    --cwd output/rnaseq/fastqc \
    --samples data/sample_fastq.list \
    --data-dir data \
    --container container/rna_quantification.sif_____no_output_____

## Call gene-level RNA expression via `rnaseqc`_____no_output_____

sos run RNA_calling.ipynb rnaseqc_call \
    --cwd output/rnaseq \
    --samples data/sample_fastq.list \
    --data-dir data \
    --fasta_with_adapters_etc TruSeq3-PE.fa \
    --STAR-index reference_data/STAR_Index/ \
    --gtf reference_data/Homo_sapiens.GRCh38.103.chr.reformatted.gene.ERCC.gtf \
    --container container/rna_quantification.sif \
    --mem 40G_____no_output_____

## Call transcript level RNA expression via `RSEM`_____no_output_____

sos run RNA_calling.ipynb rsem_call \
    --cwd output/rnaseq \
    --samples data/sample_fastq.list \
    --data-dir data \
    --fasta_with_adapters_etc TruSeq3-PE.fa \
    --STAR-index reference_data/STAR_Index/ \
    --RSEM-index reference_data/RSEM_Index/ \
    --container container/rna_quantification.sif \
    --mem 40G_____no_output_____

## Multi-sample RNA-seq QC_____no_output_____We need to use a different MWE data-set that contains multiple samples -- here is the [Google Drive link](https://drive.google.com/drive/u/0/folders/1Rv2bWHBbX_tastTh49ToYVDMV6rFP5Wk)._____no_output_____

sos run bulk_expression_QC.ipynb qc \
    --cwd output \
    --tpm-gct data/mwe.TPM.gct \
    --counts-gct data/mwe.Counts.gct \
    --container container/rna_quantification.sif_____no_output_____

## Multi-sample read count normalization_____no_output_____

sos run bulk_expression_normalization.ipynb normalize \
    --cwd output \
    --tpm-gct data/mwe.low_expression_filtered.outlier_removed.tpm.gct.gz \
    --counts-gct data/mwe.low_expression_filtered.outlier_removed.geneCount.gct.gz \
    --annotation-gtf reference_data/Homo_sapiens.GRCh38.103.chr.reformatted.gene.ERCC.gtf  \
    --sample-participant-lookup data/sampleSheetAfterQC.txt \
    --container container/rna_quantification.sif \
    --count-threshold 1_____no_output_____


# Notebook from biocore/tcga
Path: jupyter_notebooks/TCGA Validation Spits Batch Correction -- Final Analysis.ipynb

import os, numpy, warnings
import pandas as pd_____no_output_____os.environ['R_HOME'] = '/home/gdpoore/anaconda3/envs/tcgaAnalysisPythonR/lib/R'
warnings.filterwarnings('ignore')
%config InlineBackend.figure_format = 'retina'_____no_output_____%reload_ext rpy2.ipython_____no_output_____%%R

require(ggplot2)
require(snm)
require(limma)
require(edgeR)
require(dplyr)
require(edgeR)
require(pvca)
require(lme4)
require(doMC)

numCores <- detectCores()
registerDoMC(cores=numCores)_____no_output_____%%R
load("validationSplitVbDataAndMetadata.RData")_____no_output_____%%R
print(dim(split1MetadataQC))
print(dim(split2MetadataQC))

print(dim(split1VbDataQC))
print(dim(split2VbDataQC))_____no_output_____%%R
qcMetadataS1 <- split1MetadataQC # metadataSamplesAllQCAML
qcDataS1 <- split1VbDataQC # vbDataBarnDFReconciledQCAML

# Set up design matrix
covDesignNormS1 <- model.matrix(~0 + sample_type +
                                  data_submitting_center_label +
                                  platform +
                                  experimental_strategy +
                                  tissue_source_site_label +
                                  portion_is_ffpe,
                              data = qcMetadataS1)
print(colnames(covDesignNormS1))
colnames(covDesignNormS1) <- gsub('([[:punct:]])|\\s+','',colnames(covDesignNormS1))
print(colnames(covDesignNormS1))

# Set up counts matrix
countsS1 <- t(qcDataS1) # DGEList object from a table of counts (rows=features, columns=samples)

# Normalize using edgeR and then plug into voom
dgeS1 <- DGEList(counts = countsS1)
keep <- filterByExpr(dgeS1, covDesignNormS1)
dgeS1 <- dgeS1[keep,,keep.lib.sizes=FALSE]
print("Now normalizing data...")
dgeS1 <- calcNormFactors(dgeS1, method = "TMM")
print("Now applying voom on normalized data...")
vdgeS1 <- voom(dgeS1, design = covDesignNormS1, plot = TRUE, save.plot = TRUE, normalize.method="none")_____no_output_____%%R
qcMetadataS2 <- split2MetadataQC # metadataSamplesAllQCAML
qcDataS2 <- split2VbDataQC # vbDataBarnDFReconciledQCAML

# Set up design matrix
covDesignNormS2 <- model.matrix(~0 + sample_type +
                                  data_submitting_center_label +
                                  platform +
                                  experimental_strategy +
                                  tissue_source_site_label +
                                  portion_is_ffpe,
                              data = qcMetadataS2)
print(colnames(covDesignNormS2))
colnames(covDesignNormS2) <- gsub('([[:punct:]])|\\s+','',colnames(covDesignNormS2))
print(colnames(covDesignNormS2))

# Set up counts matrix
countsS2 <- t(qcDataS2) # DGEList object from a table of counts (rows=features, columns=samples)

# Normalize using edgeR and then plug into voom
dgeS2 <- DGEList(counts = countsS2)
keep <- filterByExpr(dgeS2, covDesignNormS2)
dgeS2 <- dgeS2[keep,,keep.lib.sizes=FALSE]
print("Now normalizing data...")
dgeS2 <- calcNormFactors(dgeS2, method = "TMM")
print("Now applying voom on normalized data...")
vdgeS2 <- voom(dgeS2, design = covDesignNormS2, plot = TRUE, save.plot = TRUE, normalize.method="none")_____no_output_____%%R

print(dim(t(vdgeS1$E)))
print(dim(t(vdgeS2$E)))_____no_output_____%%R
taxaIntersect <- intersect(colnames(t(vdgeS1$E)), colnames(t(vdgeS2$E)))
print(length(taxaIntersect))

vdgeS1Filt <- t(vdgeS1$E)[,taxaIntersect]
vdgeS2Filt <- t(vdgeS2$E)[,taxaIntersect]
print(dim(vdgeS1Filt))
print(dim(vdgeS2Filt))_____no_output_____%%R

# Apply
bio.var.sample.typeS1 <- model.matrix(~sample_type, #sample_type, # histological_diagnosis_label and disease_type tried but cause function to fail
                        data=qcMetadataS1)
adj.varS1 <- model.matrix(~data_submitting_center_label +
                          platform +
                          experimental_strategy +
                          tissue_source_site_label +
                          portion_is_ffpe,
                        data=qcMetadataS1)
colnames(bio.var.sample.typeS1) <- gsub('([[:punct:]])|\\s+','',colnames(bio.var.sample.typeS1))
colnames(adj.varS1) <- gsub('([[:punct:]])|\\s+','',colnames(adj.varS1))
print(dim(adj.varS1))
print(dim(bio.var.sample.typeS1))
print(dim(vdgeS1Filt))
print(dim(covDesignNormS1))_____no_output_____%%R

# Apply
bio.var.sample.typeS2 <- model.matrix(~sample_type, #sample_type, # histological_diagnosis_label and disease_type tried but cause function to fail
                        data=qcMetadataS2)
adj.varS2 <- model.matrix(~data_submitting_center_label +
                          platform +
                          experimental_strategy +
                          tissue_source_site_label +
                          portion_is_ffpe,
                        data=qcMetadataS2)
colnames(bio.var.sample.typeS2) <- gsub('([[:punct:]])|\\s+','',colnames(bio.var.sample.typeS2))
colnames(adj.varS2) <- gsub('([[:punct:]])|\\s+','',colnames(adj.varS2))
print(dim(adj.varS2))
print(dim(bio.var.sample.typeS2))
print(dim(vdgeS2Filt))
print(dim(covDesignNormS2))_____no_output_____%%R
snmDataObjSampleTypeWithExpStrategyFAS1 <- snm(raw.dat = t(vdgeS1Filt),
                                            bio.var = bio.var.sample.typeS1,
                                            adj.var = adj.varS1,
                                            rm.adj=TRUE,
                                            verbose = TRUE,
                                            diagnose = TRUE)
snmDataSampleTypeWithExpStrategyFAS1 <- t(snmDataObjSampleTypeWithExpStrategyFAS1$norm.dat)

print(dim(snmDataSampleTypeWithExpStrategyFAS1))_____no_output_____%%R
snmDataObjSampleTypeWithExpStrategyFAS2 <- snm(raw.dat = t(vdgeS2Filt),
                                            bio.var = bio.var.sample.typeS2,
                                            adj.var = adj.varS2,
                                            rm.adj=TRUE,
                                            verbose = TRUE,
                                            diagnose = TRUE)
snmDataSampleTypeWithExpStrategyFAS2 <- t(snmDataObjSampleTypeWithExpStrategyFAS2$norm.dat)

print(dim(snmDataSampleTypeWithExpStrategyFAS2))_____no_output_____%%R
save(snmDataSampleTypeWithExpStrategyFAS1, snmDataSampleTypeWithExpStrategyFAS2,
     split1MetadataQC, split2MetadataQC,
     file = "validationSplits_snmDataSampleTypeWithExpStrategyFAS1S2.RData")_____no_output_____

# PCA plotting to visually examine batch effects and batch correction_____no_output_____

%%R
pcaPlotting <- function(pcaObject,pcChoices, dataLabels, factorString, titleString){
  require(ggbiplot)
  theme_update(plot.title = element_text(hjust = 0.5))
  g <- ggbiplot(pcaObject,pcChoices, obs.scale = 1, var.scale = 1,
                groups = dataLabels, ellipse = TRUE,
                alpha = 0.2,
                circle = TRUE,var.axes=FALSE) +
    scale_color_discrete(name = factorString) +
    theme_bw() +
    #theme(legend.direction = "horizontal", legend.position = "top") +
    ggtitle(titleString) + theme(plot.title = element_text(hjust = 0.5))

  print(g)
}_____no_output_____%%R
unnormalizedPCAPlotFA <- pcaPlotting(pcaObject = prcomp(t(vdge$E)),
                                   pcChoices = c(1,2),
                                   dataLabels = qcMetadata$data_submitting_center_label,
                                   factorString = "Batch",
                                   titleString = "PCA w/o Batch Correction")_____no_output_____%%R
snmPCAPlotSampleTypeFA <- pcaPlotting(pcaObject = prcomp(snmDataSampleTypeWithExpStrategyFA),
                          pcChoices = c(1,2),
                          dataLabels = qcMetadata$data_submitting_center_label,
                          factorString = "Sequencing Center",
                          titleString = "PCA w/ SNM Correction\n(Target: Sample Type)")_____no_output_____# %%R
# snmPCAPlotGender <- pcaPlotting(pcaObject = prcomp(snmDataGenderWithAML),
#                           pcChoices = c(1,2),
#                           dataLabels = qcMetadata$data_submitting_center_label,
#                           factorString = "Sequencing Center",
#                           titleString = "PCA w/ SNM Correction\n(Target: Gender)")_____no_output_____%%R
ggsave(plot = unnormalizedPCAPlotFA,
       filename = "unnormalizedPCAPlotFA_DecreasedOpacity.png",
       width = 16.2,
       height = 5.29,
       units = "in",
       dpi = "retina")

ggsave(plot = snmPCAPlotSampleTypeFA,
       filename = "snmPCAPlotSampleTypeFA_DecreasedOpacity.png",
       width = 16.2,
       height = 5.29,
       units = "in",
       dpi = "retina")

# save(snmDataGenderWithAML, metadataSamplesAllQCAML,
#      vbDataBarnDFReconciledQCAML,
#      file = "amlVbDataAndMetadataAndSNMByGender.RData")_____no_output_____# %%R
# snmDataObjGenderWithAML <- snm(raw.dat = vdge$E,
#                                 bio.var = bio.var.gender,
#                                 adj.var = adj.var,
#                                 rm.adj=TRUE,
#                                 verbose = TRUE,
#                                 diagnose = TRUE)
# snmDataGenderWithAML <- t(snmDataObjGenderWithAML$norm.dat)

# print(dim(snmDataGenderWithAML))_____no_output_____

# PVCA using key filtered metadata features (i.e. narrowing down the extended version of this)_____no_output_____

%%R
# Implement PVCA
# From extended model, remove variables that contribute very little if at all:
# ethnicity, gender, reference_genome
pct_threshold <- 0.8
metaPVCAExtendedFiltered <- metadataSamplesAllQC[,c("sample_type",
                                            "disease_type",
                                            "data_submitting_center_label",
                                            "platform",
                                            "experimental_strategy",
                                            "tissue_source_site_label",
                                            "portion_is_ffpe")]
print(dim(metaPVCAExtendedFiltered))
print(dim(snmDataSampleTypeWithExpStrategy))
print(dim(vbDataBarnDFReconciledQC))_____no_output_____%%R
pvcaVbRawNoVoomNoSNM_ExtendedFiltered_FA <- PVCA(counts = t(vbDataBarnDFReconciledQC),
                                               meta = metaPVCAExtendedFiltered,
                                               threshold = pct_threshold,
                                               inter = FALSE)
save(pvcaVbRawNoVoomNoSNM_ExtendedFiltered_FA, file = "pvcaVbRawNoVoomNoSNM_ExtendedFiltered_FA.RData")
PlotPVCA(pvcaVbRawNoVoomNoSNM_ExtendedFiltered_FA, "Raw count data")_____no_output_____%%R
pvcaVoomNoSNM_ExtendedFiltered_FA <- PVCA(counts = vdge$E,
                                           meta = metaPVCAExtendedFiltered,
                                           threshold = pct_threshold,
                                           inter = FALSE)
save(pvcaVoomNoSNM_ExtendedFiltered_FA, file = "pvcaVoomNoSNM_ExtendedFiltered_FA.RData")
PlotPVCA(pvcaVoomNoSNM_ExtendedFiltered_FA, "Voom Normalized")_____no_output_____%%R
pvcaSampleWithExpStrategySNM_ExtendedFiltered_FA <- PVCA(counts = t(snmDataSampleTypeWithExpStrategyFA),
                                                       meta = metaPVCAExtendedFiltered,
                                                       threshold = pct_threshold,
                                                       inter = FALSE)
save(pvcaSampleWithExpStrategySNM_ExtendedFiltered_FA,
     file = "pvcnoaSampleWithExpStrategySNM_ExtendedFiltered_FA.RData")
PlotPVCA(pvcaSampleWithExpStrategySNM_ExtendedFiltered_FA,
         "Voom Normalized & SNM Corrected Plus Exp Strategy (Target is Sample Type)")_____no_output_____%%R
1+2_____no_output_____

# Examining sample and taxa ratio changes due to batch correction_____no_output_____

%%R
require(ggplot2)
require(matrixStats)
divSNMDataSampleType <- snmDataSampleType / t(snmDataObjSampleType$raw.dat)
taxaMedians <- data.frame(Medians = colMedians(divSNMDataSampleType),
                          Taxa = colnames(divSNMDataSampleType),
                          pval = factor(ifelse(snmDataObjSampleType$pval <=0.05,
                                               yes = "P-value <= 0.05", no = "P-value > 0.05")))
sampleMedians <- data.frame(Medians = rowMedians(divSNMDataSampleType),
                            Samples = rownames(divSNMDataSampleType),
                            SeqCenter = metadataSamplesAllQC$data_submitting_center_label,
                            SampleType = metadataSamplesAllQC$sample_type,
                            CancerType = metadataSamplesAllQC$disease_type)
gt <- ggplot(taxaMedians, aes(x = reorder(Taxa, -Medians), y = Medians, fill = pval)) +
geom_bar(stat = "identity") +
theme(axis.title.x=element_blank(), axis.text.x=element_blank(), axis.ticks.x=element_blank()) +
labs(y = "Median of Normalizing Ratios Per Taxa", x = "Samples", fill = "ANOVA Result Per Taxa")

gs <- ggplot(sampleMedians, aes(x = reorder(Samples, -Medians), y = Medians, fill = CancerType)) +
  geom_bar(stat = "identity") + coord_flip() +
  theme(axis.text.y=element_blank(), axis.ticks.y=element_blank()) +
  scale_y_log10() + labs(y = "Median of Normalizing Ratios Per Sample", x = "Samples", fill='Cancer Type') _____no_output_____%%R
gt_____no_output_____%%R
ggsave(plot = gt,
       filename = "snmNormMedianPerTaxaPval.png",
       width = 8.5,
       height = 6,
       units = "in",
       dpi = "retina")_____no_output_____%%R
require(pheatmap)
pheatmap(snmDataSampleTypeLMFit$coefficients,
         clustering_distance_rows = "correlation",
         clustering_distance_cols = "correlation",
         show_rownames = FALSE,
         show_colnames = FALSE,
         filename = "snmLMFitCoefCorr.png")_____no_output_____# %%R
# save(snmDataObjPathStage, snmDataPathStage, metadataSamplesAllQCPath, file = "snmResultsPathBinned.RData")_____no_output_____


# Notebook from YiweiMao/blog
Path: _notebooks/2021-01-25-Displaying_Spectra.ipynb

# Why Displays Cannot Show Pure Emission Lines
> So how can the observed colour from spectra be displayed? An exploration of the CIE 1931 color space and how that relates to sRGB. Python code included.

- toc: true
- badges: true
- comments: true
- categories: []
- image: images/2021-01-25-displaying_spectra_files/CIE1931xy_srgb.svg
- hide: true
- search_exclude: true
- permalink: /colour_of_spectra/_____no_output_____

#hide
from coloured_spectra.coloured_spectra import * # wrote this library just for this blog post
import numpy as np
import matplotlib.pyplot as plt
import cv2_____no_output_____

# Introduction

Okay, you got yourself a spectrometer and you now have a spectra. As a sensible person, you did *not* stare into the end of the fiber optic cable to see what colour that spectra represents. (And seriously, do not do this with your remaining eye either!) So you decide to simulate what that colour is from the spectra you obtained but as it turns out, this task is *not* trivial. This was the story of how this blog post came to be.

In this blog post, we will discuss human vision and the colour spaces that are necessary to represent spectra in the "right" colour - in particular the CIE 1931 XYZ colour space. In doing so, we will discover that there are colours that we can see but are not possible to display on screens and how to work around this. Lastly, as a demonstration, we will see how spectra can be coloured.

> Tip: This whole blog post is a Jupyter Notebook so you can run it with your own choice of parameters.

_____no_output_____# Human Vision

The ordinary human eye has three types of cone cells that are sensitive to different spectral ranges under bright conditions. (When it is dark, rod cells dominate and they give us monochromatic vision.) They are the short "S", middle "M", and long "L" cones and their sensitivity is shown in Figure 1. Together, this forms the LMS colour space and is good for simulating various human eye visual receptions but is otherwise not very useful for computer displays. We will get to why later but the fundamental reason lies in the overlap between the L, M, and S sensitivities.

![](https://upload.wikimedia.org/wikipedia/commons/0/04/Cone-fundamentals-with-srgb-spectrum.svg "Figure 1: Normalised spectral sensitivity of human cone cells. Also, we are more sensitive to green light.")

## Displays and the sRGB Colour Space

According to [this website](https://techterms.com/definition/srgb#:~:text=sRGB%20is%20a%20color%20space,%2C%20green%2C%20and%20blue%20values), the definition of colours that can be displayed on screens fall under the Standard RGB (sRGB) standard. So in order to represent a colour to show on our screens, we must produce an sRGB representation from a spectra. As it turns out, this conversion between from spectra to sRGB cannot be done directly and we must turn to a standard reference that defines other colour spaces called the CIE XYZ colour space. _____no_output_____## The CIE XYZ Colour Space

The Commission Internationale de l'éclairage (CIE) 1931 XYZ colour space defines all colour sensations an average human can experience.

> Note: **The CIE Standard Observer**: The distribution of cones depends on the field of view so in initial experiments, this was set to be within 2° arc of the fovea. Other angles were used later including 10$^\circ$.

### Matching Functions

The matching functions were obtained by the standard observers and is shown below (produced from an analytic approximation). Overall, these are similar to the LMS plot in Figure 1 with a notable difference - the bumb in X($\lambda$) around 450 nm. I haven't found conclusive evidence why that is but after experimenting in code, this bump is needed to get conversions to *indigo and violet* for wavelengths close to 400 nm. Without this bump, the displayed colour would just be blue and if you've seen a rainbow, the colours of the rainbow do not go from red to green to blue but includes a shade of purple too.

_____no_output_____

plot_cie_xyz_matching_functions()_____no_output_____

Here is a rainbow for good measure.

![](https://media.nationalgeographic.org/assets/photos/000/284/28417.jpg "Figure 2: A rainbow that shows indigo and violet colours")
_____no_output_____In Figure 3, the boundary of the coloured shark fin represent the colour of each pure wavelength. By definition, the sRGB colour space is a subset of the CIE XYZ. Any chromaticity that lies outside the sRGB triangle will have some R, G, or B values that are *negative* and cannot be displayed. Let's look at why this is the case using an example.

![](../images/2021-01-25-displaying_spectra_files/CIE1931xy_srgb.svg "Figure 3: sRGB is a subset of CIE XYZ.")

The white point is marked as D65. What is the reasoning behind this naming?

#### D65 and the CIE Standard Illuminant

[D65](https://en.wikipedia.org/wiki/Illuminant_D65) is known as the CIE standard illuminant and is roughly equivalent to daylight at midday Europe. The 65 refers to a colour temperature of 6500 K (actually 6504 K after physical constants were revised). There are other standard illuminants defined by different colour temperatures.

![](https://upload.wikimedia.org/wikipedia/commons/thumb/d/d0/SPD_D65.png/512px-SPD_D65.png "Figure 4: D65 spectral power distribution.")

#### How to display a pure green spectral line?
Let's use the CIE XYZ space for the sake of this argument. The same reasoning can be applied to the LMS colour space.
In our example, we assume that [green on the display is emitted at 532 nm](https://www.rp-photonics.com/rgb_sources.html) (will depend on your display!). Then this pure spectral line will have components in X, Y, and Z but most of the contribution is towards Y.

_____no_output_____

wavelength2xyz(532) # X, Y, and Z contributions at 532 nm_____no_output_____

If we treated these values as the same as sRGB and that the possible sRGB values lie between 0 (min) and 1 (max), then what colour will be displayed? _____no_output_____

plot_colour(wavelength2xyz(532))_____no_output_____

Then the colour will less green than expected, whitened by adding blue and red, and shifted a little more red when it should just display only green components! Can you tell the difference bewteen the green above and below?_____no_output_____

plot_colour([0,1.,0])_____no_output_____

The same can be said for any other pure wavelength.

### How to deal with negative sRGB values

Here, we will see two ways we can deal with negative sRGB values. They are: clamping all negatives to zero, and whitening.
In whitening, we add to all channels until all numbers are non-negative then rescale the result such that the original max sRGB value is unchanged.
The following plots will show you what the difference is._____no_output_____

plot_wavelength_colours("CLAMP")_____no_output_____plot_wavelength_colours("WHITEN")_____no_output_____

## Colour of a Blackbody

The Sun can be appoximated as a blackbody with temperature 5778 K. Let's see what colour this spectra corresponds to.
_____no_output_____

bb = Blackbody(5778)
bb.plot()_____no_output_____
def show_blackbody_colour(T_K):
    bb = Blackbody(T_K,np.linspace(380,750))

    sRGB = spectra2sRGB(bb.λ_nm,bb.B_λT)

    # Due to normalisation choices, the brightness can change depending on the spectra
    # show the same hue at max brightness
    HSV = cv2.cvtColor(np.reshape(sRGB,(1,1,3)), cv2.COLOR_RGB2HSV_FULL)
    HSV[0,0,2] = 255
    RGB = cv2.cvtColor(HSV, cv2.COLOR_HSV2RGB_FULL)

    plot_colour(RGB)_____no_output_____show_blackbody_colour(5778)_____no_output_____show_blackbody_colour(11000) # what about the star Rigel?_____no_output_____

# Displaying spectra

Let's artifically create the spectra for HgAr and then use `coloured_spectra` to show the emission lines in its colour.
We can't see UV and NIR so those emission lines will be coloured white. The colour palette for each wavelength we will be using is shown below.
_____no_output_____

plot_hsv_LUT_spectrum()_____no_output_____

This is a simulated HgAr spectra._____no_output_____

lines_nm = [254,436,546,764,405,365,578,750,738,697,812,772,912,801,842,795,706,826,852,727] # approx sorted by emission strength
img = np.zeros((100,1000))
wavelengths = np.linspace(350,850,1000)

strength = 1.
for line in lines_nm:
    indx = np.sum(wavelengths<line)
    if indx > 0 and indx < 1000:
        img[:,indx-2:indx+2] = strength
        strength -= 0.04

plt.imshow(img,cmap="gray",extent=[np.min(wavelengths),np.max(wavelengths),0,np.shape(img)[0]])
plt.xlabel("wavelength (nm)")
_____no_output_____colour_hyperspectral_line(wavelengths,img)100%|██████████| 100/100 [00:01<00:00, 54.87it/s]

# Conclusion
In this blog post, we learned that displays cannot show all the colours we can see. We saw how the CIE 1931 XYZ colour space can be used to generate suitable sRGB values to display including ways to mitigate negative sRGB values. As a cool demo, we ended on colouring in the HgAr emission spectra._____no_output_____


# Notebook from mbod/comm313_spring2021
Path: previous_final_project_examples/jdlish/Data Analysis -- Keyness Analysis.ipynb

# Data Analysis -- Measuring Coronavirus Word Choice and Messaging Focus -- Keyness Analysis_____no_output_____### The sentiment and KWIC analyses I conducted delved into and revealed an important difference between Fox's and CNN's coronavirus response: consistency. Another important difference between Fox's and CNN's coronanvirus response could be their word choice and vocabulary, and their overall messaging from a content perspective. Keyness analysis is one tool that can help provide insight into this.

### Keyness Analysis is a statistical tool that is often used in order to identify significant differences between 2 corpora. Essentially, Keyness Analysis compares the normalized frequencies of linguistic items in two corpora. Keyness Analysis normalizes frequencies of linguistic items by scaling the raw frequency of an item in a text/corpus by the size of the text/corpus.

### In this project, I used Keyness Analysis to compare normalized word frequencies between Fox and CNN news broadcasts, comparing word frequencies in CNN news broadcasts to those in Fox news broadcasts and vice versa.

### This will help provide me with insights into the vocabulary, word choice, and messaging differences that exist between the two news outlets' coronavirus responses. It will help me focus on which words in particular differ between Fox and CNN, which vocabulary differences are meaningful, and how messaging differs between Fox and CNN from a content perspective as a result of this. This will also help to extend KWIC analysis, by drawing insights about each news outlet's overall messaging between January and April, as opposed to focusing more granularly on certain months, the differences between messaging within certain months and between them, and messaging consistency._____no_output_____

%run data_processing.ipynb[nltk_data] Downloading package vader_lexicon to
[nltk_data]     /Commjhub/jupyterhub/comm318_fall2019/jdlish/nltk_data
[nltk_data]     ...
[nltk_data]   Package vader_lexicon is already up-to-date!

### Setting Up Keyness Analysis_____no_output_____

flattened_tokens_cnn = []

#flatten the list
for i in range(len(data_cnn['targeted text'])):
    toks=tokenize(data_cnn['targeted text'][i],True,strip_chars=strip_chars)
    for y in toks:
        flattened_tokens_cnn.append(y)

flattened_tokens_fox = []

#flatten the list
for i in range(len(data_fox['targeted text'])):
    toks=tokenize(data_fox['targeted text'][i],True,strip_chars=strip_chars)

    for y in toks:
        flattened_tokens_fox.append(y)_____no_output_____CNN_words=Counter(flattened_tokens_cnn)
Fox_words=Counter(flattened_tokens_fox)_____no_output_____import math
cnn_vs_fox=calculate_keyness(CNN_words, Fox_words,print_table=False)
cnn_vs_fox.columns=["CNN Word","CNN Word Frequency","Fox Word Frequency","Keyness CNN vs. Fox"]_____no_output_____fox_vs_cnn=calculate_keyness(Fox_words, CNN_words,print_table=False)
fox_vs_cnn.columns=["Fox Word","Fox Word Frequency","CNN Word Frequency","Keyness Fox vs. CNN"]_____no_output_____combined_keyness=pd.concat([cnn_vs_fox.reset_index(drop=True), fox_vs_cnn.reset_index(drop=True)], axis=1)_____no_output_____combined_keyness.iloc[1:25]_____no_output_____

### From the above table, it appears that there are many interesting vocabulary differences between Fox and CNN news broadcasts. It appears that these differencs are meaningful in that they help paint a picture of messaging differences between the two news outlets' coronavirus coverage and reveal which words in particular distinguish between their coronavirus messaging and overall responses.

### Some important words that distinguish CNN news broadcasts from Fox news broadcasts include, 'cases', 'confirmed', 'tested', 'positive', 'outbreakt', 'symptoms', 'deaths', 'died', and 'united states'. Some important words that distinguish Fox news broadcasts from CNN news broadcasts include 'covid19', 'chinese', 'america', 'media', 'china', 'democrats', 'hydroxychloroquine', 'trace', and 'response'.

### CNN appears to have focused its messaging around the United States, the spread of the coronavirus, and the results of this spread. Their response has contained significantly more coverage of the number of deaths in the U.S., the symptoms patients have suffered from, the number of confirmed cases, the spread of the virus, and the evolution of testing in the U.S. compared with Fox's response.

### In contrast, Fox appears to have focussed its messaging around China, focussing a lot of coverge around both the country and Chinese people much more than CNN has. Fox mentions China significantly more than it mentions America (362 times versus 127 times), and mentions Chinese more than it mentions America as well (183 times versus 127 times). Fox also mentions China and Chinese significantly more than CNN does. Moreover, it appears that Fox has made its messaging significantly more political than CNN has. Fox has mentioned the words democrats and biden a total of 166 times which is not only significantly more than CNN has mentioned them, but is also more than Fox has mentioned America (127 times). Moreover, Fox appears to have focussed a lot more attention around the response to coronavirus than CNN has. This is underscored by Fox's focus on the malaria drug hydroxychloroquine, which it has mentioned significantly more than CNN has.

### Overall, it appears that there are certain words that distinguish CNN and Fox coronavirus responses from one another. It also appears that these vocbulary differences paint a picture of the differences between the messaging and content of each news outlet's responses._____no_output_____


# Notebook from nicwolf/notebooks-latest
Path: 06_EPO/e-TeenAstronomyCafe/08_Breaking_the_Solar_System/Breaking_the_Solar_System.ipynb

Breaking the Solar System

And other ways simulations help us understand the Universe

_**Created by Rachel Smullen and Christine O'Donnell in Spring 2020.**_

In this computer activity, we're going to run simulations of planetary systems in order to understand how stable the Solar System is. Would the Solar System look the same if everything was 10 times more massive? What about if the planets were spaced closer together? Farther apart?

We hope that, by the end of today's activity, you'll have the answers!
________no_output_____# Table of Contents

* [How to Use This Notebook](#How-to-Use-This-Notebook)
* [Pre-Activity Setup](#Pre-Activity-Setup)
* [Activity 1: Simulate a Single Planet](#Activity-1:-Simulate-a-Single-Planet)
    * [Part 1.1: Create a Rebound simulation Part](#Part-1.1:-Create-a-Rebound-simulation-Part)
    * [Part 1.2: Add a central star for our planets to orbit](#Part-1.2:-Add-a-central-star-for-our-planets-to-orbit)
    * [Part 1.3: Add planets](#Part-1.3:-Add-planets)
    * [Part 1.4: Run the simulation](#Part-1.4:-Run-the-simulation)
* [Activity 2: Simulate a Hot Jupiter Exoplanet](#Activity-2:-Simulate-a-Hot-Jupiter-Exoplanet)
* [Activity 3: Simulate the Solar System](#Activity-3:-Simulate-the-Solar-System)
* [Activity 4: Break the Solar System](#Activity-4:-Break-the-Solar-System)
________no_output_____# How to Use This Notebook

The webpage you are in is actually an app - much like the ones on your cellphone. This app consists of cells.

An *input* cell looks like a light grey box with an `In [ ]:` on its left. Input cells each contain code - instructions to make the computer do something.

To activate or select a cell, click anywhere inside of it.

    Select the cell below and read its contents.

_____no_output_____

# Text that follows a "#" is known as a comment.
# Comments do not affect your code in any way.
# You should always read the comments at the top of each cell you interact with.
# Comments will be used to describe what the cell's code is actually doing._____no_output_____

To execute or run a selected cell, hit `[Shift + Enter]` on your keyboard.

    Select the cell below and read its contents. Then, run the cell.

 If a warning appears, just click "Run Anyway", this code is safe ;)

 Also, if you want to save your progress, click the "Copy to Drive" button at the top.

_____no_output_____

# Text that DOESN'T follow a "#" is considered code.
# Lines of code are instructions given to your computer.
# The line of code below is a "print" statement.
# A print statement literally prints out the text between its quotes.

print("Congrats! You have successfully run your first cell!")_____no_output_____

Running a cell creates an *output* directly below it. An output can be some text, a graph, an interactive slider, or even nothing at all! For that last case, you know you have run a cell when the `In [ ]:` becomes `In [#]:`, where "#" is any number.  If the code is still in progress, the input cell will look like `In [*]:`.

You can learn more about how Jupyter notebooks work at https://try.jupyter.org/_____no_output________
# Pre-Activity Setup

#### Before we start simulating
We need to load the software we'll use in this activity. We're using a really nice simulation package called `Rebound` that does most of the hard work for us.  The first rule of writing new software is that it has to have a good name!

    Select and run the cell below.

_____no_output_____

#If you are running this in Colab...

!pip install rebound &> /dev/null
print("You have successfully installled: Rebound")_____no_output_____# Now we create a variable with the link to our repository
repoURL = 'https://raw.githubusercontent.com/astro-datalab/notebooks-latest/master/06_EPO/e-TeenAstronomyCafe/'

import requests

url = repoURL+'08_Breaking_the_Solar_System/Files/tools.ipynb'
r = requests.get(url, allow_redirects=True, stream=True)
open('tools.ipynb', 'wb').write(r.content)

print("You have succesfully downloaded the additional tools needed for this activity.")_____no_output_____# Software loading
# DO NOT CHANGE ANYTHING IN THIS CELL

# Simulation package
import rebound

# Math packages
from numpy import *

# Plotting packages and settings
import matplotlib.pyplot as plt
plt.rcParams['animation.html']='jshtml'
plt.rcParams['animation.embed_limit']=1024
%matplotlib inline

# Behind-the-scenes tools to simplify code
%run tools.ipynb

# Temporary fix to some benign warnings that appear when running this on Binder
import warnings
warnings.filterwarnings("ignore")

print('Done! You have successfully imported the libraries.')_____no_output_____

Helpful Reminder(s)

The worksheet to go along with this python notebook activity can be found at this link.

_____no_output________
# Activity 1: Simulate a Single Planet_____no_output_____The type of simulations we're running here are called **N-body simulations** because they use the gravitational force between bodies to predict the positions of those bodies in the future.  Remember that the gravitational force between two bodies is defined as

$$
 F = \frac{-Gm_1m_2}{r^2}
$$

where $G$ is the gravitational constant, $m_1$ is the mass of one body, $m_2$ is the mass of the other body, and $r$ is the distance between bodies. If the objects are closer, or if one of the bodies is massive, the force will be larger, leading to larger tugs between bodies that can make some crazy things happen._____no_output_____There are four steps to running a simulation of a planetary system.  This section walks you through each piece of the puzzle.

Run each of the code cells below when you understand what it does._____no_output_____## Part 1.1: Create a Rebound simulation

We'll add all of our stars and planets to this simulation object._____no_output_____

mysim = initialize_simulation() # This will create a simulation called 'mysim'_____no_output_____

## Part 1.2: Add a central star for our planets to orbit

We must specify the star's _mass_ and _name_. The star should always be the first object added to the simulation.

The star's mass must have units of **solar masses** (units where the Sun's mass is 1) and can have any name you want (as long as it is surrounded by quotation marks `"` or `'`)_____no_output_____

add_star(mysim,name='star',mass=1.0) # add a star to mysim, with mass in units of solar masses_____no_output_____

## Part 1.3: Add planets

Planets must have a *mass*, *name*, and *semi-major axis*. Each planet requires its own line

Planets can also have an *eccentricity*, *inclination*, *argument of perihelion*, *longitude of ascending node*, and *true anomaly*, but these values default to 0 if not specified. Remember that these quantities are described on your worksheet. The values $i$, $\omega$, $\Omega$ and $f$ all have units of degrees ($0-360^\circ$). You can specify as many or as few of these quantities as needed.

The planet's mass must be in units of **Jupiter masses** (units where the mass of Jupiter is 1), and the semi-major axis must have units in **astronomical units (AU)** (units where the distance between the Sun and Earth is 1). Again, the name must be wrapped in quotation marks.

As an aside: Jupiter's mass is ${\approx}1/1000$ times that of the Sun. Earth's mass is ${\approx}\frac{1}{300}$ times that of Jupiter, or $\frac{1}{300{,}000}$ times the mass of the Sun. _____no_output_____

add_planet(mysim,name='planet',mass=1,a=1) # add a planet to mysim with mass in Jupiter masses and a in AU_____no_output_____

## Part 1.4: Run the simulation

Run the simulation for an amount of time that we specify with the variable *end\_time*.  This piece of code returns a movie of the orbits that we can look at by typing the movie's name. It also returns a plot of the semi-major axis, distance from the star, and eccentricity as a function of time

Time in the simulation is measured in **years**.  This step can take a while! The code is running if you see `In [*]:`_____no_output_____

movie = run_simulation(mysim,end_time=10) # run mysim for 10 years
movie # show the movie_____no_output_____

There are some things you should notice that may be helpful in the next steps.

First, while the simulation was running, you should have seen a progress bar with some numbers off to the side. The progress bar is to help you see the status of your simulation.  For very short simulations, the simulation may run too fast for the progress bar to show up. The meaning of the numbers are shown in the picture below.  In particular, the "% Done" and "Time Remaining" numbers are quite useful._____no_output__________no_output_____Second, you have a movie to play with that shows a "top down" view of our planetary system.  The controls of the movie are shown in the picture below._____no_output__________no_output_____Sometimes the movies may appear to run backward or stay stationary.  This is called the ["wagon wheel effect"](https://en.wikipedia.org/wiki/Wagon-wheel_effect).  If the planet appears to stay still, the frames in the movie are being output once every time the planet goes around the star an integer number of times.  If the planet appears to move backward, the frames are being output when the planet goes around more than once but less than twice (or an integer multiple of that) between frames._____no_output_____**Before we go any further**, know that we can put all of the code into one cell to make things simpler. An example is shown below.  You do _not_ need to run this code._____no_output_____

# Create simulation
mysim = initialize_simulation()

# Add a star
add_star(mysim, name='Sun', mass=1.0)

# Add some planets
add_planet(mysim, name='big planet', mass=1, a=1) # a Jupiter at 1 AU
add_planet(mysim, name='small planet', mass=1/300, a=5, e=0.2, i=10, omega=180, Omega=90, f=143) # an eccentric Earth at 5 AU

# Run the simulation and show the movie
movie = run_simulation(mysim,end_time=100)
movie_____no_output_____

___
# Activity 2: Simulate a Hot Jupiter Exoplanet

We first discovered a planet outside our own Solar System in 1995.  The planet is named 51 Pegasi b, and the two scientists who found it were awarded the Nobel Prize in Physics in 2019 for their discovery.

51 Pegasi b, and most of the other exoplanets (planets outside our own Solar System) discovered before 2012 are a class of planets called **hot Jupiters**.  These are _massive_ planets that orbit _very close_ to their host star and are typically _eccentric_.  We've compiled a list of known hot Jupiters at [this link](https://rsmullen.github.io/files/hot_Jupiters.html).
_____no_output_____**Following along in your worksheet, simulate your first planet!**

Select your favorite hot Jupiter from the list linked above. Create a new simulation and add your star and planet. Run the simulation for 5 years. Assume any orbital parameters not listed in the table are 0.

Copy-paste is totally okay, as long as you check all of your numbers! 🙃 _____no_output_____

Before moving on:

Let's wait for everyone to get here before going further.

 Make sure your worksheet is filled out! If you're done early, share your results.

_____no_output_________
# Activity 3: Simulate the Solar System_____no_output_____Before we get to breaking the Solar System, let's first make sure we can get it to work in it's current configuration.

**Add the Sun and the giant planets to the simulation below and run it for 100 years.**

The orbital elements for the Solar System are in your worksheet. Neptune's orbit takes 164 years. Does it even make one full orbit around the Sun? How do you expect the orbital elements will change on long timescales, considering that the Solar System has existed for 4.5 billion years?_____no_output_____

# Initialize the simulation
mysim = initialize_simulation()

# Add the Sun here

# The inner terrestrial planets
add_planet(mysim, name='Mercury', mass=0.00017, a=0.38, e=0.22, i=7.1, omega=30,  Omega=48,  f=201)
add_planet(mysim, name='Venus',   mass=0.0026,  a=0.74, e=0.02, i=3.4, omega=91,  Omega=7,   f=347)
add_planet(mysim, name='Earth',   mass=0.0031,  a=1.00, e=0.01, i=0.0, omega=335, Omega=133, f=86)
add_planet(mysim, name='Mars',    mass=0.00034, a=1.51, e=0.09, i=1.9, omega=292, Omega=49,  f=281)

# Add the giant planets here

# Pluto-Charon, just for fun. :)
add_planet(mysim, name='Pluto-Charon', mass=0.000007, a=39.5, e=0.25, i=17.1, omega=114, Omega=110, f=69)

# Run the simulation
movie = run_simulation(mysim, end_time=0)
movie_____no_output_____

You might have noticed that this simulation took a long time to run compared to the simulations we ran earlier. There are three big things that impact the time you have to twiddle your thumbs when running simulations like these:
1. The finishing time of the simulation (obviously).
2. The number of bodies in the simulation. Each step requires $N^2$ calculations, so for a two planet system, there are four calculations required (the star on each planet and each planet on each other) and for an eight planet system, like the Solar System, there are 256.  Fewer planets means a faster simulation.
3. The distance of the closest planet to the star.  Because we're approximating the orbits between timesteps, we have to take smaller steps to get a good approximation if there is a close in planet. For instance, if we put Mercury in our simulation, one year requires 83 simulation steps, but if Jupiter is the closest planet to the Sun, one year requires 2 simulation steps. A more distant inner planet means a faster simulation._____no_output_____

Before moving on:

Before moving on to the next section of coding, do Section 3 of the worksheet.

Consider what you've learned in the lecture and the coding activities you've already done.

We'll have a group discussion before moving on to the final section.

_____no_output________
# Activity 4: Break the Solar System

How sensitive is the stability of the Solar System? You get to find out!_____no_output_____**Run a few simulations to figure out the smallest change you need to break the Solar System based on the criterion you defined in the worksheet!**

* Each simulation you test should go in its own cell.  At the top of the cell, type a comment to remind yourself what you're testing. Remember that comments start with `#`.
* Run each simulation to an end time of 10 million years.  This can be written in your code as `end_time=10E6` (capital E is important; in code talk, this translates to $10\times10^6$).
* Make sure to fill out your worksheet as you go along!

_____no_output_____

# Parameter being tested:

# Add your simulation below
_____no_output_____# Parameter being tested:

# Add your simulation below
_____no_output_____# Parameter being tested:

# Add your simulation below
_____no_output_____# Parameter being tested:

# Add your simulation below
_____no_output_____# Parameter being tested:

# Add your simulation below
_____no_output_____

Do you really like a movie you made? You can save it to take home by putting the following command at the end of the cell that made the movie (you can change `'mymovie'` to any name you like) . It will then be in Colab's session storage folder (left panel) for you to download to your local computer._____no_output_____

movie.save('mymovie.mpeg')_____no_output_____


# Notebook from sbg/okAPI
Path: Recipes/SBPLAT/volumes_writeToCloudStorage.ipynb

# How do I write files to my own _cloud storage_?
### Overview
Connecting to cloud storage facilitates sharing and leveraging bioinformatics data that is commonly stored there (details [here](http://docs.sevenbridges.com/docs/connecting-cloud-storage-overview)). Here, we show an example of **moving** files from the _Seven Bridges Platform_ to a user's _Amazon Web Services_ **bucket**. Afterwards, an **alias** to the file will be preserved in the user's _Seven Bridges Platform_ project.

### Prerequisites
 1. You need your _authentication token_ and the API needs to know about it. See **Setup_API_environment.ipynb** for details.
 2. You need to have an AWS account with an S3 bucket
 3. You need to be a member (or owner) of a project that has some files in it.

### Setting up Identity and Access Management (IAM) access
There is a detailed tutorial to set up access to your buckets on [AWS](http://docs.sevenbridges.com/v1.0/docs/aws-cloud-storage-tutorial) or [GCP](https://docs.sevenbridges.com/docs/google-cloud-storage-gcs-volumes).

## Imports
We import the _Api_ class from the official sevenbridges-python bindings below._____no_output_____

import sevenbridges as sbg_____no_output_____

## Initialize the object
The `Api` object needs to know your **auth\_token** and the correct path. Here we assume you are using the credentials file in your home directory. For other options see Setup_API_environment.ipynb_____no_output_____

# [USER INPUT] specify credentials file profile {cgc, sbg, default}
prof = 'default'

config_file = sbg.Config(profile=prof)
api = sbg.Api(config=config_file)_____no_output_____

## Mount the volume
Since we have configured the IAM policy in the prior step, we can now mount the volume. Make sure to **replace** (BUCKET-NAME, INSERT ACCESS KEY ID, and INSERT SECRET ACCESS KEY) below

### Warning
You only need to mount a volume **once**. If you have already done this, then skip this cell and go to _Get details of the volume_. If you try to mount it more than once, you will get an error (likely error: `Forbidden: Could not obtain cross-write access on the service. Check the documentation.`).

#### Additional information
 * Detailed documentation of this particular REST architectural style request is available [here](http://docs.sevenbridges.com/docs/create-a-volume-v2)_____no_output_____

volume_import = api.volumes.create_s3_volume(
    name='my_volume_RW',
    bucket='BUCKET-NAME',
    access_key_id='INSERT ACCESS KEY ID',
    secret_access_key = 'INSERT SECRET ACCESS KEY',
    access_mode='RW')_____no_output_____

## Get details of the volume
Let's list all our volumes and get one volume's (`my_volume_RW`, which we have just imported in the prior cell) details to make sure it's mounted as we expected.

#### Additional information
 * Detailed documentation of these particular REST architectural style request are available [here (list)](http://docs.sevenbridges.com/docs/list-volumes-v2) and [here (details)](http://docs.sevenbridges.com/docs/get-details-of-a-volume-v2)_____no_output_____

# [USER INPUT] Set volume name here:
volume_name = 'my_volume'

all_volumes = api.volumes.query()

my_volume = [v for v in all_volumes.all()
            if v.name == volume_name]

if not my_volume:
    print('Volume {} does not exist, check name / mounting'
          .format(volume_name))
    raise KeyboardInterrupt
else:
    my_volume = my_volume[0]

print(my_volume.name)_____no_output_____

## Get some files to move
Here we pick a project and a few files to move. In case you don't have any files, you could add them via the [GUI](http://docs.sevenbridges.com/docs/copy-files-using-the-visual-interface) or an API [recipe](files_copyFromMyProject.ipynb).

#### PROTIPS
 * Using this [recipe](files_upload_and_setMetadata.ipynb) to upload some files would mean **you don't need to change** names in the _file\_list_ below (if this is the first time you are running this script).
 * A detailed _recipe_ for listing projects is [here](projects_listAll.ipynb)
 * A detailed _recipe_ for listing files is [here](files_listAll.ipynb)_____no_output_____

# [USER INPUT] Set project name here:
project_id = 'division-name/project-name'
file_list = ['files_listAll.ipynb',
            'files_copyFromMyProject.ipynb',
            'files_copyFromPublicReference.ipynb']

# Find files in your project matching your file_list
my_files = api.files.query(limit=100, project=project_id,
                          names=file_list)_____no_output_____

## Start an export job
Spin up a job to export files from the _Seven Bridges Platform_ to your _Cloud Storage_ (Volume).

#### Additional information
 * Detailed documentation of these particular REST architectural style request are available [here](https://docs.sevenbridges.com/reference#start-a-bulk-export-job)

### Possible ERRORS
Note that you are only permitted to export a file _we host for you_. This **does not include** **Public Reference** files (even if you have _copied_ them into your project), other **imported files** (aliases) or **archived files** that have not been restored.
The error you would likely see for doing this is `Forbidden: Requested file cannot be exported. Check the documentation.`_____no_output_____

# Loop through selected files and submit a bulk export request
exports = []

for f in my_files:
    export = {
            'file':f,
            'volume': my_volume,
            'location':f.name
    }
    exports.append(export)

export_jobs = api.exports.bulk_submit(exports=exports, copy_only=True)

errors = []
for bulk_item, job in zip(exports, export_jobs):
    if job.error:
        error_message = "File: %s - %s" % (
            bulk_item['file'].name, job.error.message)
        errors.append(error_message)
if errors:
    print(
        'There were errors with bulk export submission:',
        '"; "'.join(errors)
    )

# Monitor export jobs where no errors were encountered
submitted_jobs = [job.resource for job in export_jobs if job.resource]_____no_output_____

## List and detail export jobs
The `api.exports.bulk_get` method will capture details of all exports which have been sent in the `bulk_submit` call.

#### Additional information
 * Detailed documentation of these particular REST architectural style request are available [here](http://docs.sevenbridges.com/docs/list-export-jobs-v2) and [here](https://docs.sevenbridges.com/reference#get-details-of-a-bulk-export-job)_____no_output_____

export_jobs = api.exports.bulk_get(exports=[s.id for s in submitted_jobs])

for j in export_jobs:
    print('File {} export stated {}; it is {}'
         .format(j.resource.destination, j.resource.started_on, j.resource.state))
print('\n')_____no_output_____


# Notebook from HAHerrmann/FluxSamplingCol0Fum2
Path: FluxSampling/MakeModel.ipynb

### Imposing Model Constraints

Here we take measured gas exchange, metabolite and proteomics data in order to constraint the flux of the reaction in the model by [Arnold and Nikoloski, 2014](https://www.ncbi.nlm.nih.gov/pubmed/24808102).

We build four models using the experimental data:
- Wild-type 20 degrees,
- Wild-type after 7 days in 4 degrees,
- fum2 mutant 20 degrees,
- fum2 mutant after 7 days in 4 degrees. _____no_output_____

<code>
# Loading Required Packages
import cobra
from cobra.flux_analysis import flux_variability_analysis
from cobra.flux_analysis.loopless import add_loopless, loopless_solution
from cobra.flux_analysis import pfba
import pandas as pd
import numpy as np
import itertools_____no_output_____# Parameterizing the model for Genotype and Condition
%run ConstrainModel.ipynb
AN_constr(100,0.003,0.006,0.028,"WT Cntl")
%run ConstrainModel.ipynb
AN_constr(100,0.012,0.0,0.042,"fum2 Cntl")
%run ConstrainModel.ipynb
AN_constr(100,0.012,0.023,0.051,"WT cold")
%run ConstrainModel.ipynb
AN_constr(94,0.025,0.0,0.063,"fum2 Cold")
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(ATCG00020 and ATCG00680 and ATCG00280 and ATCG00270 and ATCG00580 and ATCG00570 and ATCG00710 and ATCG00080 and ATCG00550 and ATCG00070 and ATCG00560 and ATCG00220 and ATCG00700 and (AT5G66570 or AT3G50820) and AT1G06680 and (AT4G21280 or AT4G05180) and AT1G79040 and AT1G44575 and ATCG00690 and AT3G21055 and AT2G30570 and AT2G06520 and AT1G67740 and ATCG00300)' for <Reaction PSII_h at 0x7f377a1ff090>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(ATCG00540 and ATCG00720 and AT4G03280 and ATCG00730 and ATCG00600 and ATCG00590 and AT2G26500 and ATCG00210)' for <Reaction Cytb6f_h at 0x7f377a1ff190>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '8*(ATCG00490) and 8*(AT5G38430 or AT5G38420 or AT1G67090 or AT5G38410)' for <Reaction RBC_h at 0x7f377a1ffd90>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '4*(AT3G26650 or AT1G12900) or (2*(AT3G26650 or AT1G12900) and 2*(AT1G42970))' for <Reaction GAPDH1_h at 0x7f377a1ff690>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT3G55440 or AT2G21170)' for <Reaction TPI_h at 0x7f377a1ff710>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '4*(AT2G01140 or AT4G26530 or AT3G52930 or AT4G38970 or AT5G03690 or AT2G21330)' for <Reaction FBPA_h at 0x7f377a1ff910>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '4*(AT3G54050)' for <Reaction FBPase_h at 0x7f377a1ff890>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT3G60750 or AT2G45290)' for <Reaction FTK_h at 0x7f3778a97710>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '4*(AT2G01140 or AT4G26530 or AT3G52930 or AT4G38970 or AT5G03690 or AT2G21330)' for <Reaction SBPA_h at 0x7f3778a97490>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT3G55800)' for <Reaction SBPase_h at 0x7f3778a97290>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT3G60750 or AT2G45290)' for <Reaction STK_h at 0x7f3779b1d0d0>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '8*(AT5G61410)' for <Reaction Ru5PE_h at 0x7f3779b1db10>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT3G04790)' for <Reaction R5PI_h at 0x7f3779b1d050>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT1G32060)' for <Reaction Ru5PK_h at 0x7f377963f2d0>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT4G24620)' for <Reaction PGI_h at 0x7f377963f910>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT5G19220 or AT1G27680 or AT4G39210 or AT2G21590) and 2*(AT5G48300 or AT1G05610)' for <Reaction AGPase_h at 0x7f377963fe10>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT3G55440 or AT2G21170)' for <Reaction TPI_c at 0x7f377933bf90>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '4*(AT4G26520 or AT4G26530 or AT3G52930 or AT2G36460 or AT5G03690)' for <Reaction FBPA_c at 0x7f377933ba90>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '4*(AT1G43670)' for <Reaction FBPase_c at 0x7f377a696c10>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '4*(AT1G07110)' for <Reaction F6PK2_c at 0x7f377933b4d0>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '4*(AT1G07110)' for <Reaction F26BPPh_c at 0x7f377933b950>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT4G24620 or AT5G42740)' for <Reaction PGI_c at 0x7f377933bc10>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT5G20280) or 4*(AT5G20280)' for <Reaction S6PS_c at 0x7f377933b290>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT2G35840 or AT3G52340)' for <Reaction S6PPh_c at 0x7f377933b310>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '4*(AT5G20830 or AT5G49190 or AT3G43190)' for <Reaction SucS_c at 0x7f377933bc90>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '4*(AT1G53310 or AT2G42600 or AT3G14940 or AT1G68750)' for <Reaction PEPC2_c at 0x7f377943ab50>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT2G29560 or AT2G36530)' for <Reaction Enol_c at 0x7f377943a210>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '4*(AT3G04120 or AT1G13440)' for <Reaction GAPDH2_c at 0x7f377943a550>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '4*(AT1G79530 or AT1G16300)' for <Reaction GAPDH2_h at 0x7f37794851d0>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT1G74030 or AT2G36530)' for <Reaction Enol_h at 0x7f37794856d0>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '4*(AT3G04050 or AT5G08570 or AT3G25960 or AT2G36580 or AT3G55650 or AT3G55810 or AT5G63680 or AT3G52990)' for <Reaction PyrK_c at 0x7f3779485050>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '4*(AT3G22960) and 4*(AT5G52920 or AT1G32440)' for <Reaction PyrK_h at 0x7f37794850d0>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT1G59900) and 2*(AT5G50850)' for <Reaction PyrDH1_m at 0x7f37794855d0>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT1G59900) and 2*(AT5G50850)' for <Reaction PyrDH2_m at 0x7f3778d1d4d0>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '3*(AT3G52200 or AT3G13930 or AT1G54220)' for <Reaction DHLAcT_m at 0x7f3778d1db10>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT1G48030 or AT3G17240)' for <Reaction DHLDH2_m at 0x7f3778d1d0d0>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT5G65750 or AT3G55410)' for <Reaction KGDH_m at 0x7f3778cef410>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '3*(AT5G55070 or AT4G26910)' for <Reaction DHLST_m at 0x7f3778cef610>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '(ATMG01275 or ATMG01120 or ATMG00516) and (ATMG00285 or ATMG01320) and ATMG00990 and (ATMG00580 or ATMG00650) and (ATMG00513 or ATMG00665 or ATMG00060) and ATMG00270 and ATMG00510 and ATMG00070 and AT5G37510 and AT5G11770 (AT1G79010 or AT1G16700) and AT5G08530 and AT4G02580' for <Reaction cplx1_m at 0x7f3778a16b90>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '3*(ATMG01190) and 3*(AT5G08670 or AT5G08690 or AT5G08680) and AT2G33040 and (AT5G13450 or AT5G47030) and AT1G51650 and (ATMG00410 or ATMG01170) and 2*(ATMG00640 or ATMG00480) and 12*(ATMG01080 or AT2G07671) and AT3G52300' for <Reaction cplx5_m at 0x7f3778a16410>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '8*(ATCG00490) and 8*(AT5G38430 or AT5G38420 or AT1G67090 or AT5G38410)' for <Reaction RBO_h at 0x7f3778a16110>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '4*(AT1G20620 or AT1G20630 or AT4G35090)' for <Reaction CAT_p at 0x7f3778a167d0>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT4G33010 or AT2G26080)' for <Reaction GlyDH_m at 0x7f3778d03950>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT1G48030 or AT3G17240)' for <Reaction DHLDH1_m at 0x7f3778d03550>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '4*(AT4G37930 or AT5G26780)' for <Reaction GlyHMT_m at 0x7f37795ca9d0>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT2G13360)' for <Reaction SGAT_p at 0x7f37795ca650>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '4*(AT2G19900 or AT5G11670 or AT5G25880)' for <Reaction MalDH2NADP_c at 0x7f377a5c62d0>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '4*(AT5G11670 or AT5G25880 or AT1G79750)' for <Reaction MalDH2NADP_h at 0x7f37795dfb90>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '4*(AT1G10670 or AT1G60810 or AT1G09430) and 4*(AT3G06650 orAT5G49460)' for <Reaction ATPCitL_c at 0x7f3778ed8890>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '(AT5G16390 or AT5G15530) and AT5G35360 and 2*(AT2G38040) and 2*(ATCG00500)' for <Reaction ACoAC_h at 0x7f377925b990>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT4G35460 or AT2G17420 or AT2G41680)' for <Reaction TRXR_c at 0x7f377925b690>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT4G12440 or AT5G11160 or AT4G22570 or AT1G27450 or AT1G80050)' for <Reaction ADPRPPT_c at 0x7f377925b590>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT1G77760 or AT1G37130)' for <Reaction NO3R1_c at 0x7f3779e60750>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT1G77760 or AT1G37130)' for <Reaction NO3R2_c at 0x7f3779e60fd0>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '4*(AT3G22890 or AT1G19920 or AT4G14680 or AT5G43780)' for <Reaction ATPSL_h at 0x7f3779e60350>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT3G54660)' for <Reaction GSSGR_h at 0x7f3779e606d0>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '(AT1G08065 or AT5G04180 or AT4G20990 or AT4G21000 or AT2G28210 or AT3G52720) or 8*(AT1G23730 or AT5G14740)' for <Reaction HCO3DHA_c at 0x7f3779e603d0>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '(AT4G20990 or AT1G08080 or AT3G52720) or 8*(AT1G23730 or AT1G70410 or AT1G58180 or AT3G01500 or AT5G14740 or AT4G33580)' for <Reaction HCO3DHA_h at 0x7f3779e60a10>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '6*(AT3G57560)' for <Reaction AGluK at 0x7f3779e60250>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT5G08100) and 2*(AT3G16150)' for <Reaction Asnase_c at 0x7f37784f0f90>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '6*(AT1G55920 or AT2G17640 or AT3G13110 or AT4G35640 or AT5G56760)' for <Reaction SerAcT_c at 0x7f377818b210>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '6*(AT1G55920 or AT3G13110)' for <Reaction SerAcT_h at 0x7f3779e60390>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '6*(AT1G55920 or AT3G13110)' for <Reaction SerAcT_m at 0x7f377818b610>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT4G14880 or AT3G22460)' for <Reaction CysS_c at 0x7f377818b790>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT3G61440 or AT3G03630 or AT4G14880 or AT2G43750)' for <Reaction CysS_h at 0x7f377818b8d0>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT3G61440 or AT3G03630 or AT2G43750 or AT5G28020)' for <Reaction CysS_m at 0x7f37784f0d90>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '6*(AT5G18170 or AT5G07440 or AT3G03910)' for <Reaction GluDH1NAD_m at 0x7f377818b490>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '6*(AT5G18170 or AT5G07440 or AT3G03910)' for <Reaction GluDH1NADP_m at 0x7f377818bdd0>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '6*(AT5G18170 or AT5G07440)' for <Reaction GluDH2NAD_m at 0x7f377818be10>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '6*(AT5G17330 or AT1G65960 or AT2G02000 or AT2G02010 or AT3G17760)' for <Reaction GluDC_c at 0x7f377818be50>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT3G22200)' for <Reaction GABATA1_m at 0x7f377818b990>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT3G22200)' for <Reaction GABATA2_m at 0x7f377818bf90>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '4*(AT1G79440)' for <Reaction SCASeADH_m at 0x7f377819c290>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '8*(AT5G37600 or AT3G17820 or AT5G16570 or AT1G66200)' for <Reaction GlnS_c at 0x7f377819c610>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '8*(AT3G17820 or AT1G48470 or AT5G35630)' for <Reaction GlnS_h at 0x7f377818bfd0>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '8*(AT5G35630)' for <Reaction GlnS_m at 0x7f377819c890>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '4*(AT1G20620 or AT1G20630 or AT4G35090)' for <Reaction CAT_h at 0x7f377819c2d0>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT2G13360' for <Reaction SGAT_h at 0x7f377819c450>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '4*(AT3G10050)' for <Reaction ThrDA_h at 0x7f377812f650>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT3G48560)' for <Reaction ALS1_h at 0x7f377812f710>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT3G48560)' for <Reaction ALS2_h at 0x7f377812f8d0>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT3G48560)' for <Reaction ALS3_h at 0x7f377812fb10>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT1G18500) or 4*(AT1G74040)' for <Reaction 2IPMS_h at 0x7f377812ff50>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '4*(AT4G19710 or AT1G31230 or AT5G13280 or AT3G02020 or AT5G14060)' for <Reaction AspK_h at 0x7f3778141050>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT1G14810)' for <Reaction Asp_DASH_SeADH_h at 0x7f37781411d0>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT4G33680)' for <Reaction DAPAT_h at 0x7f3778141650>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '4*(AT1G31230 AT4G19710)' for <Reaction HSerDHNADP_h at 0x7f3778141c10>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '4*(AT1G31230 AT4G19710)' for <Reaction HSerDHNAD_h at 0x7f3778141790>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '4*(AT3G57050)' for <Reaction CTHL_h at 0x7f3778141fd0>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT2G44160 or AT3G59970)' for <Reaction 5M_DASH_THFor_c at 0x7f3778141e50>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '4*(AT4G13930 or AT4G13890 or AT1G22020 or AT1G36370 or AT4G37930 or AT5G26780)' for <Reaction GlyHMT_c at 0x7f37781544d0>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT4G29840 or AT1G72810)' for <Reaction ThrS_h at 0x7f3778162e50>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT1G24807) and 2*(AT3G55870 or AT5G05730 or AT2G29690)' for <Reaction ANTS_h at 0x7f3778162e10>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT2G38280)' for <Reaction AMPDA_c at 0x7f37780f4f90>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT3G57610)' for <Reaction DCAMPS_h at 0x7f3778106110>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT2G21790) and 2*(AT3G23580 or AT3G27060)' for <Reaction ADPR_c at 0x7f3778106bd0>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT2G21790) and 2*(AT3G23580 or AT3G27060)' for <Reaction CDPR_c at 0x7f3778106e10>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT2G21790) and 2*(AT3G23580 or AT3G27060)' for <Reaction GDPR_c at 0x7f3778106e50>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '2*(AT2G21790) and 2*(AT3G23580 or AT3G27060)' for <Reaction UDPR_c at 0x7f3778106f10>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '3*(AT3G46940)' for <Reaction dUTPP_c at 0x7f3778106f90>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '6*(AT4G09320 or AT5G63310)' for <Reaction GDPK_c at 0x7f3778117090>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '6*(AT4G09320 or AT5G63310)' for <Reaction GDPK_h at 0x7f3778117410>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '6*(AT4G09320 or AT5G63310)' for <Reaction UDPK_c at 0x7f3778117490>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '6*(AT4G09320 or AT5G63310)' for <Reaction dADPK_c at 0x7f3778117ad0>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '6*(AT4G09320 or AT5G63310)' for <Reaction dCDPK_c at 0x7f3778117c10>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '6*(AT4G09320 or AT5G63310)' for <Reaction dGDPK_c at 0x7f3778117d50>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '6*(AT4G09320 or AT5G63310)' for <Reaction dTDPK_c at 0x7f3778117ed0>
cobra/core/reaction.py:394 UserWarning: malformed gene_reaction_rule '6*(AT4G09320 or AT5G63310)' for <Reaction dUDPK_c at 0x7f3778117e90>

</code>