Python Lesson 5
Lesson outline
Input and Output: dealing with files in Python and with NumPy
More on NumPy
More on Graphics
Exercises
Writing and Reading data from files
We first explain the basics of file reading and writing in native Python and then move into the more specialized NumPy functions, better for dealing with data arrays.
File access in native Python
Using the native Python function open
(with an absolute or a relative trajectory with respect to the notebook active directory) and the method close
allows to set a filehandle. By default files are opened in the r
mode (readonly).
You can treat the filehandle as an iterator and build a loop. In this case the number of characters in each line is printed
It is important to close the filehandle once finished with it to return resources to the processor.
The usual form to open files makes unnecessary the last step, and once the file is dealt with it is automatically closed
We are reading each line, removing the trailing spaces and carriage return into a list using a list comprehension.
The complete syntax for open would be open(path, mode)
and the major modes are:
mode
r
: Default mode. Read only.mode
w
: Write only. Beware, it deletes an existing file and overwrites it.mode
x
: Write only. It exits if the file exists.mode
a
: Write only. Append to the file if it exists.mode
r+
: Read and Write.mode
b
: add to the mode for binary files. E.g. "rb", "ab"…
The write
and writelines
methods allow to write into a filehandle. If, for example, we want to read a file and save it stripping the first and last lines we can run
The most commonly used native Python file methods are
read([size]): Read data from file, with optional argument of the number of bytes to read. The method returns the specified number of bytes from the file. Default is -1 which means the whole file.
readlines([size]): Return list of lines from file, with optional argument of the number of bytes to read.
write(str): Write string to file.
writelines(strings): Write list of lines to file.
close(): Close the filehandle.
flush(): Flush the internal buffered I/O to the disk.
seek(pos): Move to position
pos
in the file.tell(): Tell the current position in the file.
closed:
True
if the filehandle is closed.
File access with NumPy
We have already used the NumPy function loadtxt
that, together with savetxt
, allows to load and save data to text files. For example
These functions are specially handy for reading csv
and tsv
data files
But using the load
and save
functions you can also save an array in binary format -saving cpu, time, and precision at the cost of not being able to open/edit the file- with standard suffix npy
.
With the function savez
you can also save multiple arrays in an npz
file that is not a compressed file. If you want to compress the data use the function savez_compressed
Once you read them they are loaded into a hash-like NumPy object with the array argument names as keys
To improve portability, and especially when you read several files in your code, and probably in different code sections, it is considered a good practice to define variables for your home and data folders and then use the variables to define the path when needed. This improves the readability of your code and helps its maintenance. A possible example, using the dataset provided at the beginning of the course is the following:
Saving Python objects with pickle
pickle
Pickling is used to save Python objects into a filesystem; lists, dictionaries, class objects, and more can be saved as a pickle file. Strictly speaking, pickling is the serializing and de-serializing of python objects to a byte stream. The opposite is unpickling.
This methodology is called serialization, marshalling, or flattening in other programming languages. Pickling is most useful when performing routine tasks on massive datasets or when you want to store, after sometimes massive calculations, a given Python object.
Once you import the pickle
library, to save and load objects one makes use of the pickle.dump
and pickle.load
combined with the right filehandles. You can make this with the following two functions
We can try saving a hash
More on NumPy
The vectorization provided by NumPy is a great advantage when dealing with large datasets and the computing times required are at least an order of magnitude less than the equivalent times for interpreted code alternatives.
We illustrate this with a simple example, plotting the 3D function f(x,y) = np.exp(-xs ** 2 - ys ** 2)*xs**2*ys
as a heatmap
We plot the figure as a heatmap in the XY plane
Another powerful NumPy feature, already presented in Lesson 2, is the possibility of Boolean indexing. This is specially adequate when combined with the NumPy function np.where
, a vectorized version of the standard Python ternary expression. The syntax for this function is np.where(condition, Array_A, Array_B)
. When condition is True
the corresponding element of Array_A
is selected, the one of Array_B
otherwise. In a previous example we replaced positive and negative values of a random array by one and minus one, respectively. This can be very conveniently done using np.where
You could also replace only negative values by -1
As you can see we can replace arr_A
or arr_B
by scalars. Avoiding the use of scalars, if we have two arrays and depending on the sign of a third array we can choose elements from one or the other.
There are a set of statistical and mathematical functions available in NumPy, we quickly outline the main ones, applying them to a GOE matrix (Gaussian Orthogonal Ensamble, real and symmetric random matrices). We first define the matrix as a matrix of random normally distributed numbers with zero mean and unity variance, and then add it to its transpose, to get a symmetric matrix
We can now compute the mean and standard deviation of the full array or for the diagonal
We already know that the option axis
allows for limiting the calculation to rows or columns (or a given index in a multi index array)
Other useful functions are cumsum
and cumprod
for cumulative addition and product
Finally another useful NumPy methods are min
(argmin
) and max
(argmax
)
The indices are provided for a flattened array, if you need the row and column index values this can be obtained using the np.unravel_index
function
You can sort values using the np.sort
function or the sort
method. There is a basic difference between these two. The function provides a sorted copy of the original array, while the method performs an in-place sort, without data copying.
Numpy also provides basic linear algebra functions, e.g. you can compute the trace of a matrix
You can also calculate the product of two matrices with the dot
or matmul
method or function. Both provide the same result in the case of 2D array multiplication
There are two main differences between these two functions. On the first hand multiplication by scalars is not allowed with matmul
(use *
instead). On the second hand, when dimension is larger than two, in the matmul
case the operation is broadcasted together as if the matrices were elements residing in the last two indexes, respecting the signature (n,k),(k,m)->(n,m)
. In the dot
case it is a sum product over the last axis of first matrix and the second-to-last of the second matrix
In the case of two vectors, matmul
provides the inner product (without taking complex conjugate)
In Python 3.5 the @
symbol works as an infix operator for matrix multiplication
In np.linalg
several functions of linear algebra are found.
det
: Matrix determinanteigvals
: Eigenvalues of a square matrixeig
: Eigenvalues and eigenstates of a square matrixeigvalsh
: Eigenvalues of a symmetric or Hermitian square matrixeigh
: Eigenvalues and eigenstates of a symmetric or Hermitian matrixinv
: Inverse of a square matrixpinv
: Compute the Moore-Penrose pseudo-inverse of a matrix.qr
: Compute the QR decomposition.svd
: Compute the singular value decomposition (SVD).solve
: Solve the linear systemAx = b
forx
, whereA
is a square matrix.lstsq
: Compute the least-squares solution toAx = b
.
For example
NumPy is also very efficient in pseudorandom number generation as it also applies vectorization techniques. The function np.random.randn
generates arrays of random numbers from a standard normal distribution (zero mean and unity standard deviation) but you can draw numbers from a Gaussian with any other mean or standard deviation making use of the np.random.normal
function
Instead of the NumPy option, you could have used the normalvariate
function in random
library, but the lack of vectorization makes this approach far slower for large datasets. We can benchmark them
Notice that, depending on the system, the gain can be as large as one order of magnitude. Notice also that in the list comprehension we have used the conventional name for the loop variable in case the variable is not used in the loop body: _
.
These numbers are called pseudorandom as they are not true random numbers and are derived through a deterministic algorithm that makes use of a seed value. To check or replicate your results you can fix the seed value
This is a global random seed value, you can also create different pseudorandom number generators isolated from each other
Other available functions provided in np.random
are
permutation
: Return a random permutation of a sequence, or return a permuted rangeshuffle
: Randomly permute a sequence in-placerand
: Draw samples from a uniform distributionrandint
: Draw random integers from a given low-to-high rangerandn
: Draw samples from a normal distribution with mean 0 and standard deviation 1 (MATLAB-like interface)binomial
: Draw samples from a binomial distributionnormal
: Draw samples from a normal (Gaussian) distributionbeta
: Draw samples from a beta distributionchisquare
: Draw samples from a chi-square distributiongamma
: Draw samples from a gamma distributionuniform
: Draw samples from a uniform [0, 1) distribution
More on Graphics
We are going to elaborate on a seemingly neverending topic. You can find the complete Matplotlib documentation in https://matplotlib.org/3.1.1/index.html. We will cover some basic aspects with examples. Now, let's load the library and create some data to display and learn some useful techniques
Let's first create a plot with a single panel. The recommended way is using subplot
without arguments, as follows
We have customized the x
and y
axis labels, the plot title and included a legend. There are several ways of plotting various curves in the same panel. The easiest one is to run one plot instance for each curve, as in the example that follows
We will later see other ways of plotting several curves. We can customize the style of the line and include symbols in the points in the plot command using one of the set of Line 2D properties. For example
c
orcolor=/color/: Control line color. Possible color abbreviations:{'b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'}
. You can also use colors from the xkcd color name survey with the prefixxkcd:
or an RGB or RGBA (red, green, blue, alpha) tuple of float values or hex string.alpha=/float/: Set the alpha value used for blending. This is not supported on all backends.ls
orlinestyle
: Control line style. Possible options:{'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
.lw
orlinewidth
float: Control linewidth.marker
markerstyle: Control marker style. For possible options check Matplotlib Markers.markersize
orms
float: Control marker size in points.markevery
None or int or (int, int) or slice or List[int] or float or (float, float): Control markers display
In this example we use some of these parameters
As already mentioned in the exercises of Lesson 2, you can also depict data using the pyplot.scatter
function and another useful tool is the pyplot.bar
. Let's try these two. We can try scatter
with the previous function
And we can plot the squared components of two GOE arrays eigenvectors as a bar plot. In this case we fix the figure width and height using the figsize
option in subplots
(default units are inches, you can change to cm
using a conversion factor cm = 1/2.54
).
You can also include insets into the plot. A simple way is declaring a new axis in the figure, you can provide in unitless percentages of the figure size the position of the new axis -(0,0 is bottom left)- and the width and height of the inset.
You can get a finer control using the inset_axes
function
Subplots
If we need to add several subplots we can do it as we did in Lesson 2, but we can also make use of loops to automatize the task. Imagine that we need to plot the previous function np.cos(x_data**A)/np.cosh(x_data/B)
for (A,B) = {(1,2),(1,5),(2,2),(2,5),(3,2),(3,5)}
. We can use subplots as follows
You can also plot several lines in each subplot
As all the panels share the same axis scaling you can only add ticks to the outer panels
Histograms
To generate 1D histograms a data vector is needed. We create one with the eigenvalues of a GOE array. We can create the array using a randn
, a convenience function for users porting Matlab
code
But it is preferred to use the default_rng
to get a new instance of a Generator
, and then call its methods to obtain different distribution samples. You can find an quick reference to random numbers in NumPy in this link. In the present case, for normally distributed random data
We can then plot the histogram, taking into account that the hist
method returns as an output the number associated to each bin, the bins, and a set of patches that allows to operate on the histogram. In the left panel we display the absolute histogram while in the right one we normalize by the total number of counts and display a percentage.
You can combine a histogram with a plot. Let's plot the value of the theoretical GOE level density (a semicircle). Let's first compute it
We now make use of the information about the bins in the output of hist
.
To plot a 2D histogram, one only needs two data vectors of the same length, corresponding to each axis of the histogram.
It is not mandatory, but one can also define the plot bins
The histogram is computed as
And it can be depicted using imshow
or meshgrid
Saving your figures
You should save a script to easily recreate any of your figures, but you can also save them in a graphic format. The available formats depend on your Python distribution. To know them run
To save a figure you can issue the command
If you want to further modify the figure in a program as inkscape or xfig you can save the figure as svg
file -vector graphics- but in this case, when you import the matplotlib
library, you should run the following statement
And now you can save the figure of your interest
The savefig
command accepts some options that are quite useful:
dpi: Figure resolution in dots-per-inch. Default value is 100.
facecolor: Color of the background. Default value
w
, white.edgecolor: Color of the figure edge line. Default value
w
, white. Notice that in this case the figurelinewidth
option needs to be set to a value different from the null default one.bboxinches: Portion of the figure saved. The value
trim
attempts to trim empty white space around the figure.
Some of these options are used in the second savefig
command in the previous example.
Optimizing and function fitting with SciPy
.
SciPy
.The ScyPy
library provides many user-friendly and efficient numerical routines, such as routines for numerical integration, interpolation, optimization, linear algebra, and statistics. In this course we will only very briefly explain how to use it to perform linear and non-ĺinear data fittings. You can find more information about this useful library in its documentation.
In a linear fit case you should import the Scipy
module stats
.
We consider that we have a data set that we suspect it follows the functional law f(N) = a*N**b. Let's first prepare our dataset and add to it a normal error.
The dependence is not linear but we can transform it into a linear dependence taking logarithm of both abscyssa and ordinate values
The obtained result provides the straight line slope and intercept values, the correlation coefficient (rvalue
), the p-value of the fit, and the coefficient errors. We can depict the data plus errors and the best fit line
In case you cannot linearize your function dependence, as in the next example, you import the optimize
module.
We now prepare our dataset and add again a random normal error.
You now define the function that will be used to perform the nonlinear fit
And the fit can be performed now as follows
The array pcov
is the covariance matrix and therefore the parerr
vector is the vector that contains the error of the obtained parameters. We can plot the original values and the resulting optimized function.
Exercises
Exercise 5.1: The Caesar's cipher is a historically relevant way of encrypting messages, already used by Julius Caesar, that is a substitution cipher. Given an integer value m, any character is replaced by the character found shifting the original character by m positions in the alphabet. Prepare a function that encrypts or decrypts a given message (assuming we only use the 26 capital letters of the English alphaber and replacing other symbols that are not letters by themselves, e.g. spaces and punctuation symbols) using a given value of m. Hints: (1) You can transform a string in uppercase characters using the
upper()
method (up_strin = orig_string.upper()
). (2) You can obtain the English ascii uppercase letters using the modulestring
(import string
) with the commandABC = string.ascii_uppercase
.Exercise 5.2: The NIST Digital Library of Mathematical Functions (DLMF) is a very useful site, where you can find an updated and expanded version of the well-known reference Handbook of Mathematical Functions compiled by Abramowitz and Stegun. Define a function to compute the Bessel function of the first kind of integer index from the series 10.2.2 in the DLMF, add a docscript and plot the functions of order 0, 1, and 2 in the interval of x between 0 and 10.
Exercise 5.3: Define and test a function that estimates the value of the special constant pi by generating N pairs of random numbers in the interval -1 and 1 and checking how many of the generated number fall into a circumference of radius 1 centered in the origin. Improve the function showing in a graphical output the square, the circumference, and the points inside and outside the circumference with different colors.
Exercise 5.4: The aim of this exercise is to generate a set of two-dimensional random walks, plot their trajectories and look and the end point distribution. The random walks considered always begin at the origin and take Nstep random steps of unit or zero size in both directions in the x and y axis. For a total number of Nw walks:
Compute the trajectories and save the final point of all of them.
Plot a sample of these random walks in the plane.
Plot all the final points together.
Compute the average distance of the final points from the origin.
Plot a histogram with the values of the distance to the origin.
Exercise 5.5: The Julia set is an important concept in fractal theory. Given a complex number a, a point z in the complex plane is said to be in the filled-in Julia set of a function f(z) = z² + a if the iteration of the function over the point does not finish with the point going to infinity. It can be proved that, if at some iterate of a point under f(z) the result has a module larger than 2 and larger than the module of a, this point will finish going to infinity. Build and plot the filled-in Julia sets for f(z) with a = (-0.5,0),(0.25,-0.52), (-1,0), (-0.2, 0.66) in the interval of -1 < Re(z), Im(z) < 1 and consider that the point belongs to the set once the previous condition has not been accomplished after Niter = 100. Hint: You can make use of the NumPy
meshgrid
and the PyPlotpplot
functions for displaying the filled-in Julia sets.
Last updated