# Enzyme Modules

An "enzyme module" is defined as a mechanistic description of a reaction consisting of mass action rate laws for all known reaction steps (Du et al., 2016). In **MASSpy**, enzyme modules are represented by the `EnzymeModule` object.

To demonstrate the utility of an `EnzymeModule` object and how it aids in constructing mechanistic models of enzyme behavior, an `EnzymeModule` of hexokinase$^{1, 2}$ is constructed and then merged with a model of glycolysis$^{3}$ for verification.

## Constructing Enzyme Modules

In order to construct the `EnzymeModule` of hexokinase, the following information is necessary:

1. The enzyme is a monomer.
2. The enzyme binding of substrates follows a random sequential mechanism.
3. The enzyme experiences product inhibtion and is competitively inhibited by 23DPG when complexed with D-glucose.

Total HEX1 Concentration$^2$: $\text{[HEX1]}_{total} = 24 nM = 0.000024 mM$.

```python
from operator import attrgetter

from mass import MassMetabolite
from mass.enzyme_modules import EnzymeModule
from mass.test import create_test_model

# Load the glycolysis and hemoglobin models, then merge them
glycolysis = create_test_model("Glycolysis")
hemoglobin = create_test_model("Hemoglobin")
glyc_hb = glycolysis.merge(hemoglobin, inplace=False)
```

The `EnzymeModule` is a subclass of the `MassModel`, meaning that it inherits the methods and behaviors of the `MassModel` object.
Like a `MassModel`, an `EnzymeModule` object requires a unique identifier in order to be created. Optionally, the `name` and `subsystem` attributes are set during initialization.

```python
HEX1 = EnzymeModule("HEX1", name="Hexokinase (D-glucose:ATP)",
                    subsystem="Glycolysis")
```

### Defining the enzyme ligands

The ligands that interact with the enzyme (e.g. as the substrates, activators, and inhibitors) are created as `MassMetabolite` objects and added to the model.

```python
glc__D_c = MassMetabolite(
    "glc__D_c",
    name="D-Glucose",
    formula="C6H12O6",
    charge=0,
    compartment="c")
g6p_c = MassMetabolite(
    "g6p_c",
    name="D-Glucose 6-phosphate",
    formula="C6H11O9P",
    charge=-2,
    compartment="c")
atp_c = MassMetabolite(
    "atp_c",
    name="ATP",
    formula="C10H12N5O13P3",
    charge=-4,
    compartment="c")
adp_c = MassMetabolite(
    "adp_c",
    name="ADP",
    formula="C10H12N5O10P2",
    charge=-3,
    compartment="c")
_23dpg_c = MassMetabolite(
    "_23dpg_c",
    name="2,3-Disphospho-D-glycerate",
    formula="C3H3O10P2",
    charge=-5,
    compartment="c")
h_c = MassMetabolite(
    "h_c",
    name="H+",
    formula="H",
    charge=1,
    compartment="c")

HEX1.add_metabolites([glc__D_c, g6p_c, atp_c, adp_c, _23dpg_c, h_c])
```

Once added to the `EnzymeModule`, ligands can be accessed using the `enzyme_module_ligands` attribute.

```python
HEX1.enzyme_module_ligands
```

    [<MassMetabolite glc__D_c at 0x7ff42b809390>,
     <MassMetabolite g6p_c at 0x7ff42b809350>,
     <MassMetabolite atp_c at 0x7ff42b8093d0>,
     <MassMetabolite adp_c at 0x7ff42b809410>,
     <MassMetabolite _23dpg_c at 0x7ff42b809490>,
     <MassMetabolite h_c at 0x7ff42b8094d0>]

To keep track of the roles played by various ligands in the module, the `enzyme_module_ligands_categorized` attribute is set. The attribute takes a `dict`, with categories as keys and relevant `MassMetabolite` objects as values. Note that an object can be a part of multiple categories.

```python
HEX1.enzyme_module_ligands_categorized =  {
    "substrates": glc__D_c,
    "cofactors": atp_c,
    "inhibitors": _23dpg_c,
    "products": [adp_c, g6p_c, h_c]}
HEX1.enzyme_module_ligands_categorized
```

    [<Group substrates at 0x7ff42b809ad0>,
     <Group cofactors at 0x7ff42b809bd0>,
     <Group inhibitors at 0x7ff42b809c50>,
     <Group products at 0x7ff42b809cd0>]

For each category, a `cobra.Group` is created containing the relevant objects. Once set, the attribute returns a `cobra.DictList` that contains the categorized groups. The groups and their members are printed as follows:

```python
for group in HEX1.enzyme_module_ligands_categorized:
    print("{0}: {1}".format(
        group.id, str(sorted([m.id for m in group.members]))))
```

    substrates: ['glc__D_c']
    cofactors: ['atp_c']
    inhibitors: ['_23dpg_c']
    products: ['adp_c', 'g6p_c', 'h_c']

### Defining the enzyme module forms

After adding `MassMetabolite` objects of ligands to the model, the various forms of the enzyme must be defined. These forms are represented by `EnzymeModuleForm` objects.

The `EnzymeModuleForm` object inherits from the `MassMetabolite` and is treated like any other metabolite in the model. However, the `EnzymeModuleForm` object contains the additional `bound_metabolites` attribute to assist in tracking metabolites bound to the enzyme form.

The `EnzymeModule.make_enzyme_module_form()` method allows for the creation of an `EnzymeModuleForm` object while assigning categories for the  `EnzymeModuleForm` in the process. Using `make_enzyme_module_form()` also adds the species to the module upon creation, accessible via the `EnzymeModule.enzyme_module_forms` attribute.

```python
hex1_c = HEX1.make_enzyme_module_form(
    "hex1_c",
    name="automatic",
    categories="Active",
    compartment="c")

hex1_A_c = HEX1.make_enzyme_module_form(
    "hex1_A_c",  # A stands complexted with ATP
    name="automatic",
    categories="Active",
    bound_metabolites={atp_c: 1},
    compartment="c")

hex1_G_c = HEX1.make_enzyme_module_form(
    "hex1_G_c",  # G stands for complexed with Glucose
    name="automatic",
    categories="Active",
    bound_metabolites={glc__D_c: 1},
    compartment="c")

hex1_AG_c = HEX1.make_enzyme_module_form(
    "hex1_AG_c",
    name="automatic",
    categories="Active",
    bound_metabolites={glc__D_c: 1, atp_c: 1},
    compartment="c")

hex1_G_CI_c = HEX1.make_enzyme_module_form(
    "hex1_G_CI_c",  # CI stands for competitive inhibition
    name="automatic",
    categories="Inhibited",
    bound_metabolites={glc__D_c: 1, _23dpg_c: 1},
    compartment="c")

hex1_A_PI_c = HEX1.make_enzyme_module_form(
    "hex1_A_PI_c",  # PI stands for competitive inhibition
    name="automatic",
    categories="Inhibited",
    bound_metabolites={adp_c: 1},
    compartment="c")

hex1_G_PI_c = HEX1.make_enzyme_module_form(
    "hex1_G_PI_c",  # PI stands for competitive inhibition
    name="automatic",
    categories="Inhibited",
    bound_metabolites={g6p_c: 1},
    compartment="c")

HEX1.enzyme_module_forms
```

    [<EnzymeModuleForm hex1_c at 0x7ff42b82e750>,
     <EnzymeModuleForm hex1_A_c at 0x7ff42b82e790>,
     <EnzymeModuleForm hex1_G_c at 0x7ff42b82e850>,
     <EnzymeModuleForm hex1_AG_c at 0x7ff42b82e710>,
     <EnzymeModuleForm hex1_G_CI_c at 0x7ff42b82eb50>,
     <EnzymeModuleForm hex1_A_PI_c at 0x7ff42b82ee10>,
     <EnzymeModuleForm hex1_G_PI_c at 0x7ff42b82ed10>]

The `bound_metabolites` attribute represents the ligands bound to the site(s) of enzyme.

```python
# Print automatically generated names
for enzyme_form in HEX1.enzyme_module_forms:
    print("Bound to sites of {0}:\n{1}\n".format(
        enzyme_form.id, {
            ligand.id: coeff
            for ligand, coeff in enzyme_form.bound_metabolites.items()}))
```

    Bound to sites of hex1_c:
    {}

    Bound to sites of hex1_A_c:
    {'atp_c': 1}

    Bound to sites of hex1_G_c:
    {'glc__D_c': 1}

    Bound to sites of hex1_AG_c:
    {'glc__D_c': 1, 'atp_c': 1}

    Bound to sites of hex1_G_CI_c:
    {'glc__D_c': 1, '_23dpg_c': 1}

    Bound to sites of hex1_A_PI_c:
    {'adp_c': 1}

    Bound to sites of hex1_G_PI_c:
    {'g6p_c': 1}

Setting the `bound_metabolites` attribute upon creation allow the `formula` and `charge` attributes of the various forms also to be set while ensuring mass and charge balancing is maintained. Note that the enzyme is represented as a moiety, and the ligands bound to the enzyme are represented in the chemical formula.

```python
# Get the elemental matrix for the enzyme
df = HEX1.get_elemental_matrix(array_type="DataFrame")
# Use iloc to only look at EnzymeModuleForms
df.iloc[:, 6:]
```

      hex1_c
      hex1_A_c
      hex1_G_c
      hex1_AG_c
      hex1_G_CI_c
      hex1_A_PI_c
      hex1_G_PI_c

      C
      0.0
      10.0
      6.0
      16.0
      9.0
      10.0
      6.0

      H
      0.0
      12.0
      12.0
      24.0
      15.0
      12.0
      11.0

      O
      0.0
      13.0
      6.0
      19.0
      16.0
      10.0
      9.0

      P
      0.0
      3.0
      0.0
      3.0
      2.0
      2.0
      1.0

      N
      0.0
      5.0
      0.0
      5.0
      0.0
      5.0
      0.0

      S
      0.0
      0.0
      0.0
      0.0
      0.0
      0.0
      0.0

      q
      0.0
      -4.0
      0.0
      -4.0
      -5.0
      -3.0
      -2.0

      [HEX]
      1.0
      1.0
      1.0
      1.0
      1.0
      1.0
      1.0

Setting the `name` argument as "automatic" in the `EnzymeModule.make_enzyme_module_form()` method causes a name for the `EnzymeModuleForm` to be generated based on the metabolites in the `bound_metabolites` attribute.

```python
# Print automatically generated names
for enzyme_form in HEX1.enzyme_module_forms:
    print(enzyme_form.name)
```

    HEX1
    HEX1-atp complex
    HEX1-glc__D complex
    HEX1-glc__D-atp complex
    HEX1-glc__D-_23dpg complex
    HEX1-adp complex
    HEX1-g6p complex

The `categories` argument allows for `EnzymeModuleForm` objects to be placed into `cobra.Group` objects representing those categories. As with the ligands, the categorized enzyme module forms are returned in a `DictList` of `Group` objects by the `enzyme_module_forms_categorized` attribute.

