This document provides an introduction and overview of the PYNQ platform and Python programming language. It discusses the PYNQ board hardware including its ARM processor and FPGA, as well as interfaces like PMOD connectors, LEDs, buttons, and switches. It also covers using overlays to extend the FPGA with custom logic, the Jupyter environment, Python syntax and basics, and common Python data types like lists and dictionaries. Examples and exercises are provided to help learn how to write Python code for I/O, conditionals, loops, mathematical operations, and list manipulation.
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
PYNQ Platform and Python Lesson
1. Firma convenzione
Politecnico di Milano e Veneranda Fabbrica
del Duomo di Milano
Aula Magna – Rettorato
Mercoledì 27 maggio 2015
Lesson 1: Introduction to PYNQ Platform
and Python language
Luca Cerina – luca.cerina@polimi.it
Ver. Updated – 22/11/2017
3. Luca Cerina, R.A. @ NECSTLab – DEIB
PYNQ Board
3
Communicaton over
ethernet
Jutpyter serverJutpyter server
Pynq APIPynq API
FPGA: programmabile logic
ARM Processor
PMODHDMI (out, in)
Audio
connectors
GPIO: leds, butoos, switches
Ethernet
Overlay
(base.bit)
Overlay
(base.bit)
USB
Micro SD
(Linux OS +
Jutpyter
notebook)
Pyoq Board
4. Luca Cerina, R.A. @ NECSTLab – DEIB
FPGA: Field Programmable Gate Arrays
A fully retprogrammable chitp in which diferent basic blocks,
like Look-Utp-Tables, Memory, and Flitp-Flotps internally
connects together to recreate comtplex digital circuits.
5. Luca Cerina, R.A. @ NECSTLab – DEIB
THE COMMUNITY FUNNEL
Atptplicaton
develotpers
Driver develotpers
Overlay designers
● Python on jutpyter
● Everything else
● Vivado SDK
● C/C++
● Python wratptpers
● Vivado/SDSoC
suite
● C/C++, VHDL
8. Luca Cerina, R.A. @ NECSTLab – DEIB
LED, Butoos aod switches
Pynq provides:
• 6 LED commanded from Python (2 RGB)
• 2 Switches and 4 Buttons with readable state
9. Luca Cerina, R.A. @ NECSTLab – DEIB
WHAT IS AN OVERLAY
Overlays are “hardware libraries” that extends the Processing
System with a Programmable Logic design
10. Luca Cerina, R.A. @ NECSTLab – DEIB
WHAT IS JUPYTER
Project Jupyter is an open
source project was born out of
the IPython Project in 2014 as it
evolved to support interactive
data science and scientific
computing across all
programming languages.
Jupyter will always be 100%
open source software, free for
all to use and released under
the liberal terms of the modified
BSD license
11. Luca Cerina, R.A. @ NECSTLab – DEIB
WHAT IS PYTHON
• Python is a tprogramming language
• High level
• Intertpreted
• (weak) Dynamic Tytping
• Object-oriented
We’ll get more on this later
• Useful for fast tprototytping of atptplicatons and with code
readability in mind.
• Documentaton: https://www.tpython.org/doc/
13. Luca Cerina, R.A. @ NECSTLab – DEIB
C vs PYTHON
C
- Low level
- Comtpiled
- Strong tytping
- Non object-oriented
Pythoo
- High level
- Intertpreted
- Weak tytping
- Object-oriented
14. Luca Cerina, R.A. @ NECSTLab – DEIB
C vs PYTHON
C
- Low level
- Comtpiled
- Strong tytping
- Non object-oriented
Pythoo
- High level
- Intertpreted
- Weak tytping
- Object-oriented
Extplicit memory allocaton
(tpointers management)
Imtplicit memory allocaton
(hidden to the user)
15. Luca Cerina, R.A. @ NECSTLab – DEIB
C vs PYTHON
C
- Low level
- Comtpiled
- Strong tytping
- Non object-oriented
Pythoo
- High level
- Intertpreted
- Weak tytping
- Object-oriented
file.cfile.c
gccgcc
Machine codeMachine code
file.tpyfile.tpy
Python intertpreterPython intertpreter
Intertpreted codeIntertpreted code
16. Luca Cerina, R.A. @ NECSTLab – DEIB
C vs PYTHON
C
- Low level
- Comtpiled
- Strong tytping
- Non object-oriented
Pythoo
- High level
- Intertpreted
- Weak tytping
- Object-oriented
int a;
a = 5; //Correct
a = “string”; //Error!!
a = 5 #Correct
a = “stringa” #Correct
a = 1.3 #Correct
Type must be known by the
compiler
No explicit type declaration
17. Luca Cerina, R.A. @ NECSTLab – DEIB
C vs PYTHON
C
- Low level
- Comtpiled
- Strong tytping
- Non object-oriented
Pythoo
- High level
- Intertpreted
- Weak tytping
- Object-oriented
void sort(int * array){...}
...
int vet[] = {1, 6, 4, 8, 9};
sort(vet);
vet = [1, 6, 4, 8, 9]
vet.sort()
sort is a functon of the object vet
and act on it
18. Luca Cerina, R.A. @ NECSTLab – DEIB
Pythoo syotax
• Variables do not need declaraton before usage
• ‘;’ are not necessary to end an instructon line,
• INDENTATION IS FUNDAMENTAL
• Code constructs (if-else, for lootps, etc…)
use ‘:’ + indentaton instead of ‘{‘
Indentaton is done with Tabs or Whitestpaces
• Comments are # (single line) or “”” (multline/docstring)
• INDENTATION IS FUNDAMENTAL
19. Luca Cerina, R.A. @ NECSTLab – DEIB
Exercise 0: Hello world (agaio)
print(“Hello world!”)
No need for I/O library imtport
20. Luca Cerina, R.A. @ NECSTLab – DEIB
Exercise 1: I/O
●
Read a number from command line, and
print if it is odd or even
●
Read a number from command line, add 5 to
it, and then save it in another variable as a
string. Then print it (hints int() and str()
functions)
21. Luca Cerina, R.A. @ NECSTLab – DEIB
Pythoo libraries
• As in C, it is possible to load libraries (modules) to extend
python functionalities
• Modules can be imported in various ways:
imtport os
#imtport namestpace of module os
imtport os as O
#imtport namestpace of module os with an alias O
from os imtport *
#imtport the entre namestpace
from os imtport curdir as CC
from os imtport listdir as LS
#imtport a stpecific element of the module
os.curdir
os.listdir(“Desktotp”)
O.curdir
O.listdir(“Desktotp”)
curdir
listdir(“Desktotp”)
CC
LS(“Desktotp”)
23. Luca Cerina, R.A. @ NECSTLab – DEIB
Utlites
• help(obj) shows the object documentaton (atributes,
functons, behaviour, …)
• len(obj) returns the length of the object Not all objects have a
length!
• dir(obj) list all atributes and functons of obj
• tytpe(obj) returns the tytpe of the object
24. Luca Cerina, R.A. @ NECSTLab – DEIB
Exercise 2: I/O “type” check
●
Read anything from command line, and
verify (print) if the object is numeric,
alphanumeric or alphabetic
●
Read anything from command line, and if it
is alphanumeric, print it in uppercase
25. Luca Cerina, R.A. @ NECSTLab – DEIB
Pythoo basic types
tpi esempio
int 1, 2, 3
float 1.5, 2.2, 4.3
bool True, False
str “abc”, “string”
list [1, 2, 3, 4], [”abc”, “def”, “ghi”]
dict {key1: value1, key2: value2}
tutple (1, 2, 3, 4), (“abc”, “def”, “ghi”)
set {1, 2, 3, 4}, {“abc”, “def”, “ghi”}
List, dict, tutple and sets will be extplained later
26. Luca Cerina, R.A. @ NECSTLab – DEIB
Logical operators
Operaziooi C Pythoo
And logico && and
Or logico || or
Not logico ! not
Uguaglianza ==, != ==, !=, is, is not
Confronto <, >, <=, >= <, >, <=, >=
==, != verify if two objects have
the same value
is, is not verify if two objects are the
same object
27. Luca Cerina, R.A. @ NECSTLab – DEIB
If-else coostruct
• If-else basic structure (REMEMBER INDENTATION):
• Nested if-else constructs can be grouped using elif:
elif
28. Luca Cerina, R.A. @ NECSTLab – DEIB
Exercise 3: Calculator
●
Read two numbers (let’s assume them to be
float)
●
Ask the user the type of calculation to be
done
●
Execute it and print the result
●
Bonus! Allow the user to insert complex
numbers (X+Yj, hint: numpy)
29. Luca Cerina, R.A. @ NECSTLab – DEIB
While loop
• While loop syntax is identical to the C equivalent:
• Con! Python do not provide a do..while loop
• But! It is possible to insert a else branch at the exit of the while
loop
• The else branch is executed when the while condition
becomes False
30. Luca Cerina, R.A. @ NECSTLab – DEIB
Exercise 4: Maximum value
●
Let the user insert a certain number of
positive integers (NB check the type!)
●
Ask the user to continue the insertion of to
stop the loop
●
At the end of the loop print the maximum
value inserted
31. Luca Cerina, R.A. @ NECSTLab – DEIB
For loop
• For loop is different from the C equivalent
• A variable iterates on the elements of a sequence
• A sequence can be a lot of things:
• A list, dictionary or set
• A string
• An iterator
• Also the for loop supports else branch on exit
32. Luca Cerina, R.A. @ NECSTLab – DEIB
Iterators
• Iterators are objects that return a sequence of other objects one element at a
time using the method next()
• The classical iterator in the for loop is range()
• Fine parameter is mandatory, inizio and step are optional:
• Iteration goes from inizio to fine (excluded)
• Default ‘inizio’ is 0
• Default ‘step’ is 1
• ‘Step’ requires that ‘inizio’ is inserted
• If inizio > fine the loop is not executed, unless step is < 0
33. Luca Cerina, R.A. @ NECSTLab – DEIB
Exercise 5: Expooeotal
●
Read one base and one exponent (integer
and positive) and print the exponential.
●
Use both ‘**’ python operator and a for loop
34. Luca Cerina, R.A. @ NECSTLab – DEIB
Exercise 6: PI calculatoo
The PI value can be approximated as:
The integral value is calculated as sum of rectangles. The higher
the number of rectangles, the better the approximation.
Write a Python script that ask the number of intervals to the user,
calculate the PI value and calculate the error against the one
available in the numpy library (use the abs() function to obtain the
error)
35. Luca Cerina, R.A. @ NECSTLab – DEIB
Lists
• Lists are object, with variable dimension, that contains other objects in the
order they were inserted
• Lists can contain objects of diferent tytpe (bags of objects)
• Python-like lists do not exist in C, but C lists allow size extension
C
- Arrays cannot contain diferent
tytpes
- Arrays cannot change their size
Python
- Lists can contain diferent
objects
- A list can change its dimension
36. Luca Cerina, R.A. @ NECSTLab – DEIB
Lists creatoo
• A list can be created using:
• Otperator [ ]
• Functon list() … REMEMBER C reserved names
• Otperator [ ]
• [ ] create an emtpty list
• [val1, val2, val3] create a list
startng from inserted values
• Functon list()
• list() create an emtpty list
• list(iteratore) create a list
using the iterator elements
37. Luca Cerina, R.A. @ NECSTLab – DEIB
Read aod iosert elemeots
• Read
lista[index] like in C, index represents the position of the elements (0-
start counting)
• Insertion
• append(val) insert the element val at the end of the list
• insert(index, val) insert an element in the position index
38. Luca Cerina, R.A. @ NECSTLab – DEIB
Remove elemeots
• Removal
• Pop(index) remove the element index
• remove(val) remove the first occurrence of val
39. Luca Cerina, R.A. @ NECSTLab – DEIB
Traverse the elemeots
• To traverse a list we can use a for-loop like in C
• Or you can iterate directly on the list
• In this case i is the value of every element in the list
40. Luca Cerina, R.A. @ NECSTLab – DEIB
Exercise 7: list maoagemeot
●
Write a program that given a list of integer
numbers, print the list in reverse order
●
Modify the program to save the reversed list
into another list object, then print it
●
Bonus! Do it without using a loop (hint
lookup the list functions)
41. Luca Cerina, R.A. @ NECSTLab – DEIB
Exercise 7: possible solutoos
●
Lists allow negative indexing
●
The function reverse() on the list revert the object itself.
Attention! Reverse is an in-place function and directly
modify the object instead of returning another one
42. Luca Cerina, R.A. @ NECSTLab – DEIB
List coocateoatoo
• You can merge or concatenate two lists using
operator +
• It is possible to replicate a list N times using the
multiplication operator
43. Luca Cerina, R.A. @ NECSTLab – DEIB
Lists of Lists
• A list can be defined inside another list
• To access an element inside you have to access the first level list, and
then the element inside it
44. Luca Cerina, R.A. @ NECSTLab – DEIB
Lists of Lists
• Python matrices can be defined as a list of lists
• The outer list contains the rows of the matrix, the inner ones the
elements of the columns related to that row
• Examtples of matrix creatons
• It is tpossible to create “matrices” with rows of diferent lengths
45. Luca Cerina, R.A. @ NECSTLab – DEIB
List compreheosioo
• List comtprehension is a method that allows to build list in a fast and
comtpressed manner
• A list is created startng from the descritpton writen inside [ ]
• x indicate the value that we want to insert in the list
• The value inserted can be the result of an otperaton, or if conditons
46. Luca Cerina, R.A. @ NECSTLab – DEIB
Teroary operator
• This list comtprehension relies on a ternary otperator, i.e. an otperator
that returns a certain value based on a conditon being true or false
• If cooditoo is true, the outtput of this istructon is value cood_true,
otherwise it is value cood_false
47. Luca Cerina, R.A. @ NECSTLab – DEIB
Exercise 8: list compreheosioo
●
Write a program that given integer N, creates
a matrix with all odd numbers in a row, and
all even numbers in the second row
●
Given two dice, one with N faces, one with M
faces, generate all the possible combinations
(hint: it’s a list of tuples)
●
Given a list of integers, generate a new list
with only the elements > than the average
48. Luca Cerina, R.A. @ NECSTLab – DEIB
Exercise 8: solutoo
●
Combs = [(x,y) for x in range(1,N+1) for
y in range(1, M+1)]
●
Input = [1,2,3,4,5,6,7,8,9,10]
average = sum(Input)/len(Input)
Output = [x for x in Input if x>average]
49. Luca Cerina, R.A. @ NECSTLab – DEIB
Fuoctoos
• Functons are reusable tportons of tprogram, which can be called when
necessary
• A Pythoo functon can receive 0 or more parameters and generate 0 or
more outputs
• Diference between Python and C functons
• WITH GREAT POWER COMES GREAT RESPONSIBILITY!!!
C
- Functons can return at most one
result
- It is necessary to declare the tytpe
of both tparameters and result
- If necessary, it is tpossible to
define the functon tprototytpe
Python
- Functons can return more results
- It is not necessary to declare the tytpe
of either tparameters or result
- Functons are defined/redefined
dynamically: no tprototytpes
50. Luca Cerina, R.A. @ NECSTLab – DEIB
Defoitoo aod call
• To define a functon use the keyword def followed by the functon
name and its intput names (tpay atenton to the ending “:” and code
indentaton!):
• A functon call is executed stpecifying the functon name followed by
the tpossible intputs
• NOTE: at the moment of a functon call, the functon has to be
defined
51. Luca Cerina, R.A. @ NECSTLab – DEIB
Parameters
• Let us distnguish between tparameter tpassage with immutable and mutable types
• Immutable tytpes are tpassed by copy to the functons:
• The functon receives a cotpy of the tparameters
• Changes to the tparameters will not be seen outside the functon
• Mutable tytpes are tpassed by refereoce to the functons:
• The functon receives the reference to the tparameters (like for C arrays)
• Changes to the tparameters are seen outside the functon
Immutable types Mutable types
int list
float dict
bool set
str
tutple
52. Luca Cerina, R.A. @ NECSTLab – DEIB
Returo values
To return a result, it is necessary to use the keyword returo setparatng
the returned values with a comma
53. Luca Cerina, R.A. @ NECSTLab – DEIB
Exercise 9: fuoctoos
●
Write a function that sums all the elements in
a list
●
Write a function that calculates the factorial
of a number
●
Rewrite the integral program (lesson 1) into
a function, and return both integral value and
error to the user
54. Luca Cerina, R.A. @ NECSTLab – DEIB
Dictooaries
• Python dictonaries are a very tpowerful tool that allows to organize data as <key,
value> coutples
• Given a key, it is tpossible to ask the dictonary to tprovide the related value (if it exists)
• Key must be an immutable tytpe (int, float, str, …) while the value may assume any tytpe
• Dictonaries are commonly used to store data associatons:
• Given the first and last name of a tperson (key), retrieve his/her tphone number
(value of iot type)
• Given a class name (key), retrieve the list of teachers who have taught that class
(value of list type)
• Given a city name (key), retrieve the tphone book of that city inhabitants (value
of dictooary type)
55. Luca Cerina, R.A. @ NECSTLab – DEIB
Dictooary creatoo
• A dictonary may be created in two ways:
• {} otperator
• Functon dict()
• Examtples of creaton with {} otperator
• Examtples of creaton with functon dict()
56. Luca Cerina, R.A. @ NECSTLab – DEIB
Add, modify, remove
• To add an element to a dictonary or edit an already existng one, use
square brackets:
• To remove an element from a dictonary startng from its key, use
pop(key):
57. Luca Cerina, R.A. @ NECSTLab – DEIB
Access elemeots
• The number of elements in a dictonary can be obtained using
leo(dictooary)
• To read the value correstponding to a key use square brackets
• To verify whether a key exists or not, use the io otperator:
• Dictonary keys are iterable!
58. Luca Cerina, R.A. @ NECSTLab – DEIB
Classes
• Classes are data structures whose purpose is to contain
different types of variables and functions useful to provide
functionalities related to the kind of data to be represented
• Differently from C struct, classes may also contain functions
• An instance of a class is called object
C Python
Declaraton of
variables or functons
59. Luca Cerina, R.A. @ NECSTLab – DEIB
Namespace
• When a class (or a function) is created, the declared
variables/functions lay within the space of names (namespace)
generated for that class/function
• The namespace is a mapping from names to objects (like a
dictionary) that allows to invoke both the attributes and functions
defined within that namespace
• For instance, when the Python interpreter starts, some functions
are already available inside the initial namespace, like print()
• Is it possible to add functions/attributes and other namespaces
to a namespace through import command
60. Luca Cerina, R.A. @ NECSTLab – DEIB
Scopes
• The scope is a textual region of a Python program where it is
possible to directly invoke attributes/functions of a namespace
• Attributes/functions of a class can be directly called only within
the class itself, while, from the outside, it is necessary to use
an object of the class to call them (through “.” operator)
• Within a scope, it is also possible to redefine
attributes/functions defined in outer scopes
61. Luca Cerina, R.A. @ NECSTLab – DEIB
Scope example
global var var redefined by
test_scope
Through global,
test_scotpe edits var
62. Luca Cerina, R.A. @ NECSTLab – DEIB
Class defoitoo
• In order to define a class, the keyword class is required:
class className:
• Within the class definition, it is possible to declare attributes
and functions
self tparameter is a reference to the class
itself from within the class
Object creaton
self has not to be tpassed as argument when
invoking class functons
63. Luca Cerina, R.A. @ NECSTLab – DEIB
Class defoitoo with __ioit__
• It is possible to define within a class a special function called
__init__ whose purpose is to initialize class attributes during
its creation
• The attributes have not to be previously declared
i, a and b were not declared yet
The values of a and b have to be
tpassed during object creaton
64. Luca Cerina, R.A. @ NECSTLab – DEIB
Exercise 11: class creatoo
●
Write a class rectangle with two attributes
(one per side)
●
Define a function that returns the rectangle’s
area
●
Define a function that returns the rectangle’s
perimeter
65. Luca Cerina, R.A. @ NECSTLab – DEIB
Boous exercises
Write a class Roman that:
●
Given an integer number returns its roman
numeral
Write a class Gray that:
●
Given a binary number, with fixed length
(known at init) returns its Gray
representation
●
Gray code:
http://mathworld.wolfram.com/GrayCode.html
66. Luca Cerina, R.A. @ NECSTLab – DEIB
Class ioheritaoce
• A class can may be created starting from another class
already existing and more generic
• The new class inherits all the attributes and functions defined
in the parent class
• Inheritance is used to specialize a class with respect to a
generic one
• In order to inherit from a parent class, the syntax is:
class childClass(parentClass):
67. Luca Cerina, R.A. @ NECSTLab – DEIB
Example
Class the child inherits from
pass is used to avoid to stpecify
the imtplementaton of a class,
functon, if etc.
68. Luca Cerina, R.A. @ NECSTLab – DEIB
Overridiog
• Overriding is used to redefine, within a child class, functions
already defined by the parent class, in order to make them
more specify for the child class
• To apply overriding, it is enough to redefine a function using
the same name
• Usually overriding is applied to __init__ constructor function
69. Luca Cerina, R.A. @ NECSTLab – DEIB
Example
Overriding of __init__
functon
Functon priotVal only belongs
to childClass, it cannot be called
by tparentClass
70. Luca Cerina, R.A. @ NECSTLab – DEIB
Exercise 12: class ioheritaoce
●
Given the class Rectangle, inherit a class
Rombus that calculates its area and
perimeter accordingly (define PI inside the
class or use Numpy)
71. Luca Cerina, R.A. @ NECSTLab – DEIB
Files
• Python provides many functionalities to act on files
• In particular, it allows to:
• Open,
• Read,
• Write,
• Close a file
• I/O functions documentation is available here:
https://docs.python.org/3/tutorial/inputoutput.html
72. Luca Cerina, R.A. @ NECSTLab – DEIB
Files: opeo aod close
• Open file
f = open(filename, mode)
• Close file f.close()
File name Otpen modes:
‘r’: reading
‘w’: writng(it deletes the tprevious content)
‘x’: creates a new file to write it
‘a’: atptpend
‘b’: binary mode
‘t’: textual mode
‘+’: otpen a file to utpdate it
73. Luca Cerina, R.A. @ NECSTLab – DEIB
Files: read aod write
• Read file
out = f.read(size)
out = f.readline()
• Write file
f.write(stringa)
Reads size characters
If omited, it reads to the
end of file
Reads a file row
Writes a string on the file
Therefore, it is necessary to convert
data into strings to write them
74. Luca Cerina, R.A. @ NECSTLab – DEIB
Files: seek aod tell
• Current position on file
out = f.tell()
• Change position on file
f.seek(offset, from_where)
Returns the current tpositon inside
the file
Ofset: character ofset with
restpect to a reference tpoint
From_where: reference tpoint
Se 0: file beginning (default value)
Se 1: current tpositon
Se 2: file end
75. Luca Cerina, R.A. @ NECSTLab – DEIB
Numpy
• NumPy is the abbreviation of Numerical Python: it is a Python
extension mainly thought for scientific computation
• NumPy allows to use (in addition to other things):
• Multidimensional arrays in a easier way with respect to Python
• Mathematical functions (linear algebra, random numbers, …)
• To use NumPy, it is necessary to import its module:
• Documentation: http://docs.scipy.org/doc/
76. Luca Cerina, R.A. @ NECSTLab – DEIB
odarray
• ndarray is a NumPy data type that allows to create n-dimensional
arrays
• The easiest way to create a NumPy array is array function:
array(object, dtype=None, copy=1, order=None)
Parameters already set to a default value
It is not necessary to insert them unless their values have to be changed
77. Luca Cerina, R.A. @ NECSTLab – DEIB
odarray
• ndarray is a NumPy data type that allows to create n-dimensional
arrays
• The easiest way to create a NumPy array is array function:
array(object, dtype=None, copy=1, order=None)
Parameters already set to a default value
It is not necessary to insert them unless their values have to be changed
78. Luca Cerina, R.A. @ NECSTLab – DEIB
odarray
array(object, dtype=None, copy=1, order=None)
• object: the object the array has to be created from (list, tuple,
etc.)
• dtype: the array data type (bool, int, float, complex, etc.)
• copy: indicates whether the array is created through a copy of
the object
• order: memory allocation style (C or Fortran)
79. Luca Cerina, R.A. @ NECSTLab – DEIB
odarray atributes
• shape: array shape
!! pure monodimensional arrays have shape (N, )
not (N, 1)
• ndim: array dimensions number
monodimensional arrays have ndim = 1
• itemsize: byte dimension of each element
• strides: bytes to jump to obtain the next element
for a specific dimension
80. Luca Cerina, R.A. @ NECSTLab – DEIB
Other creatoo methods
• zeros( shape, dtype=float, order =‘C’ )
• ones( shape, dtype=None, order =‘C’ )
• empty( shape, dtype=None, order =‘C’ )
81. Luca Cerina, R.A. @ NECSTLab – DEIB
Other creatoo methods
• identity( n, dtype=None )
• eye( N, M=None, k=0, dtype=float )
• k indicates how much to translate the main diagonal
• k > 0: diagonal translated k positions right
• k < 0: diagonal translated k positions left
82. Luca Cerina, R.A. @ NECSTLab – DEIB
Araoge aod liospace
• Just like a list may be created from range, it is possible to create an
array with two similar functions: arange and linspace
• arange is very similar to range:
arange( [start,] stop[, step,], dtype=None )
• linspace generates a sequence of num values equally distributed
from start to stop
linspace( start, stop, num=50, endpoint=True, restep=False )
• endpoint: if True, stop is the last value
• restep: if True, the function returns also the step
optional Diferently from range(), float
stetps are accetpted
83. Luca Cerina, R.A. @ NECSTLab – DEIB
Reshape aod resize
• Reshape and resize functions allow to change
the shape of the array and resize it
reshape(shape)
• Reshape creates/returns a new data structure
redistributing array elements (the number of
elements does not change)
!!Not an inplace function
resize(new_shape)
• Resize works in-place modifying the array
itself
84. Luca Cerina, R.A. @ NECSTLab – DEIB
Exercise 13: array creatoo
Write a Python program that, given in input a bidimensional shape,
creates:
• A sequence of values coherent with that dimension
• A monodimensional array starting from the sequence
• A bidimensional array whose shape corresponts to the one
inserted by the user
• Example:
• Shape = (2,3)
• Sequence = 0, 1, 2, 3, 4, 5
• Monodimensional_array = [0, 1, 2, 3, 4, 5]
• Bidimensional_array = [[0, 1, 2], [3, 4, 5]]
85. Luca Cerina, R.A. @ NECSTLab – DEIB
Array sliciog
• It is possible to access to portions of a list and/or array
through slicing operator “:”
Array[start:end]
• start: index of the first element to start from
– It may be omitted if equal to 0
• end: index of the last element to arrive
– The element is not included in slicing output
– It may be omitted if it correspond to the array end
86. Luca Cerina, R.A. @ NECSTLab – DEIB
Array sliciog
• It is possible to apply slicing also on multidimensional arrays
(but not on lists!!)
array[startDIM1:endDIM1, startDIM2:endDIM2, etc.]
00 11 22 33 44 55
66 77 88 99 1010 1111
1212 1313 1414 1515 1616 1717
87. Luca Cerina, R.A. @ NECSTLab – DEIB
Array operators
Array / scalar operations: array / array operations:
a e b must have the same dimensions!!
89. Luca Cerina, R.A. @ NECSTLab – DEIB
Matplotlib
• Matplotlib library provides functionalities to plot 2D graphs using
functions similar to MATLAB
• matplotlib contains different sub-modules, in particular we will refer
to pyplot
• Documentation: http://matplotlib.org/
Stpecial Jutpyter directve to
show gratphs within the working
area
Imtport namestpace
mattplotlib.tpytplot as “tplt”
Examtple of a tpytplot functon
to create a gratphShow gratph
90. Luca Cerina, R.A. @ NECSTLab – DEIB
Create a graph
• To create a graph, define a set of values to be drawn with plot
and then visualize the graph with show
• plot function may be called in different ways
plot(y_values_list)
plot(x_values_list, y_values_list)
plot(x_values_list, y_values_list, line_properties)
NOTE: lists may be substituted by NumPy arrays
91. Luca Cerina, R.A. @ NECSTLab – DEIB
example
X axis values are
automatcally defined in
an incremental order
startng from 0
92. Luca Cerina, R.A. @ NECSTLab – DEIB
example
Y values list
X values list
Note: the dimensions of the
two lists must coincide!
93. Luca Cerina, R.A. @ NECSTLab – DEIB
Multple lioe graphs
By calling multiple times plot function, it is possible to insert more
curves inside the same graph
95. Luca Cerina, R.A. @ NECSTLab – DEIB
Exercise 14:
Write a Python program that, given a frequency and a certain time
window (e.g. 2,10 s):
●
Create a sinusoid at given frequency in the time window and plot it
●
Create a sinusoid with a frequency 10% higher
●
Sum the two sinusoids and plot it in another figure.
●
Observe the phenomen ;) (hint: acoustic battimento)