In [3]:
import numpy as np

import urllib    # for reading information from a URL

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
In [2]:
%matplotlib notebook   

Reading a white-space delimited data file

Download the file test1.dat from PHYS 310 website. Here's what's in the file:

# This line is a comment
#
#t x y
# ============
1.2 2.3 3.2
2.2 4.6 6.1
3.0 5.9 9.1

The file is in the format of a typical data file. Each line might be something like $(t,x,y)$.

Note that by default loadtxt ignores any lines in the data file that begin with the # character. (This can be changed.)

In [4]:
a = np.loadtxt("test1.dat")
a
Out[4]:
array([[1.2, 2.3, 3.2],
       [2.1, 4.6, 6.1],
       [3. , 5.9, 9.1]])

It's often useful to break the data into single arrays for $t$, $x$, and $y$. One way to do this is with the transpose of a:

In [5]:
a.T
Out[5]:
array([[1.2, 2.1, 3. ],
       [2.3, 4.6, 5.9],
       [3.2, 6.1, 9.1]])
In [6]:
t, x, y = a.T
In [7]:
t
Out[7]:
array([1.2, 2.1, 3. ])

or loadtxt can get the columns of the data file directly:u

In [8]:
t, x, y = np.loadtxt("test1.dat", unpack=True)

Reading a comma delimited, or comma separated value (CSV) data file

Here's a copy of test2.csv

# This line is a comment
#
#t x y
# ============
, 1, 2, 3
comment in column 0, 2, 4, 6
, 3, 9, 27

In [9]:
b = np.loadtxt("test2.csv", delimiter = ',', usecols = (1,2,3), unpack = True)
b
Out[9]:
array([[ 1.,  2.,  3.],
       [ 2.,  4.,  9.],
       [ 3.,  6., 27.]])

Writing an array to a whitespace delimited file

In [10]:
c = 2*a
c
Out[10]:
array([[ 2.4,  4.6,  6.4],
       [ 4.2,  9.2, 12.2],
       [ 6. , 11.8, 18.2]])
In [11]:
np.savetxt('testout1.dat', c, header='sample header (optional)' )

Retrieve a data file from a URL

np.loadtxt() has now been upgraded to read directly from a URL:

In [12]:
link = 'http://www.eg.bucknell.edu/~phys310/jupyter/test1.dat'
f = urllib.request.urlopen(link)
data = np.loadtxt(f)
print(data)
[[1.2 2.3 3.2]
 [2.1 4.6 6.1]
 [3.  5.9 9.1]]

Retrieve and display a JPG image

Retrieve file from URL and create copy in local filesystem

In [13]:
urllib.request.urlretrieve(' http://www.atlasoftheuniverse.com/nebulae/m42.jpg','orion.jpg')
Out[13]:
('orion.jpg', <http.client.HTTPMessage at 0x7f5530742490>)

Display an image from local filesystem

In [14]:
img = mpimg.imread('orion.jpg')

plt.figure()
plt.imshow(img);

Version Information

version_information is from J.R. Johansson (jrjohansson at gmail.com); see Introduction to scientific computing with Python for more information and instructions for package installation.

version_information is installed on the linux network at Bucknell

In [15]:
%load_ext version_information
In [16]:
%version_information numpy, matplotlib
Out[16]:
SoftwareVersion
Python3.7.7 64bit [GCC 7.3.0]
IPython7.16.1
OSLinux 3.10.0 1062.9.1.el7.x86_64 x86_64 with centos 7.7.1908 Core
numpy1.18.5
matplotlib3.3.0
Fri Aug 07 15:11:32 2020 EDT
In [ ]: