Workshop: Advanced Computation (with Python)

From Design and Build Lab
Revision as of 21:11, 30 September 2019 by JosephM (talk | contribs)
Jump to navigation Jump to search

Modules and Packages

Modules and packages are a feature of Python wherein, you can import subtasks (or modules) into your code. Using modules and packages leads to cleaner code because the files you create are less verbose.

Modules

Suppose you write an algorithm called sort.py which sorts a given dataset alphanumerically. Anytime you write a python script where you want to utilize this alphanumeric sorting function you can import the sort.py script into your existing code as a module with the following line:

import sort


Packages

Some coders write large modules and publish them for public use. We call these open source modules “packages”. SciPy, NumPy and matplotlib are all examples of popular python packages. We import them into our code with the same syntax as with modules. We can create a nickname for each package, simply “import [packagename] as [nickname]”.

import numpy as np

import scipy

import matplotlib as plt


Install Some Packages

For this tutorial we will be installing three packages. Please follow along.

  • For Windows - Open command prompt (go to the search bar, type “cmd” then enter).
  • For Mac - Open terminal

Now that you are in either command prompt or terminal, we are going to install NumPy, SciPy, and Matplotlib. Type in the following commands one-by-one, waiting for them to execute completely before entering the next one.

python -m pip install numpy

python -m pip install scipy

python -m pip install matplotlib

So what are these packages?

  • NumPy - This package gives you methods allow you to make arrays/matrices. It makes representing, analyzing and computing data easy.
  • SciPy - This package gives you further scientific computational resources including functions for optimization, linear algebra, FFT, signal and image processing and much more.
  • Matplotlib - This is a plotting library which gives you an easy way to visually represent data sets.


Using Packages

When you decide that you want to implement a package it is important to refer to the package’s official documentation. The documentation is a guide which can show you the capabilities, limitations and implementation of the package. The documentation for SciPy, NumPy and Matplotlib can be found under “Other Educational Resources for Python” at the end of this workshop.

All methods and functions which come along with the package can be called by their nickname (or the package name if no nickname was assigned in the import command).

NumPy example documentation.png
Np example.png