Profiling, debugging and testing with Python. Jonathan Bollback, Georg Rieckh and Jose Guzman

Similar documents
Intro to scientific programming (with Python) Pietro Berkes, Brandeis University

CIS 192: Lecture 13 Scientific Computing and Unit Testing

Advanced Topics: Biopython

Survey of Unit-Testing Frameworks. by John Szakmeister and Tim Woods

Writing robust scientific code with testing (and Python) Pietro Berkes, Enthought UK

Assignment 2: Option Pricing and the Black-Scholes formula The University of British Columbia Science One CS Instructor: Michael Gelbart

Introduction to Python

Introduction to Python

Computing Concepts with Java Essentials

CSE 6040 Computing for Data Analytics: Methods and Tools

Exercise 0. Although Python(x,y) comes already with a great variety of scientic Python packages, we might have to install additional dependencies:

Self-review 9.3 What is PyUnit? PyUnit is the unit testing framework that comes as standard issue with the Python system.

CUDAMat: a CUDA-based matrix class for Python

Computer Science 1 CSci 1100 Lecture 3 Python Functions

HPC Wales Skills Academy Course Catalogue 2015

CS 1133, LAB 2: FUNCTIONS AND TESTING

Python for Scientific Computing.

Applications to Computational Financial and GPU Computing. May 16th. Dr. Daniel Egloff

AQA GCSE in Computer Science Computer Science Microsoft IT Academy Mapping

Microsoft Windows PowerShell v2 For Administrators

Test Driven Development in Python

Python programming Testing

Python Classes and Objects

personalkollen fredag 5 juli 13

CME 193: Introduction to Scientific Python Lecture 8: Unit testing, more modules, wrap up

Software Testing with Python

Monitoring, Tracing, Debugging (Under Construction)

CRASH COURSE PYTHON. Het begint met een idee

An introduction to Python Programming for Research

Python and Google App Engine

Software Testing. Theory and Practicalities

Objects and classes. Objects and classes. Jarkko Toivonen (CS Department) Programming in Python 1

Python Testing with unittest, nose, pytest

FEEG Applied Programming 5 - Tutorial Session

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

Python programming guide for Earth Scientists. Maarten J. Waterloo and Vincent E.A. Post

Python 2 and 3 compatibility testing via optional run-time type checking

Welcome to Introduction to programming in Python

WESTMORELAND COUNTY PUBLIC SCHOOLS Integrated Instructional Pacing Guide and Checklist Computer Math

How to write a bash script like the python? Lloyd Huang. KaLUG - Kaohsiung Linux User Group COSCUP Aug

Python. Python. 1 Python. M.Ulvrova, L.Pouilloux (ENS LYON) Informatique L3 Automne / 25

An Introduction to APGL

Modeling with Python

Slides from INF3331 lectures - web programming in Python

Scientific Programming in Python

WebIOPi. Installation Walk-through Macros

Introduction to Python

Optimizing and interfacing with Cython. Konrad HINSEN Centre de Biophysique Moléculaire (Orléans) and Synchrotron Soleil (St Aubin)

Software Tool Seminar WS Taming the Snake

Objectives. Python Programming: An Introduction to Computer Science. Lab 01. What we ll learn in this class

Testing for Security

Visual Basic Programming. An Introduction

Computational Mathematics with Python

Peach Fuzzer Platform

ADVANCED SCHOOL OF SYSTEMS AND DATA STUDIES (ASSDAS) PROGRAM: CTech in Computer Science

Course MS10975A Introduction to Programming. Length: 5 Days

Chapter 12 Programming Concepts and Languages

Python Programming: An Introduction to Computer Science

Python Loops and String Manipulation

latest Release 0.2.6

Visual Basic. murach's TRAINING & REFERENCE

The Clean programming language. Group 25, Jingui Li, Daren Tuzi

Programmierpraktikum

Introduction to Python for Text Analysis

How To Train A Face Recognition In Python And Opencv

Compute Cluster Server Lab 3: Debugging the parallel MPI programs in Microsoft Visual Studio 2005

Driving a Time-based Simulation from MATLAB for Custom Calculations and Control

Thomas Jefferson High School for Science and Technology Program of Studies Foundations of Computer Science. Unit of Study / Textbook Correlation

#820 Computer Programming 1A

Introduction to FreeNAS development

Computational Mathematics with Python

Rake Task Management Essentials

Invitation to Ezhil : A Tamil Programming Language for Early Computer-Science Education 07/10/13

Unit testing with JUnit and CPPUnit. Krzysztof Pietroszek

Obfuscation: know your enemy

Python Documentation & Startup

Slides prepared by : Farzana Rahman TESTING WITH JUNIT IN ECLIPSE

Introducing Tetra: An Educational Parallel Programming System

Unit Testing. and. JUnit

General Software Development Standards and Guidelines Version 3.5

Debugging and Profiling Lab. Carlos Rosales, Kent Milfeld and Yaakoub Y. El Kharma

Availability of the Program A free version is available of each (see individual programs for links).

GPU Tools Sandra Wienke

River Dell Regional School District. Computer Programming with Python Curriculum

GET 114 Computer Programming Course Outline. Contact: Office Hours: TBD (or by appointment)

QEngine Technical Paper. Building Maintainable Test Cases with QEngine

Simulation Tools. Python for MATLAB Users I. Claus Führer. Automn Claus Führer Simulation Tools Automn / 65

Module 10. Coding and Testing. Version 2 CSE IIT, Kharagpur

A Comparison of C, MATLAB, and Python as Teaching Languages in Engineering

Parallel Debugging with DDT

Setting up PostgreSQL

SQL and PL/SQL Development and Leveraging Oracle Multitenant in Visual Studio. Christian Shay Product Manager, NET Technologies Oracle

Big Data Analytics with Spark and Oscar BAO. Tamas Jambor, Lead Data Scientist at Massive Analytic

Python. KS3 Programming Workbook. Name. ICT Teacher Form. Do you speak Parseltongue?

Intel Tunnel Mountain Software Development Platform Overview, IHV Tools Update

Syntax Check of Embedded SQL in C++ with Proto

WAYNESBORO AREA SCHOOL DISTRICT CURRICULUM INTRODUCTION TO COMPUTER SCIENCE (June 2014)

Transcription:

Profiling, debugging and testing with Python Jonathan Bollback, Georg Rieckh and Jose Guzman

Overview 1.- Profiling 4 Profiling: timeit 5 Profiling: exercise 6 2.- Debugging 7 Debugging: pdb 8 Debugging: exercise 11 3.- Testing 12 Simple case testing 13 Unittesting: exercise 16 Documentation 17... it is all about writing good code

1.- Profiling Code optimization refers to the practice of reducing the processor time of an algorithm or function. Two rules to write optimized code (in Python) 1. avoid for loops if possible 2. use existing routines or modules (e.g NumPy/Scipy libraries) To evaluate where the code spends more of its time we need a Profiler 1.- Profiling

Profiling: timeit Syntax: Timer("main statement", "setup statement") timeit() returns the time (in seconds) that takes to execute the main statement. It takes the number of executions as argument. from timeit import Timer myprofiler = Timer("np.random.rand(1e6)", "import numpy as np") myprofiler.timeit(2) # call main statement 2 times 0.061825990676879883 repeat(n, m) calls timeit(m) n-times to execute the main statement m-times and returns a list. myprofiler.repeat(3, 2) # call timeit(2) 3 times [0.065870046615600586, 0.061974048614501953, 0.061568975448608398] Profiling: timeit

Profiling: exercise We will evaluate the following functions described in matrices.py 1. matrix_python0(n,p) 2. matrix_python1(n,p) 3. matrix_python2(n,p) 4. matrix_numpy(n,p) 5. matrix_numpy1(n,p) 6. matrix_c(n,p) where n is the size of a quadratic matrix whose elements are one with a probability of p, or zero otherwise. To profile generate 10 matrices of size 1000 and 0.5 probabilities (n=1000, p=0.5) return the average of at least 20 profiles to have a representative measurement Profiling: exercise

2.- Debugging A bug is a failure in a routine that blocks the standard execution of a program. A bug is not: An exception (i.e the program does not work under specified conditions) A not implemented feature (i.e a program do not cover all features) Example Find 2+1 bugs in the code above def sphere_volume(radius): returns the volume of a sphere of radius given as argument vol = (3/4)*PI*(raduis)**3 return(vol) 2.- Debugging

Debugging: pdb pdb is a command-line based debugger it opens an interactive shell that allows us: to examine and change the value of variables execute code line by line set up breakpoints examine call stacks To execute the Python debugger we simply type in our shell: $ pdb <filename>.py Debugging: pdb

pdb basic commands: Demo quit [q] quit debugging next [n] executes the next statement print [p] prints the value of a variable list [l] list the current code continue [c] continues until pdb.set_trace() statement We will run the pdb debugger on simple.py to know if the variable val is taking the right values. def parabola(x, c): returns the solution to f(x) = x^2 + c return(x**2+c) if name == ' main ': offset = 8 for i in range(0,10,2): val = parabola(x=i, c=offset) pdb basic commands:

pdb basic commands:

Debugging: exercise Use a debugger to find the following discrepancy in debugme.py : from debugme import average1 mydata = range(10) average1(mydata) >>> 0 sum(mydata)/10. # point in denominator to return a float >>> 4.5 Debugging: exercise

3.- Testing Test suites are fundamental part of modern programming techniques. unittest is the standard Python testing library Unittesting is designed to avoid errors of the type described bellow: from math import pi as PI def sphere_volume(radius): returns the volume of a sphere of radius given as argument volume(r) = 4/3*pi*r^3 vol = (3/4)*PI*(radius)**3 return(vol) 3.- Testing

Simple case testing A basic schema for unittesting look like this: import unittest class FirstTestCase(unittest.TestCase): first sets of tests def test_true(self): methods beginning with 'test' are executed self.asserttrue() self.assertfalse() if name == ' main ': unittest.main() Simple case testing

Simple case testing A first implementation for testing that the volume of a sphere is a float would be... import unittest from volume import sphere_volume as v_sphere class ReturnValues(unittest.TestCase): def test_is_float(self): Test if return values are floats sol = v_sphere(radius=1) self.asserttrue( type(sol) == float ) def test_is_not_int(self): Test if return values are floats sol = v_sphere(radius=1) self.assertfalse( type(sol) == int) Simple case testing

Unittesting cases TestCase methods Examples asserttrue() asserttrue( isinstance([1,2], list) ) asserttrue( 'Hi'.islower() ) assertfalse() assertfalse( isinstance([1,2], float) ) assertfalse( isinstance('hello', str) ) assertequal() assertequal( [2,3], [2,3] ) assertequal( 3.14, 3.1416) assertnotequal() assertnotequal( 1.2, 1.21 ) assertnotequal( 3.14, 3.14 ) assertalmostequal() assertalmostequal( 1.125, 1.12, 2 ) assertnotequal( 1.125, 1.12, 3) Unittesting cases

Unittesting: exercise Perform the testing of the function sphere_volume in volumen.py. For that, you can test that it returns its correct value: for radius=2 units the volume of a sphere is 18.84 units^3 Unittesting: exercise

Documentation Despite the whole debugging techniques, one of the best practices to write good code is to provide a good documentation: To Provide a thoughtful documentation of your code 1. Enter docstrings at the beginning of your file models.py Date: Sat Sep 8 2012 this script contains probability distribution functions... import numpy as np This allows the reader to have additional information about the file (titles tend to be rather unspecific). Documentation

2. Use doc strings in every new function/method def random(n, seed=none): returns a NumPy array with random numbers Arguments: n -- number of random in the array seed -- the seed Example: >>> random(5, 100) array([ 0.54340494, 0.27836939, 0.42451759, 0.84477613, 0.00471886]) if seed is not None: np.random.seend(seed) return np.random.rand(n) 3. Comment any non obvious piece of code np.random.rand(1e6) # we did not use a seed here Your doc strings will be accessible via the help statement in Python. To create HTML documentation of your scripts use pydoc -w myscript Documentation