```python
for group in HEX1.enzyme_module_forms_categorized:
    print("{0}: {1}".format(
        group.id, str(sorted([m.id for m in group.members]))))
```

    Active: ['hex1_AG_c', 'hex1_A_c', 'hex1_G_c', 'hex1_c']
    Inhibited: ['hex1_A_PI_c', 'hex1_G_CI_c', 'hex1_G_PI_c']

Alternatively, the `enzyme_module_forms_categorized` attribute can be set using a `dict`:

```python
HEX1.enzyme_module_forms_categorized =  {
    "competitively_inhibited": hex1_G_CI_c}

for group in HEX1.enzyme_module_forms_categorized:
    print("{0}: {1}".format(
        group.id, str(sorted([m.id for m in group.members]))))
```

    Active: ['hex1_AG_c', 'hex1_A_c', 'hex1_G_c', 'hex1_c']
    Inhibited: ['hex1_A_PI_c', 'hex1_G_CI_c', 'hex1_G_PI_c']
    competitively_inhibited: ['hex1_G_CI_c']

### Defining enzyme module reactions

The next step is to define all of the reaction steps that represent the catalytic mechanism and regulation of the enzyme module. These reactions are represented as `EnzymeModuleReaction` objects.

The `EnzymeModuleReaction` object inherits from the `MassReaction` and is treated like any other reaction in the model. Like the `make_enzyme_module_form()` method, the `make_enzyme_module_reaction()` method allows for the creation of an `EnzymeModuleReaction` object while assigning categories for the `EnzymeModuleReaction` in the process.

Species that exist in the model can also be added to the reaction by providing a dictionary of metabolites and their stoichiometric coefficients to the `metabolites_to_add` argument.

```python
HEX1_1 = HEX1.make_enzyme_module_reaction(
    "HEX1_1",
    name="Automatic",
    subsystem="Glycolysis",
    reversible=True,
    categories="product_inhibition",
    metabolites_to_add={
        "hex1_c": -1,
        "adp_c": -1,
        "hex1_A_PI_c": 1})

HEX1_2 = HEX1.make_enzyme_module_reaction(
    "HEX1_2",
    name="Automatic",
    subsystem="Glycolysis",
    reversible=True,
    categories="product_inhibition",
    metabolites_to_add={
        "hex1_c": -1,
        "g6p_c": -1,
        "hex1_G_PI_c": 1})

HEX1_3 = HEX1.make_enzyme_module_reaction(
    "HEX1_3",
    name="Automatic",
    subsystem="Glycolysis",
    reversible=True,
    categories="glc__D_c_binding",
    metabolites_to_add={
        "hex1_c": -1,
        "glc__D_c": -1,
        "hex1_G_c": 1})

HEX1_4 = HEX1.make_enzyme_module_reaction(
    "HEX1_4",
    name="Automatic",
    subsystem="Glycolysis",
    reversible=True,
    categories="atp_c_binding",
    metabolites_to_add={
        "hex1_c": -1,
        "atp_c": -1,
        "hex1_A_c": 1})

HEX1_5 = HEX1.make_enzyme_module_reaction(
    "HEX1_5",
    name="Automatic",
    subsystem="Glycolysis",
    reversible=True,
    categories="competitive_inhibition",
    metabolites_to_add={
        "hex1_G_c": -1,
        "_23dpg_c": -1,
        "hex1_G_CI_c": 1})

HEX1_6 = HEX1.make_enzyme_module_reaction(
    "HEX1_6",
    name="Automatic",
    subsystem="Glycolysis",
    reversible=True,
    categories="atp_c_binding",
    metabolites_to_add={
        "hex1_G_c": -1,
        "atp_c": -1,
        "hex1_AG_c": 1})

HEX1_7 = HEX1.make_enzyme_module_reaction(
    "HEX1_7",
    name="Automatic",
    subsystem="Glycolysis",
    reversible=True,
    categories="glc__D_c_binding",
    metabolites_to_add={
        "hex1_A_c": -1,
        "glc__D_c": -1,
        "hex1_AG_c": 1})

HEX1_8 = HEX1.make_enzyme_module_reaction(
    "HEX1_8",
    name="Automatic",
    subsystem="Glycolysis",
    reversible=True,
    categories="catalyzation",
    metabolites_to_add={
        "hex1_AG_c": -1,
        "hex1_c": 1,
        "adp_c": 1,
        "g6p_c": 1,
        "h_c": 1})

for reaction in HEX1.enzyme_module_reactions:
    print(reaction)
```

    HEX1_1: adp_c + hex1_c <=> hex1_A_PI_c
    HEX1_2: g6p_c + hex1_c <=> hex1_G_PI_c
    HEX1_3: glc__D_c + hex1_c <=> hex1_G_c
    HEX1_4: atp_c + hex1_c <=> hex1_A_c
    HEX1_5: _23dpg_c + hex1_G_c <=> hex1_G_CI_c
    HEX1_6: atp_c + hex1_G_c <=> hex1_AG_c
    HEX1_7: glc__D_c + hex1_A_c <=> hex1_AG_c
    HEX1_8: hex1_AG_c <=> adp_c + g6p_c + h_c + hex1_c

The `categories` argument allows for `EnzymeModuleReactions` objects to be placed into `cobra.Group` objects representing those categories. As with the ligands and enzyme forms, a `DictList` of the relevant groups are returned with the `enzyme_module_reactions_categorized` attribute.

```python
HEX1.enzyme_module_reactions_categorized
```

    [<Group product_inhibition at 0x7ff42b87ae10>,
     <Group glc__D_c_binding at 0x7ff42b87c650>,
     <Group atp_c_binding at 0x7ff42b87ca50>,
     <Group competitive_inhibition at 0x7ff42b87cc90>,
     <Group catalyzation at 0x7ff42b85ef50>]

#### Unifying rate parameters

For this `EnzymeModule`, the reactions representing glucose binding to the enzyme and ATP binding to the enzyme have the same forward rate and equilibrium constants. Instead of defining the parameter values for each individual reaction, the `unify_rate_parameters()` method can be used to create custom rate laws for the given reactions that all depend on the same rate parameters.

The `unify_rate_parameters()` method takes a list of reactions and an identifier to use for the unified parameter. The `enzyme_prefix` flag can be set to `True` to prefix the new parameter identifier with the identifier of the `EnzymeModule`, ensuring that any existing custom parameters are not overwritten.

```python
for ligand, pid in zip([glc__D_c, atp_c],["G", "A"]):
    # Get the group of reactions corresponding to the ligand
    category = "_".join((ligand.id, "binding"))
    group = HEX1.enzyme_module_reactions_categorized.get_by_id(category)

    # Unify the parameters
    HEX1.unify_rate_parameters(
        group.members, new_parameter_id=pid, enzyme_prefix=True)

    # Print the new reaction rates
    print("\n" + category + "\n" + "-" * len(category))
    for reaction in sorted(group.members, key=attrgetter("id")):
        print(reaction.id + ": " + str(reaction.rate))
```

    glc__D_c_binding
    ----------------
    HEX1_3: kf_HEX1_G*(glc__D_c(t)*hex1_c(t) - hex1_G_c(t)/Keq_HEX1_G)
    HEX1_7: kf_HEX1_G*(glc__D_c(t)*hex1_A_c(t) - hex1_AG_c(t)/Keq_HEX1_G)

    atp_c_binding
    -------------
    HEX1_4: kf_HEX1_A*(atp_c(t)*hex1_c(t) - hex1_A_c(t)/Keq_HEX1_A)
    HEX1_6: kf_HEX1_A*(atp_c(t)*hex1_G_c(t) - hex1_AG_c(t)/Keq_HEX1_A)

## Determining Enzyme Form Concentrations and Rate Constants

The next step is to solve for the steady state concentrations for the various forms of the enzyme symbolically using **SymPy**. Because the numerical values for the dissociation constants have been defined, these equations are solved in terms of the rate constants. The rate constants can be approximated using the total enzyme concentration as a constraint and substituted back into the equations to calculate the numerical values of the steady state concentrations.

```python
from sympy import Eq, Symbol, lambdify, simplify, solveset

from mass import strip_time
from mass.util.matrix import matrix_rank
```

### Solving steady state concentrations symbolically

To get the symbolic solutions for the individual enzyme forms, the ODEs are first collected in a `dict`. Keys are the enzyme forms, and values are their ODEs with the time dependency stripped via the `strip_time` function.

```python
ode_dict = {
    enzyme_form.id: Eq(strip_time(enzyme_form.ode), 0)
    for enzyme_form in HEX1.enzyme_module_forms}
# Matrix rank of enzyme stoichiometric matrix without substrates
rank = matrix_rank(HEX1.S[6:])
print("Rank Deficiency: {0}".format(len(ode_dict) - rank))
```

    Rank Deficiency: 1

Because the stoichiometric matrix (without ligands) has a rank deficiency of one, there is a dependent variable in the system unless another equation is added. Therefore, the completely free enzyme form is treated as the dependent variable, and all of the enzyme forms are solved in terms of the free enzyme form.

```python
enzyme_solutions = {}
for enzyme_form in HEX1.enzyme_module_forms:
    # Skip dependent variable
    if enzyme_form.id == "hex1_c":
        continue
    # Get the ODE for the enzyme form from the ODE dict
    equation = ode_dict[enzyme_form.id]
    # Solve the equation for the enzyme form, substituting
    # previously found enzyme form solutions into the equation
    solution = solveset(equation.subs(enzyme_solutions),
                        enzyme_form.id)
    # Store the solution
    enzyme_solutions[enzyme_form.id] = list(solution)[0]
    # Substitute the new solution into existing solutions
    enzyme_solutions.update({
        enzyme_form: sol.subs(enzyme_solutions)
        for enzyme_form, sol in enzyme_solutions.items()})

args = set()
for solution in enzyme_solutions.values():
    args.update(solution.atoms(Symbol))
```

#### Defining the Rate Equation

To make up for the rank deficiency, an additional equation is needed. Typically, the rate of the enzyme is the summation of the rates for the catalyzation reaction step(s) of the enzyme. The `make_enzyme_rate_equation()` method can be used to create the rate equation from a list of reactions. If `use_rates=True`, the rate expressions of the reactions are added together. If `update_enzyme=True`, the rate equation is set as a symbolic expression for the `enzyme_rate_equation` attribute.

```python
# Get the catalyzation reactions
catalyzation_group = HEX1.enzyme_module_reactions_categorized.get_by_id(
    "catalyzation")

HEX1.make_enzyme_rate_equation(catalyzation_group.members,
                               use_rates=True,
                               update_enzyme=True)

print(HEX1.enzyme_rate_equation)
```

    kf_HEX1_8*(Keq_HEX1_8*hex1_AG_c(t) - adp_c(t)*g6p_c(t)*hex1_c(t))/Keq_HEX1_8

With the rate equation defined, the `enzyme_rate_error()` method is used to get the equation as the difference between the flux value and the rate equation.

```python
enzyme_rate_equation = strip_time(HEX1.enzyme_rate_error(use_values=False))
print(enzyme_rate_equation)
```

    v_HEX1 - kf_HEX1_8*(Keq_HEX1_8*hex1_AG_c - adp_c*g6p_c*hex1_c)/Keq_HEX1_8

The solutions for the enzyme forms are substituted into the rate equation, and the equation is solved for the free enzyme form. The solutions are subsequently updated, resulting in symbolic equations that do not depend on any enzyme form.

```python
# Solve for last unknown concentration symbolically
solution = solveset(enzyme_rate_equation.subs(enzyme_solutions),
                    "hex1_c")

# Update solution dictionary with the new solution
enzyme_solutions["hex1_c"] = list(solution)[0]

# Update solutions with free variable solutions
enzyme_solutions = {
    enzyme_form: simplify(solution.subs(enzyme_solutions))
    for enzyme_form, solution in enzyme_solutions.items()}

args = set()
for solution in enzyme_solutions.values():
    args.update(solution.atoms(Symbol))
print(args)
```

    {g6p_c, kf_HEX1_8, kf_HEX1_A, v_HEX1, Keq_HEX1_A, atp_c, glc__D_c, _23dpg_c, kf_HEX1_G, Keq_HEX1_5, Keq_HEX1_8, adp_c, Keq_HEX1_2, Keq_HEX1_1, Keq_HEX1_G}

Numerical values for known quantities are substituted into the equations. For this `EnzymeModule` of Hexokinase, the following dissociation constants are used:

$$\begin{align}
K_{d,\ \text{GLC-D}} &= 0.038\ \text{mM} \\
K_{d,\ \text{ATP}} &= 2.06\ \text{mM} \\
K_{i,\ \text{23DPG}} &= 5.5\ \text{mM} \\
K_{i,\ \text{ADP}} &= 1\ \text{mM} \\
K_{i,\ \text{G6P}} &= 66.67\ \text{mM} \\
\end{align}$$

A value of $K_{\text{HEX1}}= 313.12$ is used for the catalyzation step. Note that the inverse of the dissociation constant is used for reactions that form complexes.

```python
numerical_values = {
    "Keq_HEX1_1": 1,
    "Keq_HEX1_2": 1 / 66.67,
    "Keq_HEX1_G": 1 / 0.038,
    "Keq_HEX1_A": 1 / 2.06,
    "Keq_HEX1_5": 1 / 5.5,
    "Keq_HEX1_8": 313.12}
# Update the model with the parameters
HEX1.update_parameters(numerical_values)
```

The ligand concentrations and the rate for the enzyme are extracted from the merged glycolysis and hemoglobin model.

```python
# Get steady state flux for EnzymeModule
HEX1.enzyme_rate = glyc_hb.reactions.get_by_id("HEX1").steady_state_flux
numerical_values[HEX1.enzyme_flux_symbol_str] = HEX1.enzyme_rate

# Get the ligand concentrations
for met in HEX1.enzyme_module_ligands:
    concentration = glyc_hb.metabolites.get_by_id(met.id).initial_condition
    # Set the ligand initial condition and add to numercal values dictionary
    met.initial_condition = concentration
    numerical_values[met.id] = concentration
```

The numerical values are substituted into the symbolic equations, resulting in the steady state concentrations that depend only on the rate constants.

```python
enzyme_solutions = {
    enzyme_form: simplify(sol.subs(numerical_values))
    for enzyme_form, sol in enzyme_solutions.items()}

args = set()
for solution in enzyme_solutions.values():
    args.update(solution.atoms(Symbol))
print(args)
```

    {kf_HEX1_A, kf_HEX1_G, kf_HEX1_8}

### Approximating Rate Constants

To determine the set of rate constants for the enzyme module, the absolute error between the total hexokinase concentration value (found in literature) and the computed hexokinase concentration is minimized. For this example, the `minimize()` function of the **SciPy** package is utilized to find a feasible set of rate constants.

```python
from scipy.optimize import minimize
```

The objective function for the minimization is first made symbolically. The `enzyme_total_symbol_str` property can be used to represent the total enzyme concentration, while the `enzyme_concentration_total_equation` property creates a symbolic expression for the sum of all enzyme forms.

```python
enzyme_total_error = abs(
    Symbol(HEX1.enzyme_total_symbol_str)
    - strip_time(HEX1.enzyme_concentration_total_equation))
print(enzyme_total_error)
```

    Abs(-HEX1_Total + hex1_AG_c + hex1_A_PI_c + hex1_A_c + hex1_G_CI_c + hex1_G_PI_c + hex1_G_c + hex1_c)

The `enzyme_concentration_total` attribute stores the total amount of enzyme in the model and substituted into the expression. The total HEX1 concentration is $24 * 10^{-6} \text{mM}$.

```python
HEX1.enzyme_concentration_total = 24e-6
enzyme_total_error = enzyme_total_error.subs({
    HEX1.enzyme_total_symbol_str: HEX1.enzyme_concentration_total})
print(enzyme_total_error)
```

    Abs(hex1_AG_c + hex1_A_PI_c + hex1_A_c + hex1_G_CI_c + hex1_G_PI_c + hex1_G_c + hex1_c - 2.4e-5)

Finally, the symbolic equations for the enzyme forms are substituted into the enzyme total error equation, resulting in an expression that represents the objective function with the only unknown variables being rate constants. The `lambdify()` function of the **SymPy** package converts the symbolic objective into a lambda function that can be used with the `minimize()` function of **SciPy**.

```python
enzyme_total_error = simplify(enzyme_total_error.subs(enzyme_solutions))

# Sort the arguments to ensure input format remains consistent
args = sorted(list(map(str, args)))
# Use lambdify to make objective function as a lambda function
obj_fun = lambda x: lambdify(args, enzyme_total_error)(*x)
```

The `minimize()` function is now used to approximate the rate constants. The optimization problems for enzyme rate constants are typically nonlinear, and require nonlinear optimization routines to find feasible solutions.

```python
# Minimize the objective function, initial guess based on publication values
initial_guess = [1e8, 9376585, 52001]
variable_bounds = ((0, 1e9), (0, 1e9), (0, 1e9))
solution = minimize(obj_fun, x0=initial_guess,
                    method="trust-constr",
                    bounds=variable_bounds)
# Map solution array to variables
rate_constants = dict(zip(args, solution.x))
print(rate_constants)
```

    {'kf_HEX1_8': 100000000.0025878, 'kf_HEX1_A': 9376585.030755484, 'kf_HEX1_G': 52006.59981223971}

Because the rate constants associated with the inhibition of the enzyme forms are not necessary for computing the concentrations, a rapid binding assumption is made for the inhibition reactions. Therefore, a large number is set for the rate constants. The parameters are set using the `update_parameters()` method.

```python
rate_constants["kf_HEX1_1"] = 1e6
rate_constants["kf_HEX1_2"] = 1e6
rate_constants["kf_HEX1_5"] = 1e6
HEX1.update_parameters(rate_constants)
```

### Calculating numerical values for concentrations

Once the rate constants have been estimated, they are substituted back into the symbolic concentration equations in order to obtain their numerical values.

```python
for enzyme_form, solution in enzyme_solutions.items():
    # Get the enzyme form object, determine the steady state concentration
    enzyme_form = HEX1.enzyme_module_forms.get_by_id(enzyme_form)
    enzyme_form.initial_condition = float(solution.subs(rate_constants))
    print("{0}: {1:e}".format(enzyme_form.id,
                              enzyme_form.initial_condition))
```

    hex1_A_c: 9.401421e-06
    hex1_G_c: 5.718872e-08
    hex1_AG_c: 1.174630e-08
    hex1_G_CI_c: 3.223364e-08
    hex1_A_PI_c: 3.519706e-06
    hex1_G_PI_c: 8.847367e-09
    hex1_c: 1.213692e-05

#### Error values

As a quality assurance check, the `enzyme_concentration_total_error()` method can be used to get the error between the `enzyme_concentration_total` attribute and the sum of the enzyme form concentrations. A positive value indicates the `enzyme_concentration_total` attribute is greater than the sum of the individual enzyme form concentrations that were computed.

```python
print("Total Enzyme Concentration Error: {0}".format(
    HEX1.enzyme_concentration_total_error(use_values=True)))
```

    Total Enzyme Concentration Error: -1.1680622689093244e-06

Similarly, the error between the `enzyme_rate` attribute and the computed value from the `enzyme_rate_equation` can be also checked using the `enzyme_rate_error()` method, in which a positive value indicates that the `enzyme_rate` attribute is greater than the value computed when using the rate equation.

```python
print("Enzyme Rate Error: {0}".format(
    HEX1.enzyme_rate_error(use_values=True)))
```

    Enzyme Rate Error: 4.440892098500626e-16

## Adding EnzymeModules to Models

With the `EnzymeModule` built, it can be integrated into a larger network and simulated. To add an `EnzymeModule` to an existing `MassModel`, the `merge()` method is used. After merging, the `remove_reactions()` method is used to remove the reaction replaced with the enzyme module. The `EnzymeModule` should always be merged into the `MassModel` as demonstrated below:

```python
glyc_hb_HEX1 = glyc_hb.merge(HEX1, inplace=False)
glyc_hb_HEX1.remove_reactions([
    glyc_hb_HEX1.reactions.get_by_id("HEX1")])
```

All objects, numerical values, and certain attributes of the `EnzymeModule` are transferred into the `MassModel` upon merging. This includes all enzyme forms, reactions steps, initial conditions, rate parameters, and category groups.

```python
glyc_hb_HEX1
```

        Name	Glycolysis_Hemoglobin_HEX1

        Memory address	0x07ff42b8e6d90

        Stoichiometric Matrix
        35x37

        Matrix Rank
        32

        Number of metabolites
        35

        Initial conditions defined
        35/35

        Number of reactions
        37

        Number of genes
        0

        Number of enzyme modules
        1

        Number of groups
        12

        Objective expression
        0

        Compartments
        Cytosol

### The EnzymeModuleDict object

During the merge process, an `EnzymeModuleDict` is created from the `EnzymeModule` and added to the `MassModel.enzyme_modules` attribute.

```python
print(glyc_hb_HEX1.enzyme_modules)
HEX1_dict = glyc_hb_HEX1.enzyme_modules.get_by_id("HEX1")
HEX1_dict
```

    [<EnzymeModuleDict HEX1 at 0x7ff42bab8950>]

        Name	HEX1

        Memory address	0x07ff42bab8950

        Stoichiometric Matrix
        13x8

        Matrix Rank
        7

        Subsystem
        Glycolysis

        Number of Ligands
        6

        Number of EnzymeForms
        7

        Number of EnzymeModuleReactions
        8

        Enzyme Concentration Total
        2.4e-05

        Enzyme Net Flux
        1.12

The `EnzymeModuleDict` inherits from an `OrderedDict`, thereby inheriting ordered dictionary methods such as `keys()`:

```python
print("\n".join(HEX1_dict.keys()))
```

    id
    name
    subsystem
    enzyme_module_ligands
    enzyme_module_forms
    enzyme_module_reactions
    enzyme_module_ligands_categorized
    enzyme_module_forms_categorized
    enzyme_module_reactions_categorized
    enzyme_concentration_total
    enzyme_rate
    enzyme_concentration_total_equation
    enzyme_rate_equation
    S
    model

The `EnzymeModuleDict` stores several of the enzyme-specific attributes so that they are still accessible after integrating the enzyme module into a larger network. The keys of the `EnzymeModuleDict`  also can be treated as attribute accessors:

```python
print("Enzyme Rate:\n{0} = {1}".format(
    HEX1_dict["enzyme_rate"],       # Returned using dict key
    HEX1_dict.enzyme_rate_equation  # Returned using attribute accessor
))
```

    Enzyme Rate:
    1.12 = kf_HEX1_8*(Keq_HEX1_8*hex1_AG_c(t) - adp_c(t)*g6p_c(t)*hex1_c(t))/Keq_HEX1_8

### Steady State Validation
The last step is to ensure that a steady state is reached with the completed enzyme module within a larger network context.

```python
import matplotlib.pyplot as plt

from mass import Simulation
from mass.visualization import plot_time_profile
```

Here, the model is simulated, and the enzyme's ability to reach steady state is graphically verified:

```python
# Setup simulation object
sim = Simulation(glyc_hb_HEX1, verbose=True)
# Simulate from 0 to 1000 with 10001 points in the output
conc_sol, flux_sol = sim.simulate(
    glyc_hb_HEX1, time=(0, 1e3, 1e4 + 1))

fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(6, 4))
plot_time_profile(
    conc_sol, observable=HEX1_dict.enzyme_module_forms, ax=ax,
    legend="right outside", plot_function="loglog",
    xlabel="Time [hr]", ylabel="Concentration [mM]",
    title="TIme profile of Concentrations for Enzyme Forms");
```

The plot shows that the enzyme can reach a steady state when integrated into a larger network, meaning the enzyme module that represents hexokinase in this system is complete!

## Additional Examples
For additional examples of analyzing and visualizing systems with enzyme modules, see the following:

* [Visualizing Catalytic Potentials of Glycolytic Regulatory Kinases](../gallery/visualization/catalytic_potential_visualizations.ipynb)

$^1$ Procedure outlined in Du et al., 2016

$^2$ Hexokinase based on Yurkovich et al., 2018, Du et al., 2016, and Mulquiney and Kuchel, 1999.

$^3$ Glycolysis model based on Yurkovich et al., 2018 and Chapter 10 of Systems Biology: Simulation of Dynamic Network States


```python
from google.colab import drive
drive.mount('/content/drive')
```

    Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3aietf%3awg%3aoauth%3a2.0%3aoob&response_type=code&scope=email%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdocs.test%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive.photos.readonly%20https%3a%2f%2fwww.googleapis.com%2fauth%2fpeopleapi.readonly

    Enter your authorization code:
    ··········
    Mounted at /content/drive

# Neuromatch Academy: Week 3, Day 4, Tutorial 1
# Deep Learning: Decoding Neural Responses

**Content creators**: Jorge A. Menendez, Carsen Stringer

**Content reviewers**: Roozbeh Farhoodi,  Madineh Sarvestani, Kshitij Dwivedi, Spiros Chavlis, Ella Batty, Michael Waskom

