Exercise: energy calculation

Please open notebook rsePython-S2E1.ipynb

The notebook can be downloaded from: https://anaconda.org/ucl-rits/rrp-s2-ex-energyexample

Diffusion model in 1D

Description: A one-dimensional diffusion model. (Could be a gas of particles, or a bunch of crowded people in a corridor, or animals in a valley habitat…)

Implementation:

import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline

density =  np.array([0, 0, 3, 5, 8, 4, 2, 1])
fig, ax = plt.subplots()
ax.bar(np.arange(len(density))-0.5, density)
ax.xrange=[-0.5, len(density)-0.5]
ax.set_ylabel("Particle count $n_i$")
ax.set_xlabel("Position $i$")

<matplotlib.text.Text at 0x16626dd2ac8>

png

Here, the total energy due to position 2 is $3 (3-1)=6$, and due to column 7 is $1 (1-1)=0$. We need to sum these to get the total energy.

Starting point

Create a Python module:

%%bash
mkdir -p diffusion
touch diffusion/__init__.py

89 packages can be updated.

61 updates are security updates.

%%writefile diffusion/model.py
def energy(density, coeff=1.0):
  """ Energy associated with the diffusion model

      Parameters
      ----------

      density: array of positive integers
          Number of particles at each position i in the array
      coeff: float
          Diffusion coefficient.
  """
  # implementation goes here

Overwriting diffusion/model.py

%%writefile diffusion/test_model.py
from .model import energy
def test_energy():
  """ Optional description for nose reporting """
  # Test something

Overwriting diffusion/test_model.py

Invoke the tests:

%%bash
cd diffusion
py.test

Microsoft Windows [Version 10.0.15063]

(c) 2017 Microsoft Corporation. All rights reserved.

C:\Users\jhetherington.TURING\devel\rsd-engineeringcourse\ch03tests>cd diffusion

C:\Users\jhetherington.TURING\devel\rsd-engineeringcourse\ch03tests\diffusion>py.test

============================= test session starts =============================

platform win32 – Python 3.5.3, pytest-3.1.2, py-1.4.34, pluggy-0.4.0

rootdir: C:\Users\jhetherington.TURING\devel\rsd-engineeringcourse\ch03tests\diffusion, inifile:

plugins: cov-2.5.1

collected 1 items

test_model.py .

========================== 1 passed in 0.17 seconds ===========================

C:\Users\jhetherington.TURING\devel\rsd-engineeringcourse\ch03tests\diffusion>

Now, write your code (in model.py), and tests (in test_model.py), testing as you go.

Return to Modules