<commit_before>{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from IPython.core.display import HTML\n",
    "def css_styling():\n",
    "    sheet = '../css/custom.css'\n",
    "    styles = open(sheet, \"r\").read() \n",
    "    return HTML(styles)\n",
    "css_styling()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Python OOP 1: Basics and Initialisation"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The previous exercise has required you to use numpy dtypes as a means for structuring some simple image data. Classes could also be used for neater syntax and more readable code. The task in this exercise is to repeat the previous exercise using a class.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import os\n",
    "import matplotlib.pyplot as plt\n",
    "import matplotlib.cm as cm\n",
    "import numpy as np\n",
    "import sys\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Task breakdown\n",
    "\n",
    "Using the previous exercise as a reference point, create a `SquareImage` class which reads (portable greymap, '.pgm') image data from a file. The class should implement the following:\n",
    "\n",
    "\n",
    "1. The Initialiser method `__init__(self, ...)`, which takes a string `filename` as an argument and\n",
    "    - stores $Nx$ and $Ny$ as *instance attributes*, both equal to 72 (this isn't robust, but simplifies the exercise)\n",
    "    \n",
    "    - calculates and stores $x$ and $y$ as *instance attrbutes*. These are again the regularly spaced pixel $x$ and $y$ values from 1 to 0 (image colour values in pgm files start from top right pixel) - use linspace from 1 to 0 with $Nx$ and $Ny$ points respectively\n",
    "    \n",
    "    - Read and store image grey levels in `filename` as an *instance attribute*, $z$. The line for extracting this data from the files is the same as before,\n",
    "    >`np.loadtxt(filename, skiprows=4).reshape(self.Nx, self.Ny)`\n",
    "\n",
    "2. An `add_image` method which takes an `image` argument, and adds the z component of image to `self.z`\n",
    "    - don't forget to add `self` as the first argument! Instance methods require us to be specific\n",
    "\n",
    "3. A `plot` method which takes no extra arguments, and plots the current instance attributes $z$ as a contour vs $x$ and $y$ (also instance attributes). As this exercise is not testing your matplotlib, we provide the code for the function here:\n",
    "\n",
    "    > `fig = plt.figure()\n",
    "    > ax = fig.add_subplot(111, aspect='equal')\n",
    "    > ax.contourf(self.x, self.y, self.z, cmap=cm.Greys_r)\n",
    "    > plt.show()`\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Implement the SquareImage class here:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# The image file names\n",
    "names = ['img1.pgm', 'img2.pgm', 'img3.pgm', 'img4.pgm']\n",
    "files = [os.path.join('data', name) for name in names]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The following cell has left out some code where indicated - Fill them in!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Instantiate the class and plot each picture. \n",
    "imgs = []\n",
    "for f in files:\n",
    "    # Produce an instance of SquareImage, passing 'f' as an argument\n",
    "    # image = ...\n",
    "    \n",
    "    print(image)\n",
    "    imgs.append(image)           # objects are first class instances: add to a list\n",
    "    \n",
    "    # Use the 'plot' method to plot the instance\n",
    "    # ...\n",
    "    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Extension\n",
    "\n",
    "Now that we can read in image data from a file, extend your `SquareImages` class above so that if the filename is '`None`', we store the $z$ attribute as `np.zeros([Nx, Ny])`.\n",
    "\n",
    "* This will require an if statement, e.g.:\n",
    "    > `if filename is None`\n",
    "    >     store z as zeros\n",
    "    > `else`\n",
    "    >     read and store z data\n",
    "    \n",
    "* The default `filename` argument should be None, so that SquareImage() produces an 'empty' image."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Create an 'empty' SquareImage \n",
    "combined = SquareImage()\n",
    "print(combined.z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now use the `add_image` method of the empty image to add on the contents of all other image in the list of `imgs`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# EXERCISE: Loop over the list of images and add on each image's z values to `combined':\n",
    "# ...\n",
    "# ...\n",
    "\n",
    "\n",
    "# Plot\n",
    "combined.plot()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# [Solutions](../soln/02-Predator_prey.ipynb)\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
<commit_msg>Fixing broken link in exercises<commit_after>{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from IPython.core.display import HTML\n",
    "def css_styling():\n",
    "    sheet = '../css/custom.css'\n",
    "    styles = open(sheet, \"r\").read() \n",
    "    return HTML(styles)\n",
    "css_styling()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Python OOP 1: Basics and Initialisation"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The previous exercise has required you to use numpy dtypes as a means for structuring some simple image data. Classes could also be used for neater syntax and more readable code. The task in this exercise is to repeat the previous exercise using a class.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import os\n",
    "import matplotlib.pyplot as plt\n",
    "import matplotlib.cm as cm\n",
    "import numpy as np\n",
    "import sys\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Task breakdown\n",
    "\n",
    "Using the previous exercise as a reference point, create a `SquareImage` class which reads (portable greymap, '.pgm') image data from a file. The class should implement the following:\n",
    "\n",
    "\n",
    "1. The Initialiser method `__init__(self, ...)`, which takes a string `filename` as an argument and\n",
    "    - stores $Nx$ and $Ny$ as *instance attributes*, both equal to 72 (this isn't robust, but simplifies the exercise)\n",
    "    \n",
    "    - calculates and stores $x$ and $y$ as *instance attrbutes*. These are again the regularly spaced pixel $x$ and $y$ values from 1 to 0 (image colour values in pgm files start from top right pixel) - use linspace from 1 to 0 with $Nx$ and $Ny$ points respectively\n",
    "    \n",
    "    - Read and store image grey levels in `filename` as an *instance attribute*, $z$. The line for extracting this data from the files is the same as before,\n",
    "    >`np.loadtxt(filename, skiprows=4).reshape(self.Nx, self.Ny)`\n",
    "\n",
    "2. An `add_image` method which takes an `image` argument, and adds the z component of image to `self.z`\n",
    "    - don't forget to add `self` as the first argument! Instance methods require us to be specific\n",
    "\n",
    "3. A `plot` method which takes no extra arguments, and plots the current instance attributes $z$ as a contour vs $x$ and $y$ (also instance attributes). As this exercise is not testing your matplotlib, we provide the code for the function here:\n",
    "\n",
    "    > `fig = plt.figure()\n",
    "    > ax = fig.add_subplot(111, aspect='equal')\n",
    "    > ax.contourf(self.x, self.y, self.z, cmap=cm.Greys_r)\n",
    "    > plt.show()`\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Implement the SquareImage class here:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# The image file names\n",
    "names = ['img1.pgm', 'img2.pgm', 'img3.pgm', 'img4.pgm']\n",
    "files = [os.path.join('data', name) for name in names]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The following cell has left out some code where indicated - Fill them in!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Instantiate the class and plot each picture. \n",
    "imgs = []\n",
    "for f in files:\n",
    "    # Produce an instance of SquareImage, passing 'f' as an argument\n",
    "    # image = ...\n",
    "    \n",
    "    print(image)\n",
    "    imgs.append(image)           # objects are first class instances: add to a list\n",
    "    \n",
    "    # Use the 'plot' method to plot the instance\n",
    "    # ...\n",
    "    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Extension\n",
    "\n",
    "Now that we can read in image data from a file, extend your `SquareImages` class above so that if the filename is '`None`', we store the $z$ attribute as `np.zeros([Nx, Ny])`.\n",
    "\n",
    "* This will require an if statement, e.g.:\n",
    "    > `if filename is None`\n",
    "    >     store z as zeros\n",
    "    > `else`\n",
    "    >     read and store z data\n",
    "    \n",
    "* The default `filename` argument should be None, so that SquareImage() produces an 'empty' image."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Create an 'empty' SquareImage \n",
    "combined = SquareImage()\n",
    "print(combined.z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now use the `add_image` method of the empty image to add on the contents of all other image in the list of `imgs`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# EXERCISE: Loop over the list of images and add on each image's z values to `combined':\n",
    "# ...\n",
    "# ...\n",
    "\n",
    "\n",
    "# Plot\n",
    "combined.plot()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# [Solutions](../soln/02-Classes_basics.ipynb)\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}

{'fraction_non_alphanumeric': 0.17524519737375374, 'fraction_numerical': 0.004701305017427252, 'mean_word_length': 2.542348550100488, 'pattern_counts': {'":': 162, '<': 3, '<?xml version=': 0, '>': 21, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7128984', 'n_tokens_mistral': 4381, 'n_tokens_neox': 4316, 'n_words': 1298}