---
# Tutorial Objectives
In this tutorial, we'll use deep learning to decode stimulus information from the responses of sensory neurons. Specifically, we'll look at the activity of ~20,000 neurons in mouse primary visual cortex responding to oriented gratings recorded in [this study](https://www.biorxiv.org/content/10.1101/679324v2.abstract). Our task will be to decode the orientation of the presented stimulus from the responses of the whole population of neurons. We could do this in a number of ways, but here we'll use deep learning. Deep learning is particularly well-suited to this problem for a number of reasons:
* The data are very high-dimensional: the neural response to a stimulus is a ~20,000 dimensional vector. Many machine learning techniques fail in such high dimensions, but deep learning actually thrives in this regime, as long as you have enough data (which we do here!).
* As you'll be able to see below, different neurons can respond quite differently to stimuli. This complex pattern of responses will, therefore, require non-linear methods to be decoded, which we can easily do with non-linear activation functions in deep networks.
* Deep learning architectures are highly flexible, meaning we can easily adapt the architecture of our decoding model to optimize decoding. Here, we'll focus on a single architecture, but you'll see that it can easily be modified with few changes to the code.

More concretely, our goal will be learn how to:
* Build a deep feed-forward network using PyTorch
* Evaluate the network's outputs using PyTorch built-in loss functions
* Compute gradients of the loss with respect to each parameter of the network using automatic differentiation
* Implement gradient descent to optimize the network's parameters

This tutorial will take up the first full session (equivalent to two tutorials on other days).

```python
#@title Video 1: Decoding from neural data using feed-forward networks in pytorch
from IPython.display import YouTubeVideo
video = YouTubeVideo(id="SlrbMvvBOzM", width=854, height=480, fs=1)
print("Video available at https://youtu.be/" + video.id)
video
```

    Video available at https://youtu.be/SlrbMvvBOzM

---
# Setup

```python
import os
import numpy as np

import torch
from torch import nn
from torch import optim

import matplotlib as mpl
from matplotlib import pyplot as plt
```

```python
#@title Data retrieval and loading
import hashlib
import requests

fname = "W3D4_stringer_oribinned1.npz"
url = "https://osf.io/683xc/download"
expected_md5 = "436599dfd8ebe6019f066c38aed20580"

if not os.path.isfile(fname):
  try:
    r = requests.get(url)
  except requests.ConnectionError:
    print("!!! Failed to download data !!!")
  else:
    if r.status_code != requests.codes.ok:
      print("!!! Failed to download data !!!")
    elif hashlib.md5(r.content).hexdigest() != expected_md5:
      print("!!! Data download appears corrupted !!!")
    else:
      with open(fname, "wb") as fid:
        fid.write(r.content)
```

```python
#@title Figure Settings
%config InlineBackend.figure_format = 'retina'
plt.style.use("https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/nma.mplstyle")
```

```python
#@title Helper Functions

def load_data(data_name=fname, bin_width=1):
  """Load mouse V1 data from Stringer et al. (2019)

  Data from study reported in this preprint:
  https://www.biorxiv.org/content/10.1101/679324v2.abstract

  These data comprise time-averaged responses of ~20,000 neurons
  to ~4,000 stimulus gratings of different orientations, recorded
  through Calcium imaginge. The responses have been normalized by
  spontanous levels of activity and then z-scored over stimuli, so
  expect negative numbers. They have also been binned and averaged
  to each degree of orientation.

  This function returns the relevant data (neural responses and
  stimulus orientations) in a torch.Tensor of data type torch.float32
  in order to match the default data type for nn.Parameters in
  Google Colab.

  This function will actually average responses to stimuli with orientations
  falling within bins specified by the bin_width argument. This helps
  produce individual neural "responses" with smoother and more
  interpretable tuning curves.

  Args:
    bin_width (float): size of stimulus bins over which to average neural
      responses

  Returns:
    resp (torch.Tensor): n_stimuli x n_neurons matrix of neural responses,
        each row contains the responses of each neuron to a given stimulus.
        As mentioned above, neural "response" is actually an average over
        responses to stimuli with similar angles falling within specified bins.
    stimuli: (torch.Tensor): n_stimuli x 1 column vector with orientation
        of each stimulus, in degrees. This is actually the mean orientation
        of all stimuli in each bin.

  """
  with np.load(data_name) as dobj:
    data = dict(**dobj)
  resp = data['resp']
  stimuli = data['stimuli']

  if bin_width > 1:
    # Bin neural responses and stimuli
    bins = np.digitize(stimuli, np.arange(0, 360 + bin_width, bin_width))
    stimuli_binned = np.array([stimuli[bins == i].mean() for i in np.unique(bins)])
    resp_binned = np.array([resp[bins == i, :].mean(0) for i in np.unique(bins)])
  else:
    resp_binned = resp
    stimuli_binned = stimuli

  # Return as torch.Tensor
  resp_tensor = torch.tensor(resp_binned, dtype=torch.float32)
  stimuli_tensor = torch.tensor(stimuli_binned, dtype=torch.float32).unsqueeze(1)  # add singleton dimension to make a column vector

  return resp_tensor, stimuli_tensor

def plot_data_matrix(X, ax):
  """Visualize data matrix of neural responses using a heatmap

  Args:
    X (torch.Tensor or np.ndarray): matrix of neural responses to visualize
        with a heatmap
    ax (matplotlib axes): where to plot

  """

  cax = ax.imshow(X, cmap=mpl.cm.pink, vmin=np.percentile(X, 1), vmax=np.percentile(X, 99))
  cbar = plt.colorbar(cax, ax=ax, label='normalized neural response')

  ax.set_aspect('auto')
  ax.set_xticks([])
  ax.set_yticks([])

def identityLine():
  """
  Plot the identity line y=x
  """
  ax = plt.gca()
  lims = np.array([ax.get_xlim(), ax.get_ylim()])
  minval = lims[:, 0].min()
  maxval = lims[:, 1].max()
  equal_lims = [minval, maxval]
  ax.set_xlim(equal_lims)
  ax.set_ylim(equal_lims)
  line = ax.plot([minval, maxval], [minval, maxval], color="0.7")
  line[0].set_zorder(-1)

def get_data(n_stim, train_data, train_labels):
  """ Return n_stim randomly drawn stimuli/resp pairs

  Args:
    n_stim (scalar): number of stimuli to draw
    resp (torch.Tensor):
    train_data (torch.Tensor): n_train x n_neurons tensor with neural
      responses to train on
    train_labels (torch.Tensor): n_train x 1 tensor with orientations of the
      stimuli corresponding to each row of train_data, in radians

  Returns:
    (torch.Tensor, torch.Tensor): n_stim x n_neurons tensor of neural responses and n_stim x 1 of orientations respectively
  """
  n_stimuli = train_labels.shape[0]
  istim = np.random.choice(n_stimuli, n_stim)
  r = train_data[istim]  # neural responses to this stimulus
  ori = train_labels[istim]  # true stimulus orientation

  return r, ori

def stimulus_class(ori, n_classes):
  """Get stimulus class from stimulus orientation

  Args:
    ori (torch.Tensor): orientations of stimuli to return classes for
    n_classes (int): total number of classes

  Returns:
    torch.Tensor: 1D tensor with the classes for each stimulus

  """
  bins = np.linspace(0, 360, n_classes + 1)
  return torch.tensor(np.digitize(ori.squeeze(), bins)) - 1  # minus 1 to accomodate Python indexing

def plot_decoded_results(train_loss, test_labels, predicted_test_labels):
  """ Plot decoding results in the form of network training loss and test predictions

  Args:
    train_loss (list): training error over iterations
    test_labels (torch.Tensor): n_test x 1 tensor with orientations of the
      stimuli corresponding to each row of train_data, in radians
    predicted_test_labels (torch.Tensor): n_test x 1 tensor with predicted orientations of the
      stimuli from decoding neural network

  """

  # Plot results
  fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 6))

  # Plot the training loss over iterations of GD
  ax1.plot(train_loss)

  # Plot true stimulus orientation vs. predicted class
  ax2.plot(stimuli_test.squeeze(), predicted_test_labels, '.')

  ax1.set_xlim([0, None])
  ax1.set_ylim([0, None])
  ax1.set_xlabel('iterations of gradient descent')
  ax1.set_ylabel('negative log likelihood')
  ax2.set_xlabel('true stimulus orientation ($^o$)')
  ax2.set_ylabel('decoded orientation bin')
  ax2.set_xticks(np.linspace(0, 360, n_classes + 1))
  ax2.set_yticks(np.arange(n_classes))
  class_bins = [f'{i * 360 / n_classes: .0f}$^o$ - {(i + 1) * 360 / n_classes: .0f}$^o$' for i in range(n_classes)]
  ax2.set_yticklabels(class_bins);

  # Draw bin edges as vertical lines
  ax2.set_ylim(ax2.get_ylim())  # fix y-axis limits
  for i in range(n_classes):
    lower = i * 360 / n_classes
    upper = (i + 1) * 360 / n_classes
    ax2.plot([lower, lower], ax2.get_ylim(), '-', color="0.7", linewidth=1, zorder=-1)
    ax2.plot([upper, upper], ax2.get_ylim(), '-', color="0.7", linewidth=1, zorder=-1)

  plt.tight_layout()
```

---
# Section 1: Load and visualize data

In the next cell, we have provided code to load the data and plot the matrix of neural responses.

Next to it, we plot the tuning curves of three randomly selected neurons.

```python
#@title

#@markdown Execute this cell to load and visualize data

# Load data
resp_all, stimuli_all = load_data()  # argument to this function specifies bin width
n_stimuli, n_neurons = resp_all.shape

print(f'{n_neurons} neurons in response to {n_stimuli} stimuli')

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(2 * 6, 5))

# Visualize data matrix
plot_data_matrix(resp_all[:100, :].T, ax1)  # plot responses of first 100 neurons
ax1.set_xlabel('stimulus')
ax1.set_ylabel('neuron')

# Plot tuning curves of three random neurons
ineurons = np.random.choice(n_neurons, 3, replace=False)  # pick three random neurons
ax2.plot(stimuli_all, resp_all[:, ineurons])
ax2.set_xlabel('stimulus orientation ($^o$)')
ax2.set_ylabel('neural response')
ax2.set_xticks(np.linspace(0, 360, 5))

plt.tight_layout()
```

We will split our data into a training set and test set. In particular, we will have a training set of orientations (`stimuli_train`) and the corresponding responses (`resp_train`). Our testing set will have held-out orientations (`stimuli_test`) and the corresponding responses (`resp_test`).

```python
#@title
#@markdown Execute this cell to split into training and test sets

# Set random seeds for reproducibility
np.random.seed(4)
torch.manual_seed(4)

# Split data into training set and testing set
n_train = int(0.6 * n_stimuli)  # use 60% of all data for training set
ishuffle = torch.randperm(n_stimuli)
itrain = ishuffle[:n_train]  # indices of data samples to include in training set
itest = ishuffle[n_train:]  # indices of data samples to include in testing set
stimuli_test = stimuli_all[itest]
resp_test = resp_all[itest]
stimuli_train = stimuli_all[itrain]
resp_train = resp_all[itrain]
```

---
# Section 2: Deep feed-forward networks in *pytorch*

We'll now build a simple deep neural network that takes as input a vector of neural responses and outputs a single number representing the decoded stimulus orientation.

To keep things simple, we'll build a deep network with **one** hidden layer. See the appendix for a deeper discussion of what this choice entails, and when one might want to use deeper/shallower and wider/narrower architectures.

Let $\mathbf{r}^{(n)} = \begin{bmatrix} r_1^{(n)} & r_2^{(n)} & \ldots & r_N^{(n)} \end{bmatrix}^T$ denote the vector of neural responses (of neurons $1, \ldots, N$) to the $n$th stimulus. The network we will use is described by the following set of equations:
\begin{align}
    \mathbf{h}^{(n)} &= \mathbf{W}^{in} \mathbf{r}^{(n)} + \mathbf{b}^{in}, && [\mathbf{W}^{in}: M \times N], \\
    y^{(n)} &= \mathbf{W}^{out} \mathbf{h}^{(n)} + \mathbf{b}^{out},  && [\mathbf{W}^{out}: 1 \times M],
\end{align}
where $y^{(n)}$ denotes the scalar output of the network: the decoded orientation of the $n$th stimulus.

The $M$-dimensional vector $\mathbf{h}^{(n)}$ denotes the activations of the **hidden layer** of the network.

The blue components of this diagram denote the **parameters** of the network, which we will later optimize with gradient descent. These include all the weights and biases $\mathbf{W}^{in}, \mathbf{b}^{in}, \mathbf{W}^{out}, \mathbf{b}^{out}$.

### Section 2.1: Introduction to PyTorch

Here, we'll use the **PyTorch** package to build, run, and train deep networks of this form in Python. There are two core components to the PyTorch package:

1. The first is the `torch.Tensor` data type used in PyTorch. `torch.Tensor`'s are effectively just like a `numpy` arrays, except that they have some important attributes and methods needed for automatic differentiation (to be discussed below). They also come along with infrastructure for easily storing and computing with them on GPU's, a capability we won't touch on here but which can be really useful in practice.

2. The second core ingredient is the PyTorch `nn.Module` class. This is the class we'll use for constructing deep networks, so that we can then easily train them using built-in PyTorch functions. Keep in my mind that `nn.Module` classes can actually be used to build, run, and train any model -- not just deep networks!

  The next cell contains code for building the deep network we defined above using the `nn.Module` class. It contains three key ingredients:

  * `__init__()` method to initialize its parameters, like in any other Python class. In this case, it takes two arguments:
    * `n_inputs`: the number of input units. This should always be set to the number of neurons whose activities are being decoded (i.e. the dimensionality of the input to the network).
    * `n_hidden`: the number of hidden units. This is a parameter that we are free to vary in deciding how to build our network. See the appendix for a discussion of how this architectural choice affects the computations the network can perform.

  * `nn.Linear` modules, which are built-in PyTorch classes containing all the weights and biases for a given network layer (documentation [here](https://pytorch.org/docs/master/generated/torch.nn.Linear.html)). This class takes two arguments to initialize:
    * \# of inputs to that layer
    * \# of outputs from that layer

    For the input layer, for example, we have:
    * \# of inputs = \# of neurons whose responses are to be decoded ($N$, specified by `n_inputs`)
    * \# of outputs = \# of hidden layer units ($M$, specified by `n_hidden`)

    PyTorch will initialize all weights and biases randomly.

  * `forward()` method, which takes as argument an input to the network and returns the network output. In our case, this comprises computing the output $y$ from a given input $\mathbf{r}$ using the above two equations. See the next cell for code implementing this computation using the built-in PyTorch `nn.Linear` classes.

```python
class DeepNet(nn.Module):
  """Deep Network with one hidden layer

  Args:
    n_inputs (int): number of input units
    n_hidden (int): number of units in hidden layer

  Attributes:
    in_layer (nn.Linear): weights and biases of input layer
    out_layer (nn.Linear): weights and biases of output layer

  """

  def __init__(self, n_inputs, n_hidden):
    super().__init__()  # needed to invoke the properties of the parent class nn.Module
    self.in_layer = nn.Linear(n_inputs, n_hidden) # neural activity --> hidden units
    self.out_layer = nn.Linear(n_hidden, 1) # hidden units --> output

  def forward(self, r):
    """Decode stimulus orientation from neural responses

    Args:
      r (torch.Tensor): vector of neural responses to decode, must be of
        length n_inputs. Can also be a tensor of shape n_stimuli x n_inputs,
        containing n_stimuli vectors of neural responses

    Returns:
      torch.Tensor: network outputs for each input provided in r. If
        r is a vector, then y is a 1D tensor of length 1. If r is a 2D
        tensor then y is a 2D tensor of shape n_stimuli x 1.

    """
    h = self.in_layer(r)  # hidden representation
    y = self.out_layer(h)
    return y
```

The next cell contains code for initializing and running this network. We use it to decode stimulus orientation from a vector of neural responses to the very first stimulus. Note that when the initialized network class is called as a function on an input (e.g. `net(r)`), its `.forward()` method is called. This is a special property of the `nn.Module` class.

Note that the decoded orientations at this point will be nonsense, since the network has been initialized with random weights. Below, we'll learn how to optimize these weights for good stimulus decoding.

```python
# Set random seeds for reproducibility
np.random.seed(1)
torch.manual_seed(1)

# Initialize a deep network with M=200 hidden units
net = DeepNet(n_neurons, 200)

# Get neural responses (r) to and orientation (ori) to one stimulus in dataset
r, ori = get_data(1, resp_train, stimuli_train)  # using helper function get_data

# Decode orientation from these neural responses using initialized network
out = net(r)  # compute output from network, equivalent to net.forward(r)

print('decoded orientation: %.2f degrees' % out)
print('true orientation: %.2f degrees' % ori)
```

    decoded orientation: 0.08 degrees
    true orientation: 139.00 degrees

---
### Section 2.2: Activation functions

```python
#@title Video 2: Nonlinear activation functions
from IPython.display import YouTubeVideo
video = YouTubeVideo(id="JAdukDCQALA", width=854, height=480, fs=1)
print("Video available at https://youtu.be/" + video.id)
video
```

    Video available at https://youtu.be/JAdukDCQALA

Note that the deep network we constructed above comprises solely **linear** operations on each layer: each layer is just a weighted sum of the elements in the previous layer. It turns out that linear hidden layers like this aren't particularly useful, since a sequence of linear transformations is actually essentially the same as a single linear transformation. We can see this from the above equations by plugging in the first one into the second one to obtain
\begin{equation}
    y^{(n)} = \mathbf{W}^{out} \left( \mathbf{W}^{in} \mathbf{r}^{(n)} + \mathbf{b}^{in} \right) + \mathbf{b}^{out} = \mathbf{W}^{out}\mathbf{W}^{in} \mathbf{r}^{(n)} + \left( \mathbf{W}^{out}\mathbf{b}^{in} + \mathbf{b}^{out} \right)
\end{equation}
In other words, the output is still just a weighted sum of elements in the input -- the hidden layer has done nothing to change this.

To extend the set of computable input/output transformations to more than just weighted sums, we'll incorporate a **non-linear activation function** in the hidden units. This is done by simply modifying the equation for the hidden layer activations to be
\begin{equation}
    \mathbf{h}^{(n)} = \phi(\mathbf{W}^{in} \mathbf{r}^{(n)} + \mathbf{b}^{in})
\end{equation}
where $\phi$ is referred to as the activation function. Using a non-linear activation function will ensure that the hidden layer performs a non-linear transformation of the input, which will make our network much more powerful (or *expressive*, cf. appendix). In practice, deep networks *always* use non-linear activation functions.

#### Exercise 1: Nonlinear Activations

Create a new class `DeepNetReLU` by modifying our above deep network model to use a non-linear activation function. We'll use the linear rectification function:
\begin{equation}
  \phi(x) =
  \begin{cases}
    x & \text{if } x > 0 \\
    0 & \text{else}
  \end{cases}
\end{equation}
which can be implemented in PyTorch using `torch.relu()`. Hidden layers with this activation function are typically referred to as "**Re**ctified **L**inear **U**nits", or **ReLU**'s.

Initialize this network with 20 hidden units and run on an example stimulus.

**Hint**: you only need to modify the `forward()` method of the above `DeepNet()` class.

```python
class DeepNetReLU(nn.Module):

  def __init__(self, n_inputs, n_hidden):
    super().__init__()  # needed to invoke the properties of the parent class nn.Module
    self.in_layer = nn.Linear(n_inputs, n_hidden) # neural activity --> hidden units
    self.out_layer = nn.Linear(n_hidden, 1) # hidden units --> output

  def forward(self, r):

    ############################################################################
    ## TO DO for students: write code for computing network output using a
    ## rectified linear activation function for the hidden units
    # Fill out function and remove
    #raise NotImplementedError("Student exercise: complete DeepNetReLU forward")
    ############################################################################

    h = torch.relu(self.in_layer(r))
    y = self.out_layer(h)

    return y

# Set random seeds for reproducibility
np.random.seed(1)
torch.manual_seed(1)

# Get neural responses (r) to and orientation (ori) to one stimulus in dataset
r, ori = get_data(1, resp_train, stimuli_train)

# Uncomment to test your class

# Initialize deep network with M=20 hidden units and uncomment lines below
net = DeepNetReLU(n_neurons,20)

# Decode orientation from these neural responses using initialized network
#net(r) is equivalent to net.forward(r)
out = net(r)

print('decoded orientation: %.2f degrees' % out)
print('true orientation: %.2f degrees' % ori)
```

    decoded orientation: 0.13 degrees
    true orientation: 139.00 degrees

[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W3D4_DeepLearning1/solutions/W3D4_Tutorial1_Solution_5bdc2033.py)

You should see that the decoded orientation is 0.13 $^{\circ}$ while the true orientation is 139.00 $^{\circ}$.

---
# Section 3: Loss functions and gradient descent

```python
#@title Video 3: Loss functions & gradient descent
from IPython.display import YouTubeVideo
video = YouTubeVideo(id="aEtKpzEuviw", width=854, height=480, fs=1)
print("Video available at https://youtu.be/" + video.id)
video
```

    Video available at https://youtu.be/aEtKpzEuviw

### Section 3.1: Loss functions

Because the weights of the network are currently randomly chosen, the outputs of the network are nonsense: the decoded stimulus orientation is nowhere close to the true stimulus orientation. We'll shortly write some code to change these weights so that the network does a better job of decoding.

But to do so, we first need to define what we mean by "better". One simple way of defining this is to use the squared error
\begin{equation}
    L = (y - \tilde{y})^2
\end{equation}
where $y$ is the network output and $\tilde{y}$ is the true stimulus orientation. When the decoded stimulus orientation is far from the true stimulus orientation, $L$ will be large. We thus refer to $L$ as the **loss function**, as it quantifies how *bad* the network is at decoding stimulus orientation.

PyTorch actually carries with it a number of built-in loss functions. The one corresponding to the squared error is called `nn.MSELoss()`. This will take as arguments a **batch** of network outputs $y_1, y_2, \ldots, y_P$ and corresponding target outputs $\tilde{y}_1, \tilde{y}_2, \ldots, \tilde{y}_P$, and compute the **mean squared error (MSE)**
\begin{equation}
    L = \frac{1}{P}\sum_{n=1}^P \left(y^{(n)} - \tilde{y}^{(n)}\right)^2
\end{equation}

#### Exercise 2: Computing MSE

Evaluate the mean squared error for a deep network with $M=20$ rectified linear units, on the decoded orientations from neural responses to 20 random stimuli.

```python
# Set random seeds for reproducibility
np.random.seed(1)
torch.manual_seed(1)

# Initialize a deep network with M=20 hidden units
net = DeepNetReLU(n_neurons, 20)

# Get neural responses to first 20 stimuli in the data set
r, ori = get_data(20, resp_train, stimuli_train)

# Decode orientation from these neural responses
out = net(r)

###################################################
## TO DO for students: evaluate mean squared error
###################################################

# Initialize PyTorch mean squared error loss function (Hint: look at nn.MSELoss)
loss_fn = nn.MSELoss()

# Evaluate mean squared error
loss = loss_fn(out, ori)

# Uncomment once above is filled in
print('mean squared error: %.2f' % loss)
```

    mean squared error: 42943.75

[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W3D4_DeepLearning1/solutions/W3D4_Tutorial1_Solution_0e539ef5.py)

You should see a mean squared error of 42943.75.

---
### Section 3.2: Optimization with gradient descent

Our goal is now to modify the weights to make the mean squared error loss $L$ as small as possible over the whole data set. To do this, we'll use the **gradient descent (GD)** algorithm, which consists of iterating three steps:
1. **Evaluate the loss** on the training data,
```
out = net(train_data)
loss = loss_fn(out, train_labels)
```
where `train_data` are the network inputs in the training data (in our case, neural responses), and `train_labels` are the target outputs for each input (in our case, true stimulus orientations).
2. **Compute the gradient of the loss** with respect to each of the network weights. In PyTorch, we can do this with one line of code:
```
loss.backward()
```
This command tells PyTorch to compute the gradients of the quantity stored in the variable `loss` with respect to each network parameter using [automatic differentiation](https://en.wikipedia.org/wiki/Automatic_differentiation). These gradients are then stored behind the scenes (see appendix for more details).
3. **Update the network weights** by descending the gradient. In Pytorch, we can do this using built-in optimizers. We'll use the `optim.SGD` optimizer (documentation [here](https://pytorch.org/docs/stable/optim.html#torch.optim.SGD)) which updates parameters along the negative gradient, scaled by a learning rate (see appendix for details). To initialize this optimizer, we have to tell it
  * which parameters to update, and
  * what learning rate to use

  For example, to optimize *all* the parameters of a network `net` using a learning rate of .001, the optimizer would be initialized as follows
  ```
  optimizer = optim.SGD(net.parameters(), lr=.001)
  ```
  where `.parameters()` is a method of the `nn.Module` class that returns a [Python generator object](https://wiki.python.org/moin/Generators) over all the parameters of that `nn.Module` class (in our case, $\mathbf{W}^{in}, \mathbf{b}^{in}, \mathbf{W}^{out}, \mathbf{b}^{out}$).

  After computing all the parameter gradients in step 2, we can then update each of these parameters using the `.step()` method of this optimizer,
  ```
  optimizer.step()
  ```
  This single line of code will extract all the gradients computed with `.backward()` and execute the SGD updates for each parameter given to the optimizer. Note that this is true no matter how big/small the network is, allowing us to use the same two lines of code to perform the gradient descent updates for any deep network model built using PyTorch.

Finally, an important detail to remember is that the gradients of each parameter need to be cleared before calling `.backward()`, or else PyTorch will try to accumulate gradients across iterations. This can again be done using built-in optimizers via the method `zero_grad()`, as follows:
```
optimizer.zero_grad()
```

Putting all this together, each iteration of the GD algorith will contain a block of code that looks something like this:
```
Get outputs from network
Evaluate loss

# Compute gradients
optimizer.zero_grad()  # clear gradients
loss.backward()

# Update weights
optimizer.step()
```

In the next exercise, we'll give you a code skeleton for implementing the GD algorithm. Your job will be to fill in the blanks.

For the mathematical details of the GD algorithm, see the appendix. Note, in particular, that here we using the gradient descent algorithm, rather than the more commonly used *stochastic* gradient descent algorithm. See the appendix for a more detailed discussion of how these differ and when one might need to use the stochastic variant.

#### Exercise 3: Gradient descent in PyTorch

Complete the function `train()` that uses the gradient descent algorithm to optimize the weights of a given network. This function takes as input arguments
* `net`: the PyTorch network whose weights to optimize
* `loss_fn`: the PyTorch loss function to use to evaluate the loss
* `train_data`: the training data to evaluate the loss on (i.e. neural responses to decode)
* `train_labels`: the target outputs for each data point in `train_data` (i.e. true stimulus orientations)

We will then train a neural network on our data and plot the loss (mean squared error) over time. When we run this function, behind the scenes PyTorch is actually changing the parameters inside this network to make the network better at decoding, so its weights will now be different than they were at initialization.

**Hint:** all the code you need for doing this is provided in the above description of the GD algorithm.

```python
def train(net, loss_fn, train_data, train_labels, n_iter=50, learning_rate=1e-4):
  """Run gradient descent to opimize parameters of a given network

  Args:
    net (nn.Module): PyTorch network whose parameters to optimize
    loss_fn: built-in PyTorch loss function to minimize
    train_data (torch.Tensor): n_train x n_neurons tensor with neural
      responses to train on
    train_labels (torch.Tensor): n_train x 1 tensor with orientations of the
      stimuli corresponding to each row of train_data, in radians
    n_iter (int): number of iterations of gradient descent to run
    learning_rate (float): learning rate to use for gradient descent

  Returns:
    (list): training loss over iterations

  """

  # Initialize PyTorch SGD optimizer
  optimizer = optim.SGD(net.parameters(), lr=learning_rate)

  # Placeholder to save the loss at each iteration
  track_loss = []

  # Loop over epochs (cf. appendix)
  for i in range(n_iter):

    ######################################################################
    ## TO DO for students: fill in missing code for GD iteration
    #raise NotImplementedError("Student exercise: write code for GD iterations")
    ######################################################################

    # Evaluate loss using loss_fn
    out = net(train_data)  # compute network output from inputs in train_data
    loss = loss_fn(out,train_labels)  # evaluate loss function

    # Compute gradients
    optimizer.zero_grad()
    loss.backward()

    # Update weights
    optimizer.step()

    # Store current value of loss
    track_loss.append(loss.item())  # .item() needed to transform the tensor output of loss_fn to a scalar

    # Track progress
    if (i + 1) % (n_iter // 5) == 0:
      print(f'iteration {i + 1}/{n_iter} | loss: {loss.item():.3f}')

  return track_loss

# Set random seeds for reproducibility
np.random.seed(1)
torch.manual_seed(1)

# Initialize network
net = DeepNetReLU(n_neurons, 20)

# Initialize built-in PyTorch MSE loss function
loss_fn = nn.MSELoss()

# Run GD on data
train_loss = train(net, loss_fn, resp_train, stimuli_train)

# Plot the training loss over iterations of GD
plt.plot(train_loss)
plt.xlim([0, None])
plt.ylim([0, None])
plt.xlabel('iterations of gradient descent')
plt.ylabel('mean squared error')
plt.show()
```

[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W3D4_DeepLearning1/solutions/W3D4_Tutorial1_Solution_8f827dbe.py)

*Example output:*

---
# Section 4: Evaluating model performance

## Section 4.1: Generalization performance with test data

Note that gradient descent is essentially an algorithm for fitting the network's parameters to a given set of training data. Selecting this training data is thus crucial for ensuring that the optimized parameters **generalize** to unseen data they weren't trained on. In our case, for example, we want to make sure that our trained network is good at decoding stimulus orientations from neural responses to any orientation, not just those in our data set.

To ensure this, we have split up the full data set into a **training set** and a **testing set**. In Exercise 3, we trained a deep network by optimizing the parameters on a training set. We will now evaluate how good the optimized parameters are by using the trained network to decode stimulus orientations from neural responses in the testing set. Good decoding performance on this testing set should then be indicative of good decoding performance on the neurons' responses to any other stimulus orientation. This procedure is commonly used in machine learning (not just in deep learning)and is typically referred to as **cross-validation**.

We will compute the MSE on the test data and plot the decoded stimulus orientations as a function of the true stimulus.

```python
#@title
#@markdown Execute this cell to evaluate and plot test error

out = net(resp_test)  # decode stimulus orientation for neural responses in testing set
ori = stimuli_test  # true stimulus orientations
test_loss = loss_fn(out, ori)  # MSE on testing set (Hint: use loss_fn initialized in previous exercise)

plt.plot(ori, out.detach(), '.')  # N.B. need to use .detach() to pass network output into plt.plot()
identityLine()  # draw the identity line y=x; deviations from this indicate bad decoding!
plt.title('MSE on testing set: %.2f' % test_loss.item())  # N.B. need to use .item() to turn test_loss into a scalar
plt.xlabel('true stimulus orientation ($^o$)')
plt.ylabel('decoded stimulus orientation ($^o$)')
axticks = np.linspace(0, 360, 5)
plt.xticks(axticks)
plt.yticks(axticks)
plt.show()
```

**PyTorch Note**:

An important thing to note in the code snippet for plotting the decoded orientations is the `.detach()` method. The PyTorch `nn.Module` class is special in that, behind the scenes, each of the variables inside it are linked to each other in a computational graph, for the purposes of automatic differentiation (the algorithm used in `.backward()` to compute gradients). As a result, if you want to do anything that is not a `torch` operation to the parameters or outputs of an `nn.Module` class, you'll need to first "detach" it from its computational graph. This is what the `.detach()` method does. In this hidden code above, we need to call it on the outputs of the network so that we can plot them with the `plt.plot()` function.

---
## (Bonus) Section 4.2: Model criticism

Please move to the Summary and visit this section only if you have time after completing all non-bonus material!

Let's now take a step back and think about how our model is succeeding/failing and how to improve it.

```python
#@title
#@markdown Execute this cell to plot decoding error

out = net(resp_test)  # decode stimulus orientation for neural responses in testing set
ori = stimuli_test  # true stimulus orientations
error = out - ori  # decoding error

plt.plot(ori, error.detach(), '.')   # plot decoding error as a function of true orientation (make sure all arguments to plt.plot() have been detached from PyTorch network!)

# Plotting
plt.xlabel('true stimulus orientation ($^o$)')
plt.ylabel('decoding error ($^o$)')
plt.xticks(np.linspace(0, 360, 5))
plt.yticks(np.linspace(-360, 360, 9))
plt.show()
```

### Think

In the cell below, we will plot the *decoding error* for each neural response in the testing set. The decoding error is defined as the decoded stimulus orientation minus true stimulus orientation
\begin{equation}
  \text{decoding error} = y^{(n)} - \tilde{y}^{(n)}
\end{equation}

In particular, we plot decoding error as a function of the true stimulus orientation.

  * Are some stimulus orientations harder to decode than others?
  * If so, in what sense? Are the decoded orientations for these stimuli more variable and/or are they biased?
  * Can you explain this variability/bias? What makes these stimulus orientations different from the others?
  * (Will be addressed in next exercise) Can you think of a way to modify the deep network in order to avoid this?

[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W3D4_DeepLearning1/solutions/W3D4_Tutorial1_Solution_3ccf8501.py)

### (Advanced Bonus) Exercise 4: Improving the loss function
As illustrated in the previous exercise, the squared error is not a good loss function for circular quantities like angles, since two angles that are very close (e.g. $1^o$ and $359^o$) might actually have a very large squared error.

Here, we'll avoid this problem by changing our loss function to treat our decoding problem as a **classification problem**. Rather than estimating the *exact* angle of the stimulus, we'll now aim to construct a decoder that classifies the stimulus into one of $C$ classes, corresponding to different bins of angles of width $b = \frac{360}{C}$. The true class $\tilde{y}^{(n)}$ of stimulus $i$ is now given by
\begin{equation}
  \tilde{y}^{(n)} =
  \begin{cases}
    1 &\text{if angle of stimulus $n$ is in the range } [0, b] \\
    2 &\text{if angle of stimulus $n$ is in the range } [b, 2b] \\
    3 &\text{if angle of stimulus $n$ is in the range } [2b, 3b] \\
    \vdots \\
    C &\text{if angle of stimulus $n$ is in the range } [(C-1)b, 360]
  \end{cases}
\end{equation}

We have a helper function `stimulus_class` that will extract `n_classes` stimulus classes for us from the stimulus orientations.

To decode the stimulus class from neural responses, we'll use a deep network that outputs a $C$-dimensional vector of probabilities $\mathbf{p} = \begin{bmatrix} p_1, p_2, \ldots, p_C \end{bmatrix}^T$, corresponding to the estimated probabilities of the stimulus belonging to each class $1, 2, \ldots, C$.

To ensure the network's outputs are indeed probabilities (i.e. they are positive numbers between 0 and 1, and sum to 1), we'll use a [softmax function](https://en.wikipedia.org/wiki/Softmax_function) to transform the real-valued outputs from the hidden layer into probabilities. Letting $\sigma(\cdot)$ denote this softmax function, the equations describing our network are
\begin{align}
    \mathbf{h}^{(n)} &= \phi(\mathbf{W}^{in} \mathbf{r}^{(n)} + \mathbf{b}^{in}), && [\mathbf{W}^{in}: M \times N], \\
    \mathbf{p}^{(n)} &= \sigma(\mathbf{W}^{out} \mathbf{h}^{(n)} + \mathbf{b}^{out}),  && [\mathbf{W}^{out}: C \times M],
\end{align}
The decoded stimulus class is then given by that assigned the highest probability by the network:
\begin{equation}
  y^{(n)} = \underset{i}{\arg\max} \,\, p_i
\end{equation}
The softmax function can be implemented in PyTorch simply using `torch.softmax()`.

Often *log* probabilities are easier to work with than actual probabilities, because probabilities tend to be very small numbers that computers have trouble representing. We'll therefore actually use the logarithm of the softmax as the output of our network,
\begin{equation}
    \mathbf{l}^{(n)} = \log \left( \mathbf{p}^{(n)} \right)
\end{equation}
which can implemented in PyTorch together with the softmax via an `nn.LogSoftmax` layer. The nice thing about the logarithmic function is that it's *monotonic*, so if one probability is larger/smaller than another, then its logarithm is also larger/smaller than the other's. We therefore have that
\begin{equation}
  y^{(n)} = \underset{i}{\arg\max} \,\, p_i^{(n)} = \underset{i}{\arg\max} \, \log p_i^{(n)} = \underset{i}{\arg\max} \,\, l_i^{(n)}
\end{equation}

See the next cell for code for constructing a deep network with one hidden layer that of ReLU's that outputs a vector of log probabilities.

```python
# Deep network for classification
class DeepNetSoftmax(nn.Module):
  """Deep Network with one hidden layer, for classification

  Args:
    n_inputs (int): number of input units
    n_hidden (int): number of units in hidden layer
    n_classes (int): number of outputs, i.e. number of classes to output
      probabilities for

  Attributes:
    in_layer (nn.Linear): weights and biases of input layer
    out_layer (nn.Linear): weights and biases of output layer

  """

  def __init__(self, n_inputs, n_hidden, n_classes):
    super().__init__()  # needed to invoke the properties of the parent class nn.Module
    self.in_layer = nn.Linear(n_inputs, n_hidden)  # neural activity --> hidden units
    self.out_layer = nn.Linear(n_hidden, n_classes)  # hidden units --> outputs
    self.logprob = nn.LogSoftmax(dim=1)  # probabilities across columns should sum to 1 (each output row corresponds to a different input)

  def forward(self, r):
    """Predict stimulus orientation bin from neural responses

    Args:
      r (torch.Tensor): n_stimuli x n_inputs tensor with neural responses to n_stimuli

    Returns:
      torch.Tensor: n_stimuli x n_classes tensor with predicted class probabilities

    """
    h = torch.relu(self.in_layer(r))
    logp = self.logprob(self.out_layer(h))
    return logp
```

What should our loss function now be? Ideally, we want the probabilities outputted by our network to be such that the probability of the true stimulus class is high. One way to formalize this is to say that we want to maximize the *log* probability of the true stimulus class $\tilde{y}^{(n)}$ under the class probabilities predicted by the network,
\begin{equation}
  \log \left( \text{predicted probability of stimulus } n \text{ being of class } \tilde{y}^{(n)} \right) = \log p^{(n)}_{\tilde{y}^{(n)}} = l^{(n)}_{\tilde{y}^{(n)}}
\end{equation}
To turn this into a loss function to be *minimized*, we can then simply multiply it by -1: maximizing the log probability is the same as minimizing the *negative* log probability. Summing over a batch of $P$ inputs, our loss function is then given by
\begin{equation}
  L = -\sum_{n=1}^P \log p^{(n)}_{\tilde{y}^{(n)}} = -\sum_{n=1}^P l^{(n)}_{\tilde{y}^{(n)}}
\end{equation}
In the deep learning community, this loss function is typically referred to as the **cross-entropy**, or **negative log likelihood**. The corresponding built-in loss function in PyTorch is `nn.NLLLoss()` (documentation [here](https://pytorch.org/docs/master/generated/torch.nn.CrossEntropyLoss.html)).

In the next cell, we've provided most of the code to train and test a network to decode stimulus orientations via classification, by minimizing the negative log likelihood. Fill in the missing pieces.

Once you've done this, have a look at the plotted results. Does changing the loss function from mean squared error to a classification loss solve our problems? Note that errors may still occur -- but are these errors as bad as the ones that our network above was making?

```python
def decode_orientation(n_classes, train_data, train_labels, test_data, test_labels):
  """ Initialize, train, and test deep network to decode binned orientation from neural responses

  Args:
    n_classes (scalar): number of classes in which to bin orientation
    train_data (torch.Tensor): n_train x n_neurons tensor with neural
      responses to train on
    train_labels (torch.Tensor): n_train x 1 tensor with orientations of the
      stimuli corresponding to each row of train_data, in radians
    test_data (torch.Tensor): n_test x n_neurons tensor with neural
      responses to train on
    test_labels (torch.Tensor): n_test x 1 tensor with orientations of the
      stimuli corresponding to each row of train_data, in radians

  Returns:
    (list, torch.Tensor): training loss over iterations, n_test x 1 tensor with predicted orientations of the
      stimuli from decoding neural network
  """

  # Bin stimulus orientations in training set
  train_binned_labels = stimulus_class(train_labels, n_classes)

  ##############################################################################
  ## TODO for students: fill out missing pieces below to initialize, train, and
  # test network
  # Fill out function and remove
  raise NotImplementedError("Student exercise: complete decode_orientation function")
  ##############################################################################

  # Initialize network
  net = ...  # use M=20 hidden units

  # Initialize built-in PyTorch MSE loss function
  loss_fn = nn.NLLLoss()

  # Run GD on training set data, using learning rate of 0.1
  train_loss = ...

  # Decode neural responses in testing set data
  out = ...
  out_labels = np.argmax(out.detach(), axis=1)  # predicted classes

  return train_loss, out_labels

# Set random seeds for reproducibility
np.random.seed(1)
torch.manual_seed(1)

n_classes = 12  # start with 12, then (bonus) try making this as big as possible! does decoding get worse?

# Uncomment below to test your function

# Initialize, train, and test network
#train_loss, predicted_test_labels = decode_orientation(n_classes, resp_train, stimuli_train, resp_test, stimuli_test)

# Plot results
#plot_decoded_results(train_loss, stimuli_test, predicted_test_labels)
```

[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W3D4_DeepLearning1/solutions/W3D4_Tutorial1_Solution_e2e84634.py)

*Example output:*

---
# Summary

We have now covered a number of common and powerful techniques for applying deep learning to decoding from neural data, some of which are common to almost any machine learning problem:
* Building and training deep networks using the **PyTorch** `nn.Module` class and built-in **optimizers**
* Choosing and evaluating **loss functions**
* Testing a trained model on unseen data via **cross-validation**, by splitting the data into a **training set and testing set**

An important aspect of this tutorial was the `train()` function we wrote in exercise 6. Note that it can be used to train *any* network to minimize *any* loss function (cf. advanced exercise) on *any* training data. This is the power of using PyTorch to train neural networks and, for that matter, **any other model**! There is nothing in the `nn.Module` class that forces us to use `nn.Linear` layers that implement neural network operations. You can actually put anything you want inside the `.__init__()` and `.forward()` methods of this class. As long as its parameters and computations involve only `torch.Tensor`'s, and the model is differentiable, you'll then be able to optimize the parameters of this model in exactly the same way we optimized the deep networks here.

What kinds of conclusions can we draw from these sorts of analyses? If we can decode the stimulus well from visual cortex activity, that means that there is information about this stimulus available in visual cortex. Whether or not the animal uses that information to make decisions is not determined from an analysis like this. In fact mice perform poorly in orientation discrimination tasks compared to monkeys and humans, even though they have information about these stimuli in their visual cortex. Why do you think they perform poorly in orientation discrimination tasks?

See this paper for some potential hypotheses (https://www.biorxiv.org/content/10.1101/679324v2), but this is totally an open question!

---
# Appendix

## Neural network *depth*, *width* and *expressivity*

Two important architectural choices that always have to be made when constructing deep feed-forward networks like those used here are
* the number of hidden layers, or the network's *depth*
* the number of units in each layer, or the layer *widths*

Here, we restricted ourselves to networks with a single hidden layer with a width of $M$ units, but it is easy to see how this code could be adapted to arbitrary depths. Adding another hidden layer simply requires adding another `nn.Linear` module to the `__init__()` method and incorporating it into the `.forward()` method.

The depth and width of a network determine the set of input/output transormations that it can perform, often referred to as its *expressivity*. The deeper and wider the network, the more *expressive* it is; that is, the larger the class of input/output transformations it can compute. In fact, it turns out that an infinitely wide *or* infinitely deep networks can in principle [compute (almost) *any* input/output transformation](https://en.wikipedia.org/wiki/Universal_approximation_theorem).

A classic mathematical demonstration of the power of depth is given by the so-called [XOR problem](https://medium.com/@jayeshbahire/the-xor-problem-in-neural-networks-50006411840b#:~:text=The%20XOr%2C%20or%20%E2%80%9Cexclusive%20or,value%20if%20they%20are%20equal.). This toy problem demonstrates how even a single hidden layer can drastically expand the set of input/output transformations a network can perform, relative to a shallow network with no hidden layers. The key intuition is that the hidden layer allows you to represent the input in a new format, which can then allow you to do almost anything you want with it. The *wider* this hidden layer, the more flexibility you have in this representation. In particular, if you have more hidden units than input units, then the hidden layer representation of the input is higher-dimensional than the raw data representation. This higher dimensionality effectively gives you more "room" to perform arbitrary computations in. It turns out that even with just this one hidden layer, if you make it wide enough you can actually approximate any input/output transformation you want. See [here](http://neuralnetworksanddeeplearning.com/chap4.html) for a neat visual demonstration of this.

In practice, however, it turns out that increasing depth seems to grant more expressivity with fewer units than increasing width does (for reasons that are not well understood). It is for this reason that truly *deep* networks are almost always used in machine learning, which is why this set of techniques is often referred to as *deep* learning.

That said, there is a cost to making networks deeper and wider. The bigger your network, the more parameters (i.e. weights and biases) it has, which need to be optimized! The extra expressivity afforded by higher width and/or depth thus carries with it (at least) two problems:
* optimizing more parameters usually requires more data
* a more highly parameterized network is more prone to overfit to the training data, so requires more sophisticated optimization algorithms to ensure generalization

## Gradient descent equations

Here we provide the equations for the three steps of the gradient descent algorithm, as applied to our decoding problem:

1. **Evaluate the loss** on the training data. For a mean squared error loss, this is given by
\begin{equation}
    L = \frac{1}{P}\sum_{n=1}^P (y^{(n)} - \tilde{y}^{(n)})^2
\end{equation}
where $y^{(n)}$ denotes the stimulus orientation decoded from the population response $\mathbf{r}^{(n)}$ to the $n$th stimulus in the training data, and $\tilde{y}^{(n)}$ is the true orientation of that stimulus. $P$ denotes the total number of data samples in the training set. In the syntax of our `train()` function above, $\mathbf{r}^{(n)}$ is given by `train_data[n, :]` and $\tilde{y}^{(n)}$ by `train_labels[n]`.

2. **Compute the gradient of the loss** with respect to each of the network weights. In our case, this entails computing the quantities
\begin{equation}
    \frac{\partial L}{\partial \mathbf{W}^{in}}, \frac{\partial L}{\partial \mathbf{b}^{in}}, \frac{\partial L}{\partial \mathbf{W}^{out}}, \frac{\partial L}{\partial \mathbf{b}^{out}}
\end{equation}
Usually, we would require lots of math in order to derive each of these gradients, and lots of code to compute them. But this is where PyTorch comes to the rescue! Using a cool technique called [automatic differentiation](https://en.wikipedia.org/wiki/Automatic_differentiation), PyTorch automatically calculates these gradients when the `.backward()` function is called.

  More specifically, when this function is called on a particular variable (e.g. `loss`, as above), PyTorch will compute the gradients with respect to each network parameter. These are computed and stored behind the scenes, and can be accessed through the `.grad` attribute of each of the network's parameters. As we saw above, however, we actually never need to look at or call these gradients when implementing gradient descent, as this can be taken care of by PyTorch's built-in optimizers, like `optim.SGD`.

3. **Update the network weights** by descending the gradient:
\begin{align}
    \mathbf{W}^{in} &\leftarrow \mathbf{W}^{in} - \alpha \frac{\partial L}{\partial \mathbf{W}^{in}} \\
    \mathbf{b}^{in} &\leftarrow \mathbf{b}^{in} - \alpha \frac{\partial L}{\partial \mathbf{b}^{in}} \\
    \mathbf{W}^{out} &\leftarrow \mathbf{W}^{out} - \alpha \frac{\partial L}{\partial \mathbf{W}^{out}} \\
    \mathbf{b}^{out} &\leftarrow \mathbf{b}^{out} - \alpha \frac{\partial L}{\partial \mathbf{b}^{out}}
\end{align}
where $\alpha$ is called the **learning rate**. This **hyperparameter** of the SGD algorithm controls how far we descend the gradient on each iteration. It should be as large as possible so that fewer iterations are needed, but not too large so as to avoid parameter updates from skipping over minima in the loss landscape.

While the equations written down here are specific to the network and loss function considered in this tutorial, the code provided above for implementing these three steps is completely general: no matter what loss function or network you are using, exactly the same commands can be used to implement these three steps.

## *Stochastic* gradient descent (SGD) vs. gradient descent (GD)

In this tutorial, we used the gradient descent algorithm, which differs in a subtle yet very important way from the more commonly used **stochastic gradient descent (SGD)** algorithm. The key difference is in the very first step of each iteration, where in the GD algorithm we evaluate the loss *at every data sample in the training set*. In SGD, on the other hand, we evaluate the loss only at a random subset of data samlpes from the full training set, called a **mini-batch**. At each iteration, we randomly sample a mini-batch to perform steps 1-3 on. All the above equations still hold, but now the $P$ data samples $\mathbf{r}^{(n)}, \tilde{y}^{(n)}$ denote a mini-batch of $P$ random samples from the training set, rather than the whole training set.

There are several reasons why one might want to use SGD instead of GD. The first is that the training set might be too big, so that we actually can't actually evaluate the loss on every single data sample in it. In this case, GD is simply infeasible, so we have no choice but to turn to SGD, which bypasses the restrictive memory demands of GD by sub-sampling the training set into smaller mini-batches.

But, even when GD is feasible, SGD turns out to be generally better. The stochasticity induced by the extra random sampling step in SGD effectively adds some noise in the search for local minima of the loss function. This can be really useful for avoiding potential local minima, and enforce that whatever minimum is converged to is a good one. This is particularly important when networks are wider and/or deeper, in which case the large number of parameters can lead to overfitting.

Here, we used only GD because (1) it is simpler, and (2) it suffices for the problem being considered here. Because we have so many neurons in our data set, decoding is not too challenging and doesn't require a particularly deep or wide network. The small number of parameters in our deep networks therefore can be optimized without a problem using GD.